Big purge of base

- Delete AtExit, FilePathWatcher, MemoryMappedFile, MessageLoop,
  TaskScheduler, most of threading/
- Delete third_party/libevent, third_party/dmg_fp (this makes the json
  reader not-exactly-json any more because it doesn't support doubles, but
  GN already disallowed doubles.)
- Add src/msg_loop.*.

After all the deleting and mucking around, a simple perf comparison
against the current in-tree Chrome gn:

c:\src\gn>python build\full_test.py \src\cr\src out\wi\gn.exe
ninja: Entering directory `out'
ninja: no work to do.
[430/430] XmlElementWriter.TestXmlEscape
PASSED
Confirming output matches...
Comparing performance... (takes a while)
In-tree gn avg: 13.522s
Our gn avg: 11.822s

This isn't rock-solid, but it seems like it's at least not slower.

Change-Id: Id956ffdbb909b1398465098d349b57e10589b27d
Reviewed-on: https://gn-review.googlesource.com/1600
Commit-Queue: Scott Graham <scottmg@chromium.org>
Reviewed-by: Brett Wilson <brettw@chromium.org>
diff --git a/base/at_exit.cc b/base/at_exit.cc
deleted file mode 100644
index 52c2151..0000000
--- a/base/at_exit.cc
+++ /dev/null
@@ -1,109 +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 "base/at_exit.h"
-
-#include <stddef.h>
-#include <ostream>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/logging.h"
-
-namespace base {
-
-// Keep a stack of registered AtExitManagers.  We always operate on the most
-// recent, and we should never have more than one outside of testing (for a
-// statically linked version of this library).  Testing may use the shadow
-// version of the constructor, and if we are building a dynamic library we may
-// end up with multiple AtExitManagers on the same process.  We don't protect
-// this for thread-safe access, since it will only be modified in testing.
-static AtExitManager* g_top_manager = nullptr;
-
-static bool g_disable_managers = false;
-
-AtExitManager::AtExitManager()
-    : processing_callbacks_(false), next_manager_(g_top_manager) {
-// If multiple modules instantiate AtExitManagers they'll end up living in this
-// module... they have to coexist.
-#if !defined(COMPONENT_BUILD)
-  DCHECK(!g_top_manager);
-#endif
-  g_top_manager = this;
-}
-
-AtExitManager::~AtExitManager() {
-  if (!g_top_manager) {
-    NOTREACHED() << "Tried to ~AtExitManager without an AtExitManager";
-    return;
-  }
-  DCHECK_EQ(this, g_top_manager);
-
-  if (!g_disable_managers)
-    ProcessCallbacksNow();
-  g_top_manager = next_manager_;
-}
-
-// static
-void AtExitManager::RegisterCallback(AtExitCallbackType func, void* param) {
-  DCHECK(func);
-  RegisterTask(base::Bind(func, param));
-}
-
-// static
-void AtExitManager::RegisterTask(base::Closure task) {
-  if (!g_top_manager) {
-    NOTREACHED() << "Tried to RegisterCallback without an AtExitManager";
-    return;
-  }
-
-  AutoLock lock(g_top_manager->lock_);
-  DCHECK(!g_top_manager->processing_callbacks_);
-  g_top_manager->stack_.push(std::move(task));
-}
-
-// static
-void AtExitManager::ProcessCallbacksNow() {
-  if (!g_top_manager) {
-    NOTREACHED() << "Tried to ProcessCallbacksNow without an AtExitManager";
-    return;
-  }
-
-  // Callbacks may try to add new callbacks, so run them without holding
-  // |lock_|. This is an error and caught by the DCHECK in RegisterTask(), but
-  // handle it gracefully in release builds so we don't deadlock.
-  base::stack<base::Closure> tasks;
-  {
-    AutoLock lock(g_top_manager->lock_);
-    tasks.swap(g_top_manager->stack_);
-    g_top_manager->processing_callbacks_ = true;
-  }
-
-  // Relax the cross-thread access restriction to non-thread-safe RefCount.
-  // It's safe since all other threads should be terminated at this point.
-  ScopedAllowCrossThreadRefCountAccess allow_cross_thread_ref_count_access;
-
-  while (!tasks.empty()) {
-    base::Closure task = tasks.top();
-    task.Run();
-    tasks.pop();
-  }
-
-  // Expect that all callbacks have been run.
-  DCHECK(g_top_manager->stack_.empty());
-}
-
-void AtExitManager::DisableAllAtExitManagers() {
-  AutoLock lock(g_top_manager->lock_);
-  g_disable_managers = true;
-}
-
-AtExitManager::AtExitManager(bool shadow)
-    : processing_callbacks_(false), next_manager_(g_top_manager) {
-  DCHECK(shadow || !g_top_manager);
-  g_top_manager = this;
-}
-
-}  // namespace base
diff --git a/base/at_exit.h b/base/at_exit.h
deleted file mode 100644
index e74de8d..0000000
--- a/base/at_exit.h
+++ /dev/null
@@ -1,80 +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_AT_EXIT_H_
-#define BASE_AT_EXIT_H_
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/containers/stack.h"
-#include "base/macros.h"
-#include "base/synchronization/lock.h"
-
-namespace base {
-
-// This class provides a facility similar to the CRT atexit(), except that
-// we control when the callbacks are executed. Under Windows for a DLL they
-// happen at a really bad time and under the loader lock. This facility is
-// mostly used by base::Singleton.
-//
-// The usage is simple. Early in the main() or WinMain() scope create an
-// AtExitManager object on the stack:
-// int main(...) {
-//    base::AtExitManager exit_manager;
-//
-// }
-// When the exit_manager object goes out of scope, all the registered
-// callbacks and singleton destructors will be called.
-
-class BASE_EXPORT AtExitManager {
- public:
-  typedef void (*AtExitCallbackType)(void*);
-
-  AtExitManager();
-
-  // The dtor calls all the registered callbacks. Do not try to register more
-  // callbacks after this point.
-  ~AtExitManager();
-
-  // Registers the specified function to be called at exit. The prototype of
-  // the callback function is void func(void*).
-  static void RegisterCallback(AtExitCallbackType func, void* param);
-
-  // Registers the specified task to be called at exit.
-  static void RegisterTask(base::Closure task);
-
-  // Calls the functions registered with RegisterCallback in LIFO order. It
-  // is possible to register new callbacks after calling this function.
-  static void ProcessCallbacksNow();
-
-  // Disable all registered at-exit callbacks. This is used only in a single-
-  // process mode.
-  static void DisableAllAtExitManagers();
-
- protected:
-  // This constructor will allow this instance of AtExitManager to be created
-  // even if one already exists.  This should only be used for testing!
-  // AtExitManagers are kept on a global stack, and it will be removed during
-  // destruction.  This allows you to shadow another AtExitManager.
-  explicit AtExitManager(bool shadow);
-
- private:
-  base::Lock lock_;
-  base::stack<base::Closure> stack_;
-  bool processing_callbacks_;
-  AtExitManager* next_manager_;  // Stack of managers to allow shadowing.
-
-  DISALLOW_COPY_AND_ASSIGN(AtExitManager);
-};
-
-#if defined(UNIT_TEST)
-class ShadowingAtExitManager : public AtExitManager {
- public:
-  ShadowingAtExitManager() : AtExitManager(true) {}
-};
-#endif  // defined(UNIT_TEST)
-
-}  // namespace base
-
-#endif  // BASE_AT_EXIT_H_
diff --git a/base/base_switches.cc b/base/base_switches.cc
deleted file mode 100644
index 49eb975..0000000
--- a/base/base_switches.cc
+++ /dev/null
@@ -1,127 +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 "base/base_switches.h"
-#include "build_config.h"
-
-namespace switches {
-
-// Delays execution of base::TaskPriority::BACKGROUND tasks until shutdown.
-const char kDisableBackgroundTasks[] = "disable-background-tasks";
-
-// Disables the crash reporting.
-const char kDisableBreakpad[]               = "disable-breakpad";
-
-// Comma-separated list of feature names to disable. See also kEnableFeatures.
-const char kDisableFeatures[] = "disable-features";
-
-// Indicates that crash reporting should be enabled. On platforms where helper
-// processes cannot access to files needed to make this decision, this flag is
-// generated internally.
-const char kEnableCrashReporter[]           = "enable-crash-reporter";
-
-// Comma-separated list of feature names to enable. See also kDisableFeatures.
-const char kEnableFeatures[] = "enable-features";
-
-// Generates full memory crash dump.
-const char kFullMemoryCrashReport[]         = "full-memory-crash-report";
-
-// Force low-end device mode when set.
-const char kEnableLowEndDeviceMode[]        = "enable-low-end-device-mode";
-
-// Force disabling of low-end device mode when set.
-const char kDisableLowEndDeviceMode[]       = "disable-low-end-device-mode";
-
-// This option can be used to force field trials when testing changes locally.
-// The argument is a list of name and value pairs, separated by slashes. If a
-// trial name is prefixed with an asterisk, that trial will start activated.
-// For example, the following argument defines two trials, with the second one
-// activated: "GoogleNow/Enable/*MaterialDesignNTP/Default/" This option can
-// also be used by the browser process to send the list of trials to a
-// non-browser process, using the same format. See
-// FieldTrialList::CreateTrialsFromString() in field_trial.h for details.
-const char kForceFieldTrials[]              = "force-fieldtrials";
-
-// Suppresses all error dialogs when present.
-const char kNoErrorDialogs[]                = "noerrdialogs";
-
-// When running certain tests that spawn child processes, this switch indicates
-// to the test framework that the current process is a child process.
-const char kTestChildProcess[]              = "test-child-process";
-
-// When running certain tests that spawn child processes, this switch indicates
-// to the test framework that the current process should not initialize ICU to
-// avoid creating any scoped handles too early in startup.
-const char kTestDoNotInitializeIcu[]        = "test-do-not-initialize-icu";
-
-// Gives the default maximal active V-logging level; 0 is the default.
-// Normally positive values are used for V-logging levels.
-const char kV[]                             = "v";
-
-// Gives the per-module maximal V-logging levels to override the value
-// given by --v.  E.g. "my_module=2,foo*=3" would change the logging
-// level for all code in source files "my_module.*" and "foo*.*"
-// ("-inl" suffixes are also disregarded for this matching).
-//
-// Any pattern containing a forward or backward slash will be tested
-// against the whole pathname and not just the module.  E.g.,
-// "*/foo/bar/*=2" would change the logging level for all code in
-// source files under a "foo/bar" directory.
-const char kVModule[]                       = "vmodule";
-
-// Will wait for 60 seconds for a debugger to come to attach to the process.
-const char kWaitForDebugger[]               = "wait-for-debugger";
-
-// Sends trace events from these categories to a file.
-// --trace-to-file on its own sends to default categories.
-const char kTraceToFile[]                   = "trace-to-file";
-
-// Specifies the file name for --trace-to-file. If unspecified, it will
-// go to a default file name.
-const char kTraceToFileName[]               = "trace-to-file-name";
-
-// Specifies a location for profiling output. This will only work if chrome has
-// been built with the gyp variable profiling=1 or gn arg enable_profiling=true.
-//
-//   {pid} if present will be replaced by the pid of the process.
-//   {count} if present will be incremented each time a profile is generated
-//           for this process.
-// The default is chrome-profile-{pid} for the browser and test-profile-{pid}
-// for tests.
-const char kProfilingFile[] = "profiling-file";
-
-#if defined(OS_WIN)
-// Disables the USB keyboard detection for blocking the OSK on Win8+.
-const char kDisableUsbKeyboardDetect[]      = "disable-usb-keyboard-detect";
-#endif
-
-#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
-// The /dev/shm partition is too small in certain VM environments, causing
-// Chrome to fail or crash (see http://crbug.com/715363). Use this flag to
-// work-around this issue (a temporary directory will always be used to create
-// anonymous shared memory files).
-const char kDisableDevShmUsage[] = "disable-dev-shm-usage";
-#endif
-
-#if defined(OS_POSIX)
-// Used for turning on Breakpad crash reporting in a debug environment where
-// crash reporting is typically compiled but disabled.
-const char kEnableCrashReporterForTesting[] =
-    "enable-crash-reporter-for-testing";
-#endif
-
-#if defined(OS_ANDROID)
-// Optimizes memory layout of the native library using the orderfile symbols
-// given in base/android/library_loader/anchor_functions.h, via madvise and
-// changing the library prefetch behavior.
-const char kOrderfileMemoryOptimization[] = "orderfile-memory-optimization";
-// Force prefetching of the native library even if otherwise disabled, eg by
-// --orderfile-memory-optimization.
-const char kForceNativePrefetch[] = "force-native-prefetch";
-// If prefetching is enabled, only prefetch the ordered part of the native
-// library. Has no effect if prefetching is disabled.
-const char kNativePrefetchOrderedOnly[] = "native-prefetch-ordered-only";
-#endif
-
-}  // namespace switches
diff --git a/base/base_switches.h b/base/base_switches.h
deleted file mode 100644
index ada2727..0000000
--- a/base/base_switches.h
+++ /dev/null
@@ -1,53 +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 all the "base" command-line switches.
-
-#ifndef BASE_BASE_SWITCHES_H_
-#define BASE_BASE_SWITCHES_H_
-
-#include "build_config.h"
-
-namespace switches {
-
-extern const char kDisableBackgroundTasks[];
-extern const char kDisableBreakpad[];
-extern const char kDisableFeatures[];
-extern const char kDisableLowEndDeviceMode[];
-extern const char kEnableCrashReporter[];
-extern const char kEnableFeatures[];
-extern const char kEnableLowEndDeviceMode[];
-extern const char kForceFieldTrials[];
-extern const char kFullMemoryCrashReport[];
-extern const char kNoErrorDialogs[];
-extern const char kProfilingFile[];
-extern const char kTestChildProcess[];
-extern const char kTestDoNotInitializeIcu[];
-extern const char kTraceToFile[];
-extern const char kTraceToFileName[];
-extern const char kV[];
-extern const char kVModule[];
-extern const char kWaitForDebugger[];
-
-#if defined(OS_WIN)
-extern const char kDisableUsbKeyboardDetect[];
-#endif
-
-#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
-extern const char kDisableDevShmUsage[];
-#endif
-
-#if defined(OS_POSIX)
-extern const char kEnableCrashReporterForTesting[];
-#endif
-
-#if defined(OS_ANDROID)
-extern const char kOrderfileMemoryOptimization[];
-extern const char kForceNativePrefetch[];
-extern const char kNativePrefetchOrderedOnly[];
-#endif
-
-}  // namespace switches
-
-#endif  // BASE_BASE_SWITCHES_H_
diff --git a/base/cancelable_callback.h b/base/cancelable_callback.h
deleted file mode 100644
index a98101a..0000000
--- a/base/cancelable_callback.h
+++ /dev/null
@@ -1,156 +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.
-//
-// CancelableCallback is a wrapper around base::Callback that allows
-// cancellation of a callback. CancelableCallback takes a reference on the
-// wrapped callback until this object is destroyed or Reset()/Cancel() are
-// called.
-//
-// NOTE:
-//
-// Calling CancelableCallback::Cancel() brings the object back to its natural,
-// default-constructed state, i.e., CancelableCallback::callback() will return
-// a null callback.
-//
-// THREAD-SAFETY:
-//
-// CancelableCallback objects must be created on, posted to, cancelled on, and
-// destroyed on the same thread.
-//
-//
-// EXAMPLE USAGE:
-//
-// In the following example, the test is verifying that RunIntensiveTest()
-// Quit()s the message loop within 4 seconds. The cancelable callback is posted
-// to the message loop, the intensive test runs, the message loop is run,
-// then the callback is cancelled.
-//
-// RunLoop run_loop;
-//
-// void TimeoutCallback(const std::string& timeout_message) {
-//   FAIL() << timeout_message;
-//   run_loop.QuitWhenIdle();
-// }
-//
-// CancelableClosure timeout(base::Bind(&TimeoutCallback, "Test timed out."));
-// ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, timeout.callback(),
-//                                                TimeDelta::FromSeconds(4));
-// RunIntensiveTest();
-// run_loop.Run();
-// timeout.Cancel();  // Hopefully this is hit before the timeout callback runs.
-//
-
-#ifndef BASE_CANCELABLE_CALLBACK_H_
-#define BASE_CANCELABLE_CALLBACK_H_
-
-#include <utility>
-
-#include "base/base_export.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_internal.h"
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-
-namespace base {
-namespace internal {
-
-template <typename CallbackType>
-class CancelableCallbackImpl {
- public:
-  CancelableCallbackImpl() : weak_ptr_factory_(this) {}
-
-  // |callback| must not be null.
-  explicit CancelableCallbackImpl(CallbackType callback)
-      : callback_(std::move(callback)), weak_ptr_factory_(this) {
-    DCHECK(callback_);
-  }
-
-  ~CancelableCallbackImpl() = default;
-
-  // Cancels and drops the reference to the wrapped callback.
-  void Cancel() {
-    weak_ptr_factory_.InvalidateWeakPtrs();
-    callback_.Reset();
-  }
-
-  // Returns true if the wrapped callback has been cancelled.
-  bool IsCancelled() const {
-    return callback_.is_null();
-  }
-
-  // Sets |callback| as the closure that may be cancelled. |callback| may not
-  // be null. Outstanding and any previously wrapped callbacks are cancelled.
-  void Reset(CallbackType callback) {
-    DCHECK(callback);
-    // Outstanding tasks (e.g., posted to a message loop) must not be called.
-    Cancel();
-    callback_ = std::move(callback);
-  }
-
-  // Returns a callback that can be disabled by calling Cancel().
-  CallbackType callback() const {
-    if (!callback_)
-      return CallbackType();
-    CallbackType forwarder;
-    MakeForwarder(&forwarder);
-    return forwarder;
-  }
-
- private:
-  template <typename... Args>
-  void MakeForwarder(RepeatingCallback<void(Args...)>* out) const {
-    using ForwarderType = void (CancelableCallbackImpl::*)(Args...);
-    ForwarderType forwarder = &CancelableCallbackImpl::ForwardRepeating;
-    *out = BindRepeating(forwarder, weak_ptr_factory_.GetWeakPtr());
-  }
-
-  template <typename... Args>
-  void MakeForwarder(OnceCallback<void(Args...)>* out) const {
-    using ForwarderType = void (CancelableCallbackImpl::*)(Args...);
-    ForwarderType forwarder = &CancelableCallbackImpl::ForwardOnce;
-    *out = BindOnce(forwarder, weak_ptr_factory_.GetWeakPtr());
-  }
-
-  template <typename... Args>
-  void ForwardRepeating(Args... args) {
-    callback_.Run(std::forward<Args>(args)...);
-  }
-
-  template <typename... Args>
-  void ForwardOnce(Args... args) {
-    weak_ptr_factory_.InvalidateWeakPtrs();
-    std::move(callback_).Run(std::forward<Args>(args)...);
-  }
-
-  // The stored closure that may be cancelled.
-  CallbackType callback_;
-  mutable base::WeakPtrFactory<CancelableCallbackImpl> weak_ptr_factory_;
-
-  DISALLOW_COPY_AND_ASSIGN(CancelableCallbackImpl);
-};
-
-}  // namespace internal
-
-// Consider using base::WeakPtr directly instead of base::CancelableCallback for
-// the task cancellation.
-template <typename Signature>
-using CancelableOnceCallback =
-    internal::CancelableCallbackImpl<OnceCallback<Signature>>;
-using CancelableOnceClosure = CancelableOnceCallback<void()>;
-
-template <typename Signature>
-using CancelableRepeatingCallback =
-    internal::CancelableCallbackImpl<RepeatingCallback<Signature>>;
-using CancelableRepeatingClosure = CancelableOnceCallback<void()>;
-
-template <typename Signature>
-using CancelableCallback = CancelableRepeatingCallback<Signature>;
-using CancelableClosure = CancelableCallback<void()>;
-
-}  // namespace base
-
-#endif  // BASE_CANCELABLE_CALLBACK_H_
diff --git a/base/containers/hash_tables.h b/base/containers/hash_tables.h
deleted file mode 100644
index 8da7b67..0000000
--- a/base/containers/hash_tables.h
+++ /dev/null
@@ -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.
-
-#ifndef BASE_CONTAINERS_HASH_TABLES_H_
-#define BASE_CONTAINERS_HASH_TABLES_H_
-
-#include <cstddef>
-#include <unordered_map>
-#include <unordered_set>
-#include <utility>
-
-#include "base/hash.h"
-
-// This header file is deprecated. Use the corresponding C++11 type
-// instead. https://crbug.com/576864
-
-// Use a custom hasher instead.
-#define BASE_HASH_NAMESPACE base_hash
-
-namespace BASE_HASH_NAMESPACE {
-
-// A separate hasher which, by default, forwards to std::hash. This is so legacy
-// uses of BASE_HASH_NAMESPACE with base::hash_map do not interfere with
-// std::hash mid-transition.
-template<typename T>
-struct hash {
-  std::size_t operator()(const T& value) const { return std::hash<T>()(value); }
-};
-
-// Use base::IntPairHash from base/hash.h as a custom hasher instead.
-template <typename Type1, typename Type2>
-struct hash<std::pair<Type1, Type2>> {
-  std::size_t operator()(std::pair<Type1, Type2> value) const {
-    return base::HashInts(value.first, value.second);
-  }
-};
-
-}  // namespace BASE_HASH_NAMESPACE
-
-namespace base {
-
-// Use std::unordered_map instead.
-template <class Key,
-          class T,
-          class Hash = BASE_HASH_NAMESPACE::hash<Key>,
-          class Pred = std::equal_to<Key>,
-          class Alloc = std::allocator<std::pair<const Key, T>>>
-using hash_map = std::unordered_map<Key, T, Hash, Pred, Alloc>;
-
-// Use std::unordered_multimap instead.
-template <class Key,
-          class T,
-          class Hash = BASE_HASH_NAMESPACE::hash<Key>,
-          class Pred = std::equal_to<Key>,
-          class Alloc = std::allocator<std::pair<const Key, T>>>
-using hash_multimap = std::unordered_multimap<Key, T, Hash, Pred, Alloc>;
-
-// Use std::unordered_multiset instead.
-template <class Key,
-          class Hash = BASE_HASH_NAMESPACE::hash<Key>,
-          class Pred = std::equal_to<Key>,
-          class Alloc = std::allocator<Key>>
-using hash_multiset = std::unordered_multiset<Key, Hash, Pred, Alloc>;
-
-// Use std::unordered_set instead.
-template <class Key,
-          class Hash = BASE_HASH_NAMESPACE::hash<Key>,
-          class Pred = std::equal_to<Key>,
-          class Alloc = std::allocator<Key>>
-using hash_set = std::unordered_set<Key, Hash, Pred, Alloc>;
-
-}  // namespace base
-
-#endif  // BASE_CONTAINERS_HASH_TABLES_H_
diff --git a/base/containers/small_map.h b/base/containers/small_map.h
index 495332f..a235f11 100644
--- a/base/containers/small_map.h
+++ b/base/containers/small_map.h
@@ -12,7 +12,6 @@
 #include <string>
 #include <utility>
 
-#include "base/containers/hash_tables.h"
 #include "base/logging.h"
 
 namespace base {
diff --git a/base/critical_closure.h b/base/critical_closure.h
deleted file mode 100644
index d593537..0000000
--- a/base/critical_closure.h
+++ /dev/null
@@ -1,76 +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_CRITICAL_CLOSURE_H_
-#define BASE_CRITICAL_CLOSURE_H_
-
-#include <utility>
-
-#include "base/callback.h"
-#include "base/macros.h"
-#include "build_config.h"
-
-#if defined(OS_IOS)
-#include "base/bind.h"
-#include "base/ios/scoped_critical_action.h"
-#endif
-
-namespace base {
-
-namespace internal {
-
-#if defined(OS_IOS)
-// Returns true if multi-tasking is supported on this iOS device.
-bool IsMultiTaskingSupported();
-
-// This class wraps a closure so it can continue to run for a period of time
-// when the application goes to the background by using
-// |ios::ScopedCriticalAction|.
-class CriticalClosure {
- public:
-  explicit CriticalClosure(OnceClosure closure);
-  ~CriticalClosure();
-  void Run();
-
- private:
-  ios::ScopedCriticalAction critical_action_;
-  OnceClosure closure_;
-
-  DISALLOW_COPY_AND_ASSIGN(CriticalClosure);
-};
-#endif  // defined(OS_IOS)
-
-}  // namespace internal
-
-// Returns a closure that will continue to run for a period of time when the
-// application goes to the background if possible on platforms where
-// applications don't execute while backgrounded, otherwise the original task is
-// returned.
-//
-// Example:
-//   file_task_runner_->PostTask(
-//       FROM_HERE,
-//       MakeCriticalClosure(base::Bind(&WriteToDiskTask, path_, data)));
-//
-// Note new closures might be posted in this closure. If the new closures need
-// background running time, |MakeCriticalClosure| should be applied on them
-// before posting.
-#if defined(OS_IOS)
-inline OnceClosure MakeCriticalClosure(OnceClosure closure) {
-  DCHECK(internal::IsMultiTaskingSupported());
-  return base::BindOnce(
-      &internal::CriticalClosure::Run,
-      Owned(new internal::CriticalClosure(std::move(closure))));
-}
-#else  // defined(OS_IOS)
-inline OnceClosure MakeCriticalClosure(OnceClosure closure) {
-  // No-op for platforms where the application does not need to acquire
-  // background time for closures to finish when it goes into the background.
-  return closure;
-}
-#endif  // defined(OS_IOS)
-
-}  // namespace base
-
-#endif  // BASE_CRITICAL_CLOSURE_H_
diff --git a/base/deferred_sequenced_task_runner.cc b/base/deferred_sequenced_task_runner.cc
deleted file mode 100644
index f88170c..0000000
--- a/base/deferred_sequenced_task_runner.cc
+++ /dev/null
@@ -1,129 +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/deferred_sequenced_task_runner.h"
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/logging.h"
-
-namespace base {
-
-DeferredSequencedTaskRunner::DeferredTask::DeferredTask()
-    : is_non_nestable(false) {
-}
-
-DeferredSequencedTaskRunner::DeferredTask::DeferredTask(DeferredTask&& other) =
-    default;
-
-DeferredSequencedTaskRunner::DeferredTask::~DeferredTask() = default;
-
-DeferredSequencedTaskRunner::DeferredTask&
-DeferredSequencedTaskRunner::DeferredTask::operator=(DeferredTask&& other) =
-    default;
-
-DeferredSequencedTaskRunner::DeferredSequencedTaskRunner(
-    scoped_refptr<SequencedTaskRunner> target_task_runner)
-    : DeferredSequencedTaskRunner() {
-  DCHECK(target_task_runner);
-  target_task_runner_ = std::move(target_task_runner);
-}
-
-DeferredSequencedTaskRunner::DeferredSequencedTaskRunner()
-    : created_thread_id_(PlatformThread::CurrentId()) {}
-
-bool DeferredSequencedTaskRunner::PostDelayedTask(const Location& from_here,
-                                                  OnceClosure task,
-                                                  TimeDelta delay) {
-  AutoLock lock(lock_);
-  if (started_) {
-    DCHECK(deferred_tasks_queue_.empty());
-    return target_task_runner_->PostDelayedTask(from_here, std::move(task),
-                                                delay);
-  }
-
-  QueueDeferredTask(from_here, std::move(task), delay,
-                    false /* is_non_nestable */);
-  return true;
-}
-
-bool DeferredSequencedTaskRunner::RunsTasksInCurrentSequence() const {
-  AutoLock lock(lock_);
-  if (target_task_runner_)
-    return target_task_runner_->RunsTasksInCurrentSequence();
-
-  return created_thread_id_ == PlatformThread::CurrentId();
-}
-
-bool DeferredSequencedTaskRunner::PostNonNestableDelayedTask(
-    const Location& from_here,
-    OnceClosure task,
-    TimeDelta delay) {
-  AutoLock lock(lock_);
-  if (started_) {
-    DCHECK(deferred_tasks_queue_.empty());
-    return target_task_runner_->PostNonNestableDelayedTask(
-        from_here, std::move(task), delay);
-  }
-  QueueDeferredTask(from_here, std::move(task), delay,
-                    true /* is_non_nestable */);
-  return true;
-}
-
-void DeferredSequencedTaskRunner::Start() {
-  AutoLock lock(lock_);
-  StartImpl();
-}
-
-void DeferredSequencedTaskRunner::StartWithTaskRunner(
-    scoped_refptr<SequencedTaskRunner> target_task_runner) {
-  AutoLock lock(lock_);
-  DCHECK(!target_task_runner_);
-  DCHECK(target_task_runner);
-  target_task_runner_ = std::move(target_task_runner);
-  StartImpl();
-}
-
-DeferredSequencedTaskRunner::~DeferredSequencedTaskRunner() = default;
-
-void DeferredSequencedTaskRunner::QueueDeferredTask(const Location& from_here,
-                                                    OnceClosure task,
-                                                    TimeDelta delay,
-                                                    bool is_non_nestable) {
-  lock_.AssertAcquired();
-
-  // Use CHECK instead of DCHECK to crash earlier. See http://crbug.com/711167
-  // for details.
-  CHECK(task);
-
-  DeferredTask deferred_task;
-  deferred_task.posted_from = from_here;
-  deferred_task.task = std::move(task);
-  deferred_task.delay = delay;
-  deferred_task.is_non_nestable = is_non_nestable;
-  deferred_tasks_queue_.push_back(std::move(deferred_task));
-}
-
-void DeferredSequencedTaskRunner::StartImpl() {
-  lock_.AssertAcquired();  // Callers should have grabbed the lock.
-  DCHECK(!started_);
-  started_ = true;
-  DCHECK(target_task_runner_);
-  for (std::vector<DeferredTask>::iterator i = deferred_tasks_queue_.begin();
-      i != deferred_tasks_queue_.end();
-      ++i) {
-    DeferredTask& task = *i;
-    if (task.is_non_nestable) {
-      target_task_runner_->PostNonNestableDelayedTask(
-          task.posted_from, std::move(task.task), task.delay);
-    } else {
-      target_task_runner_->PostDelayedTask(task.posted_from,
-                                           std::move(task.task), task.delay);
-    }
-  }
-  deferred_tasks_queue_.clear();
-}
-
-}  // namespace base
diff --git a/base/deferred_sequenced_task_runner.h b/base/deferred_sequenced_task_runner.h
deleted file mode 100644
index 2805f47..0000000
--- a/base/deferred_sequenced_task_runner.h
+++ /dev/null
@@ -1,97 +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_DEFERRED_SEQUENCED_TASK_RUNNER_H_
-#define BASE_DEFERRED_SEQUENCED_TASK_RUNNER_H_
-
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/sequenced_task_runner.h"
-#include "base/synchronization/lock.h"
-#include "base/threading/platform_thread.h"
-#include "base/time/time.h"
-
-namespace base {
-
-// A DeferredSequencedTaskRunner is a subclass of SequencedTaskRunner that
-// queues up all requests until the first call to Start() is issued.
-// DeferredSequencedTaskRunner may be created in two ways:
-// . with an explicit SequencedTaskRunner that the events are flushed to
-// . without a SequencedTaskRunner. In this configuration the
-//   SequencedTaskRunner is supplied in StartWithTaskRunner().
-class BASE_EXPORT DeferredSequencedTaskRunner : public SequencedTaskRunner {
- public:
-  explicit DeferredSequencedTaskRunner(
-      scoped_refptr<SequencedTaskRunner> target_runner);
-
-  // Use this constructor when you don't have the target SequencedTaskRunner.
-  // When using this call StartWithTaskRunner().
-  DeferredSequencedTaskRunner();
-
-  // TaskRunner implementation
-  bool PostDelayedTask(const Location& from_here,
-                       OnceClosure task,
-                       TimeDelta delay) override;
-  bool RunsTasksInCurrentSequence() const override;
-
-  // SequencedTaskRunner implementation
-  bool PostNonNestableDelayedTask(const Location& from_here,
-                                  OnceClosure task,
-                                  TimeDelta delay) override;
-
-  // Start the execution - posts all queued tasks to the target executor. The
-  // deferred tasks are posted with their initial delay, meaning that the task
-  // execution delay is actually measured from Start.
-  // Fails when called a second time.
-  void Start();
-
-  // Same as Start(), but must be used with the no-arg constructor.
-  void StartWithTaskRunner(
-      scoped_refptr<SequencedTaskRunner> target_task_runner);
-
- private:
-  struct DeferredTask  {
-    DeferredTask();
-    DeferredTask(DeferredTask&& other);
-    ~DeferredTask();
-    DeferredTask& operator=(DeferredTask&& other);
-
-    Location posted_from;
-    OnceClosure task;
-    // The delay this task was initially posted with.
-    TimeDelta delay;
-    bool is_non_nestable;
-  };
-
-  ~DeferredSequencedTaskRunner() override;
-
-  // Both variants of Start() call into this.
-  void StartImpl();
-
-  // Creates a |Task| object and adds it to |deferred_tasks_queue_|.
-  void QueueDeferredTask(const Location& from_here,
-                         OnceClosure task,
-                         TimeDelta delay,
-                         bool is_non_nestable);
-
-  // // Protects |started_| and |deferred_tasks_queue_|.
-  mutable Lock lock_;
-
-  const PlatformThreadId created_thread_id_;
-
-  bool started_ = false;
-  scoped_refptr<SequencedTaskRunner> target_task_runner_;
-  std::vector<DeferredTask> deferred_tasks_queue_;
-
-  DISALLOW_COPY_AND_ASSIGN(DeferredSequencedTaskRunner);
-};
-
-}  // namespace base
-
-#endif  // BASE_DEFERRED_SEQUENCED_TASK_RUNNER_H_
diff --git a/base/files/dir_reader_fallback.h b/base/files/dir_reader_fallback.h
deleted file mode 100644
index d44c227..0000000
--- a/base/files/dir_reader_fallback.h
+++ /dev/null
@@ -1,35 +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_FILES_DIR_READER_FALLBACK_H_
-#define BASE_FILES_DIR_READER_FALLBACK_H_
-
-namespace base {
-
-class DirReaderFallback {
- public:
-  // Open a directory. If |IsValid| is true, then |Next| can be called to start
-  // the iteration at the beginning of the directory.
-  explicit DirReaderFallback(const char* directory_path) {}
-
-  // After construction, IsValid returns true iff the directory was
-  // successfully opened.
-  bool IsValid() const { return false; }
-
-  // Move to the next entry returning false if the iteration is complete.
-  bool Next() { return false; }
-
-  // Return the name of the current directory entry.
-  const char* name() { return nullptr;}
-
-  // Return the file descriptor which is being used.
-  int fd() const { return -1; }
-
-  // Returns true if this is a no-op fallback class (for testing).
-  static bool IsFallback() { return true; }
-};
-
-}  // namespace base
-
-#endif  // BASE_FILES_DIR_READER_FALLBACK_H_
diff --git a/base/files/dir_reader_linux.h b/base/files/dir_reader_linux.h
deleted file mode 100644
index 259bcfe..0000000
--- a/base/files/dir_reader_linux.h
+++ /dev/null
@@ -1,101 +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_FILES_DIR_READER_LINUX_H_
-#define BASE_FILES_DIR_READER_LINUX_H_
-
-#include <errno.h>
-#include <fcntl.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <sys/syscall.h>
-#include <unistd.h>
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/posix/eintr_wrapper.h"
-
-// See the comments in dir_reader_posix.h about this.
-
-namespace base {
-
-struct linux_dirent {
-  uint64_t        d_ino;
-  int64_t         d_off;
-  unsigned short  d_reclen;
-  unsigned char   d_type;
-  char            d_name[0];
-};
-
-class DirReaderLinux {
- public:
-  explicit DirReaderLinux(const char* directory_path)
-      : fd_(open(directory_path, O_RDONLY | O_DIRECTORY)),
-        offset_(0),
-        size_(0) {
-    memset(buf_, 0, sizeof(buf_));
-  }
-
-  ~DirReaderLinux() {
-    if (fd_ >= 0) {
-      if (IGNORE_EINTR(close(fd_)))
-        RAW_LOG(ERROR, "Failed to close directory handle");
-    }
-  }
-
-  bool IsValid() const {
-    return fd_ >= 0;
-  }
-
-  // Move to the next entry returning false if the iteration is complete.
-  bool Next() {
-    if (size_) {
-      linux_dirent* dirent = reinterpret_cast<linux_dirent*>(&buf_[offset_]);
-      offset_ += dirent->d_reclen;
-    }
-
-    if (offset_ != size_)
-      return true;
-
-    const int r = syscall(__NR_getdents64, fd_, buf_, sizeof(buf_));
-    if (r == 0)
-      return false;
-    if (r == -1) {
-      DPLOG(FATAL) << "getdents64 returned an error: " << errno;
-      return false;
-    }
-    size_ = r;
-    offset_ = 0;
-    return true;
-  }
-
-  const char* name() const {
-    if (!size_)
-      return nullptr;
-
-    const linux_dirent* dirent =
-        reinterpret_cast<const linux_dirent*>(&buf_[offset_]);
-    return dirent->d_name;
-  }
-
-  int fd() const {
-    return fd_;
-  }
-
-  static bool IsFallback() {
-    return false;
-  }
-
- private:
-  const int fd_;
-  alignas(linux_dirent) unsigned char buf_[512];
-  size_t offset_;
-  size_t size_;
-
-  DISALLOW_COPY_AND_ASSIGN(DirReaderLinux);
-};
-
-}  // namespace base
-
-#endif  // BASE_FILES_DIR_READER_LINUX_H_
diff --git a/base/files/dir_reader_posix.h b/base/files/dir_reader_posix.h
deleted file mode 100644
index e238d6b..0000000
--- a/base/files/dir_reader_posix.h
+++ /dev/null
@@ -1,36 +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_FILES_DIR_READER_POSIX_H_
-#define BASE_FILES_DIR_READER_POSIX_H_
-
-#include "build_config.h"
-
-// This header provides a class, DirReaderPosix, which allows one to open and
-// read from directories without allocating memory. For the interface, see
-// the generic fallback in dir_reader_fallback.h.
-
-// Mac note: OS X has getdirentries, but it only works if we restrict Chrome to
-// 32-bit inodes. There is a getdirentries64 syscall in 10.6, but it's not
-// wrapped and the direct syscall interface is unstable. Using an unstable API
-// seems worse than falling back to enumerating all file descriptors so we will
-// probably never implement this on the Mac.
-
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-#include "base/files/dir_reader_linux.h"
-#else
-#include "base/files/dir_reader_fallback.h"
-#endif
-
-namespace base {
-
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-typedef DirReaderLinux DirReaderPosix;
-#else
-typedef DirReaderFallback DirReaderPosix;
-#endif
-
-}  // namespace base
-
-#endif  // BASE_FILES_DIR_READER_POSIX_H_
diff --git a/base/files/file.cc b/base/files/file.cc
index b79802b..7485b1a 100644
--- a/base/files/file.cc
+++ b/base/files/file.cc
@@ -4,7 +4,6 @@
 
 #include "base/files/file.h"
 #include "base/files/file_path.h"
-#include "base/files/file_tracing.h"
 #include "base/timer/elapsed_timer.h"
 #include "build_config.h"
 
@@ -53,7 +52,6 @@
 
 File::File(File&& other)
     : file_(other.TakePlatformFile()),
-      tracing_path_(other.tracing_path_),
       error_details_(other.error_details()),
       created_(other.created()),
       async_(other.async_) {}
@@ -75,7 +73,6 @@
 File& File::operator=(File&& other) {
   Close();
   SetPlatformFile(other.TakePlatformFile());
-  tracing_path_ = other.tracing_path_;
   error_details_ = other.error_details();
   created_ = other.created();
   async_ = other.async_;
@@ -95,9 +92,6 @@
     error_details_ = FILE_ERROR_ACCESS_DENIED;
     return;
   }
-  if (FileTracing::IsCategoryEnabled())
-    tracing_path_ = path;
-  SCOPED_FILE_TRACE("Initialize");
   DoInitialize(path, flags);
 }
 #endif
diff --git a/base/files/file.h b/base/files/file.h
index 801d68a..3f959a4 100644
--- a/base/files/file.h
+++ b/base/files/file.h
@@ -11,7 +11,6 @@
 
 #include "base/base_export.h"
 #include "base/files/file_path.h"
-#include "base/files/file_tracing.h"
 #include "base/files/platform_file.h"
 #include "base/files/scoped_file.h"
 #include "base/macros.h"
@@ -345,8 +344,6 @@
   static std::string ErrorToString(Error error);
 
  private:
-  friend class FileTracing::ScopedTrace;
-
   // Creates or opens the given file. Only called if |path| has no
   // traversal ('..') components.
   void DoInitialize(const FilePath& path, uint32_t flags);
@@ -355,13 +352,6 @@
 
   ScopedPlatformFile file_;
 
-  // A path to use for tracing purposes. Set if file tracing is enabled during
-  // |Initialize()|.
-  FilePath tracing_path_;
-
-  // Object tied to the lifetime of |this| that enables/disables tracing.
-  FileTracing::ScopedEnabler trace_enabler_;
-
   Error error_details_;
   bool created_;
   bool async_;
diff --git a/base/files/file_descriptor_watcher_posix.cc b/base/files/file_descriptor_watcher_posix.cc
deleted file mode 100644
index b26bf6c..0000000
--- a/base/files/file_descriptor_watcher_posix.cc
+++ /dev/null
@@ -1,217 +0,0 @@
-// Copyright 2016 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/files/file_descriptor_watcher_posix.h"
-
-#include "base/bind.h"
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/memory/ptr_util.h"
-#include "base/message_loop/message_loop_current.h"
-#include "base/message_loop/message_pump_for_io.h"
-#include "base/sequenced_task_runner.h"
-#include "base/single_thread_task_runner.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-#include "base/threading/thread_checker.h"
-#include "base/threading/thread_local.h"
-
-namespace base {
-
-namespace {
-
-// MessageLoopForIO used to watch file descriptors for which callbacks are
-// registered from a given thread.
-LazyInstance<ThreadLocalPointer<MessageLoopForIO>>::Leaky
-    tls_message_loop_for_io = LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace
-
-FileDescriptorWatcher::Controller::~Controller() {
-  DCHECK(sequence_checker_.CalledOnValidSequence());
-
-  // Delete |watcher_| on the MessageLoopForIO.
-  //
-  // If the MessageLoopForIO is deleted before Watcher::StartWatching() runs,
-  // |watcher_| is leaked. If the MessageLoopForIO is deleted after
-  // Watcher::StartWatching() runs but before the DeleteSoon task runs,
-  // |watcher_| is deleted from Watcher::WillDestroyCurrentMessageLoop().
-  message_loop_for_io_task_runner_->DeleteSoon(FROM_HERE, watcher_.release());
-
-  // Since WeakPtrs are invalidated by the destructor, RunCallback() won't be
-  // invoked after this returns.
-}
-
-class FileDescriptorWatcher::Controller::Watcher
-    : public MessagePumpForIO::FdWatcher,
-      public MessageLoopCurrent::DestructionObserver {
- public:
-  Watcher(WeakPtr<Controller> controller, MessagePumpForIO::Mode mode, int fd);
-  ~Watcher() override;
-
-  void StartWatching();
-
- private:
-  friend class FileDescriptorWatcher;
-
-  // MessagePumpForIO::FdWatcher:
-  void OnFileCanReadWithoutBlocking(int fd) override;
-  void OnFileCanWriteWithoutBlocking(int fd) override;
-
-  // MessageLoopCurrent::DestructionObserver:
-  void WillDestroyCurrentMessageLoop() override;
-
-  // The MessageLoopForIO's watch handle (stops the watch when destroyed).
-  MessagePumpForIO::FdWatchController fd_watch_controller_;
-
-  // Runs tasks on the sequence on which this was instantiated (i.e. the
-  // sequence on which the callback must run).
-  const scoped_refptr<SequencedTaskRunner> callback_task_runner_ =
-      SequencedTaskRunnerHandle::Get();
-
-  // The Controller that created this Watcher.
-  WeakPtr<Controller> controller_;
-
-  // Whether this Watcher is notified when |fd_| becomes readable or writable
-  // without blocking.
-  const MessagePumpForIO::Mode mode_;
-
-  // The watched file descriptor.
-  const int fd_;
-
-  // Except for the constructor, every method of this class must run on the same
-  // MessageLoopForIO thread.
-  ThreadChecker thread_checker_;
-
-  // Whether this Watcher was registered as a DestructionObserver on the
-  // MessageLoopForIO thread.
-  bool registered_as_destruction_observer_ = false;
-
-  DISALLOW_COPY_AND_ASSIGN(Watcher);
-};
-
-FileDescriptorWatcher::Controller::Watcher::Watcher(
-    WeakPtr<Controller> controller,
-    MessagePumpForIO::Mode mode,
-    int fd)
-    : fd_watch_controller_(FROM_HERE),
-      controller_(controller),
-      mode_(mode),
-      fd_(fd) {
-  DCHECK(callback_task_runner_);
-  thread_checker_.DetachFromThread();
-}
-
-FileDescriptorWatcher::Controller::Watcher::~Watcher() {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  MessageLoopCurrentForIO::Get()->RemoveDestructionObserver(this);
-}
-
-void FileDescriptorWatcher::Controller::Watcher::StartWatching() {
-  DCHECK(thread_checker_.CalledOnValidThread());
-
-  if (!MessageLoopCurrentForIO::Get()->WatchFileDescriptor(
-          fd_, false, mode_, &fd_watch_controller_, this)) {
-    // TODO(wez): Ideally we would [D]CHECK here, or propagate the failure back
-    // to the caller, but there is no guarantee that they haven't already
-    // closed |fd_| on another thread, so the best we can do is Debug-log.
-    DLOG(ERROR) << "Failed to watch fd=" << fd_;
-  }
-
-  if (!registered_as_destruction_observer_) {
-    MessageLoopCurrentForIO::Get()->AddDestructionObserver(this);
-    registered_as_destruction_observer_ = true;
-  }
-}
-
-void FileDescriptorWatcher::Controller::Watcher::OnFileCanReadWithoutBlocking(
-    int fd) {
-  DCHECK_EQ(fd_, fd);
-  DCHECK_EQ(MessagePumpForIO::WATCH_READ, mode_);
-  DCHECK(thread_checker_.CalledOnValidThread());
-
-  // Run the callback on the sequence on which the watch was initiated.
-  callback_task_runner_->PostTask(
-      FROM_HERE, BindOnce(&Controller::RunCallback, controller_));
-}
-
-void FileDescriptorWatcher::Controller::Watcher::OnFileCanWriteWithoutBlocking(
-    int fd) {
-  DCHECK_EQ(fd_, fd);
-  DCHECK_EQ(MessagePumpForIO::WATCH_WRITE, mode_);
-  DCHECK(thread_checker_.CalledOnValidThread());
-
-  // Run the callback on the sequence on which the watch was initiated.
-  callback_task_runner_->PostTask(
-      FROM_HERE, BindOnce(&Controller::RunCallback, controller_));
-}
-
-void FileDescriptorWatcher::Controller::Watcher::
-    WillDestroyCurrentMessageLoop() {
-  DCHECK(thread_checker_.CalledOnValidThread());
-
-  // A Watcher is owned by a Controller. When the Controller is deleted, it
-  // transfers ownership of the Watcher to a delete task posted to the
-  // MessageLoopForIO. If the MessageLoopForIO is deleted before the delete task
-  // runs, the following line takes care of deleting the Watcher.
-  delete this;
-}
-
-FileDescriptorWatcher::Controller::Controller(MessagePumpForIO::Mode mode,
-                                              int fd,
-                                              const Closure& callback)
-    : callback_(callback),
-      message_loop_for_io_task_runner_(
-          tls_message_loop_for_io.Get().Get()->task_runner()),
-      weak_factory_(this) {
-  DCHECK(!callback_.is_null());
-  DCHECK(message_loop_for_io_task_runner_);
-  watcher_ = std::make_unique<Watcher>(weak_factory_.GetWeakPtr(), mode, fd);
-  StartWatching();
-}
-
-void FileDescriptorWatcher::Controller::StartWatching() {
-  DCHECK(sequence_checker_.CalledOnValidSequence());
-  // It is safe to use Unretained() below because |watcher_| can only be deleted
-  // by a delete task posted to |message_loop_for_io_task_runner_| by this
-  // Controller's destructor. Since this delete task hasn't been posted yet, it
-  // can't run before the task posted below.
-  message_loop_for_io_task_runner_->PostTask(
-      FROM_HERE, BindOnce(&Watcher::StartWatching, Unretained(watcher_.get())));
-}
-
-void FileDescriptorWatcher::Controller::RunCallback() {
-  DCHECK(sequence_checker_.CalledOnValidSequence());
-
-  WeakPtr<Controller> weak_this = weak_factory_.GetWeakPtr();
-
-  callback_.Run();
-
-  // If |this| wasn't deleted, re-enable the watch.
-  if (weak_this)
-    StartWatching();
-}
-
-FileDescriptorWatcher::FileDescriptorWatcher(
-    MessageLoopForIO* message_loop_for_io) {
-  DCHECK(message_loop_for_io);
-  DCHECK(!tls_message_loop_for_io.Get().Get());
-  tls_message_loop_for_io.Get().Set(message_loop_for_io);
-}
-
-FileDescriptorWatcher::~FileDescriptorWatcher() {
-  tls_message_loop_for_io.Get().Set(nullptr);
-}
-
-std::unique_ptr<FileDescriptorWatcher::Controller>
-FileDescriptorWatcher::WatchReadable(int fd, const Closure& callback) {
-  return WrapUnique(new Controller(MessagePumpForIO::WATCH_READ, fd, callback));
-}
-
-std::unique_ptr<FileDescriptorWatcher::Controller>
-FileDescriptorWatcher::WatchWritable(int fd, const Closure& callback) {
-  return WrapUnique(
-      new Controller(MessagePumpForIO::WATCH_WRITE, fd, callback));
-}
-
-}  // namespace base
diff --git a/base/files/file_descriptor_watcher_posix.h b/base/files/file_descriptor_watcher_posix.h
deleted file mode 100644
index aa44579..0000000
--- a/base/files/file_descriptor_watcher_posix.h
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright 2016 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_FILES_FILE_DESCRIPTOR_WATCHER_POSIX_H_
-#define BASE_FILES_FILE_DESCRIPTOR_WATCHER_POSIX_H_
-
-#include <memory>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/weak_ptr.h"
-#include "base/message_loop/message_loop.h"
-#include "base/message_loop/message_pump_for_io.h"
-#include "base/sequence_checker.h"
-
-namespace base {
-
-class SingleThreadTaskRunner;
-
-// The FileDescriptorWatcher API allows callbacks to be invoked when file
-// descriptors are readable or writable without blocking.
-//
-// To enable this API in unit tests, use a ScopedTaskEnvironment with
-// MainThreadType::IO.
-//
-// Note: Prefer FileDescriptorWatcher to MessageLoopForIO::WatchFileDescriptor()
-// for non-critical IO. FileDescriptorWatcher works on threads/sequences without
-// MessagePumps but involves going through the task queue after being notified
-// by the OS (a desirablable property for non-critical IO that shouldn't preempt
-// the main queue).
-class BASE_EXPORT FileDescriptorWatcher {
- public:
-  // Instantiated and returned by WatchReadable() or WatchWritable(). The
-  // constructor registers a callback to be invoked when a file descriptor is
-  // readable or writable without blocking and the destructor unregisters it.
-  class Controller {
-   public:
-    // Unregisters the callback registered by the constructor.
-    ~Controller();
-
-   private:
-    friend class FileDescriptorWatcher;
-    class Watcher;
-
-    // Registers |callback| to be invoked when |fd| is readable or writable
-    // without blocking (depending on |mode|).
-    Controller(MessagePumpForIO::Mode mode, int fd, const Closure& callback);
-
-    // Starts watching the file descriptor.
-    void StartWatching();
-
-    // Runs |callback_|.
-    void RunCallback();
-
-    // The callback to run when the watched file descriptor is readable or
-    // writable without blocking.
-    Closure callback_;
-
-    // TaskRunner associated with the MessageLoopForIO that watches the file
-    // descriptor.
-    const scoped_refptr<SingleThreadTaskRunner>
-        message_loop_for_io_task_runner_;
-
-    // Notified by the MessageLoopForIO associated with
-    // |message_loop_for_io_task_runner_| when the watched file descriptor is
-    // readable or writable without blocking. Posts a task to run RunCallback()
-    // on the sequence on which the Controller was instantiated. When the
-    // Controller is deleted, ownership of |watcher_| is transfered to a delete
-    // task posted to the MessageLoopForIO. This ensures that |watcher_| isn't
-    // deleted while it is being used by the MessageLoopForIO.
-    std::unique_ptr<Watcher> watcher_;
-
-    // Validates that the Controller is used on the sequence on which it was
-    // instantiated.
-    SequenceChecker sequence_checker_;
-
-    WeakPtrFactory<Controller> weak_factory_;
-
-    DISALLOW_COPY_AND_ASSIGN(Controller);
-  };
-
-  // Registers |message_loop_for_io| to watch file descriptors for which
-  // callbacks are registered from the current thread via WatchReadable() or
-  // WatchWritable(). |message_loop_for_io| may run on another thread. The
-  // constructed FileDescriptorWatcher must not outlive |message_loop_for_io|.
-  FileDescriptorWatcher(MessageLoopForIO* message_loop_for_io);
-  ~FileDescriptorWatcher();
-
-  // Registers |callback| to be posted on the current sequence when |fd| is
-  // readable or writable without blocking. |callback| is unregistered when the
-  // returned Controller is deleted (deletion must happen on the current
-  // sequence). To call these methods, a FileDescriptorWatcher must have been
-  // instantiated on the current thread and SequencedTaskRunnerHandle::IsSet()
-  // must return true (these conditions are met at least on all TaskScheduler
-  // threads as well as on threads backed by a MessageLoopForIO).
-  static std::unique_ptr<Controller> WatchReadable(int fd,
-                                                   const Closure& callback);
-  static std::unique_ptr<Controller> WatchWritable(int fd,
-                                                   const Closure& callback);
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(FileDescriptorWatcher);
-};
-
-}  // namespace base
-
-#endif  // BASE_FILES_FILE_DESCRIPTOR_WATCHER_POSIX_H_
diff --git a/base/files/file_enumerator_posix.cc b/base/files/file_enumerator_posix.cc
index 383d202..a0c5d45 100644
--- a/base/files/file_enumerator_posix.cc
+++ b/base/files/file_enumerator_posix.cc
@@ -11,7 +11,6 @@
 #include <string.h>
 
 #include "base/logging.h"
-#include "base/threading/thread_restrictions.h"
 #include "build_config.h"
 
 namespace base {
@@ -95,8 +94,6 @@
 FileEnumerator::~FileEnumerator() = default;
 
 FilePath FileEnumerator::Next() {
-  AssertBlockingAllowed();
-
   ++current_directory_entry_;
 
   // While we've exhausted the entries in the current directory, do the next
diff --git a/base/files/file_enumerator_win.cc b/base/files/file_enumerator_win.cc
index f96074c..a2bfabf 100644
--- a/base/files/file_enumerator_win.cc
+++ b/base/files/file_enumerator_win.cc
@@ -9,7 +9,6 @@
 #include <string.h>
 
 #include "base/logging.h"
-#include "base/threading/thread_restrictions.h"
 
 namespace base {
 
@@ -111,8 +110,6 @@
 }
 
 FilePath FileEnumerator::Next() {
-  AssertBlockingAllowed();
-
   while (has_find_data_ || !pending_paths_.empty()) {
     if (!has_find_data_) {
       // The last find FindFirstFile operation is done, prepare a new one.
diff --git a/base/files/file_path_watcher.cc b/base/files/file_path_watcher.cc
deleted file mode 100644
index 5b50312..0000000
--- a/base/files/file_path_watcher.cc
+++ /dev/null
@@ -1,46 +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.
-
-// Cross platform methods for FilePathWatcher. See the various platform
-// specific implementation files, too.
-
-#include "base/files/file_path_watcher.h"
-
-#include "base/logging.h"
-#include "build_config.h"
-
-namespace base {
-
-FilePathWatcher::~FilePathWatcher() {
-  DCHECK(sequence_checker_.CalledOnValidSequence());
-  impl_->Cancel();
-}
-
-// static
-bool FilePathWatcher::RecursiveWatchAvailable() {
-#if (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_WIN) || \
-    defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_AIX)
-  return true;
-#else
-  // FSEvents isn't available on iOS.
-  return false;
-#endif
-}
-
-FilePathWatcher::PlatformDelegate::PlatformDelegate(): cancelled_(false) {
-}
-
-FilePathWatcher::PlatformDelegate::~PlatformDelegate() {
-  DCHECK(is_cancelled());
-}
-
-bool FilePathWatcher::Watch(const FilePath& path,
-                            bool recursive,
-                            const Callback& callback) {
-  DCHECK(sequence_checker_.CalledOnValidSequence());
-  DCHECK(path.IsAbsolute());
-  return impl_->Watch(path, recursive, callback);
-}
-
-}  // namespace base
diff --git a/base/files/file_path_watcher.h b/base/files/file_path_watcher.h
deleted file mode 100644
index 9e29d0a..0000000
--- a/base/files/file_path_watcher.h
+++ /dev/null
@@ -1,110 +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 module provides a way to monitor a file or directory for changes.
-
-#ifndef BASE_FILES_FILE_PATH_WATCHER_H_
-#define BASE_FILES_FILE_PATH_WATCHER_H_
-
-#include <memory>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/files/file_path.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/sequence_checker.h"
-#include "base/sequenced_task_runner.h"
-
-namespace base {
-
-// This class lets you register interest in changes on a FilePath.
-// The callback will get called whenever the file or directory referenced by the
-// FilePath is changed, including created or deleted. Due to limitations in the
-// underlying OS APIs, FilePathWatcher has slightly different semantics on OS X
-// than on Windows or Linux. FilePathWatcher on Linux and Windows will detect
-// modifications to files in a watched directory. FilePathWatcher on Mac will
-// detect the creation and deletion of files in a watched directory, but will
-// not detect modifications to those files. See file_path_watcher_kqueue.cc for
-// details.
-//
-// Must be destroyed on the sequence that invokes Watch().
-class BASE_EXPORT FilePathWatcher {
- public:
-  // Callback type for Watch(). |path| points to the file that was updated,
-  // and |error| is true if the platform specific code detected an error. In
-  // that case, the callback won't be invoked again.
-  typedef base::Callback<void(const FilePath& path, bool error)> Callback;
-
-  // Used internally to encapsulate different members on different platforms.
-  class PlatformDelegate {
-   public:
-    PlatformDelegate();
-    virtual ~PlatformDelegate();
-
-    // Start watching for the given |path| and notify |delegate| about changes.
-    virtual bool Watch(const FilePath& path,
-                       bool recursive,
-                       const Callback& callback) WARN_UNUSED_RESULT = 0;
-
-    // Stop watching. This is called from FilePathWatcher's dtor in order to
-    // allow to shut down properly while the object is still alive.
-    virtual void Cancel() = 0;
-
-   protected:
-    friend class FilePathWatcher;
-
-    scoped_refptr<SequencedTaskRunner> task_runner() const {
-      return task_runner_;
-    }
-
-    void set_task_runner(scoped_refptr<SequencedTaskRunner> runner) {
-      task_runner_ = std::move(runner);
-    }
-
-    // Must be called before the PlatformDelegate is deleted.
-    void set_cancelled() {
-      cancelled_ = true;
-    }
-
-    bool is_cancelled() const {
-      return cancelled_;
-    }
-
-   private:
-    scoped_refptr<SequencedTaskRunner> task_runner_;
-    bool cancelled_;
-
-    DISALLOW_COPY_AND_ASSIGN(PlatformDelegate);
-  };
-
-  FilePathWatcher();
-  ~FilePathWatcher();
-
-  // Returns true if the platform and OS version support recursive watches.
-  static bool RecursiveWatchAvailable();
-
-  // Invokes |callback| whenever updates to |path| are detected. This should be
-  // called at most once. Set |recursive| to true to watch |path| and its
-  // children. The callback will be invoked on the same sequence. Returns true
-  // on success.
-  //
-  // On POSIX, this must be called from a thread that supports
-  // FileDescriptorWatcher.
-  //
-  // Recursive watch is not supported on all platforms and file systems.
-  // Watch() will return false in the case of failure.
-  bool Watch(const FilePath& path, bool recursive, const Callback& callback);
-
- private:
-  std::unique_ptr<PlatformDelegate> impl_;
-
-  SequenceChecker sequence_checker_;
-
-  DISALLOW_COPY_AND_ASSIGN(FilePathWatcher);
-};
-
-}  // namespace base
-
-#endif  // BASE_FILES_FILE_PATH_WATCHER_H_
diff --git a/base/files/file_path_watcher_fsevents.cc b/base/files/file_path_watcher_fsevents.cc
deleted file mode 100644
index 49ed36b..0000000
--- a/base/files/file_path_watcher_fsevents.cc
+++ /dev/null
@@ -1,282 +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 "base/files/file_path_watcher_fsevents.h"
-
-#include <dispatch/dispatch.h>
-
-#include <list>
-
-#include "base/bind.h"
-#include "base/files/file_util.h"
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/mac/scoped_cftyperef.h"
-#include "base/strings/stringprintf.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-
-namespace base {
-
-namespace {
-
-// The latency parameter passed to FSEventsStreamCreate().
-const CFAbsoluteTime kEventLatencySeconds = 0.3;
-
-// Resolve any symlinks in the path.
-FilePath ResolvePath(const FilePath& path) {
-  const unsigned kMaxLinksToResolve = 255;
-
-  std::vector<FilePath::StringType> component_vector;
-  path.GetComponents(&component_vector);
-  std::list<FilePath::StringType>
-      components(component_vector.begin(), component_vector.end());
-
-  FilePath result;
-  unsigned resolve_count = 0;
-  while (resolve_count < kMaxLinksToResolve && !components.empty()) {
-    FilePath component(*components.begin());
-    components.pop_front();
-
-    FilePath current;
-    if (component.IsAbsolute()) {
-      current = component;
-    } else {
-      current = result.Append(component);
-    }
-
-    FilePath target;
-    if (ReadSymbolicLink(current, &target)) {
-      if (target.IsAbsolute())
-        result.clear();
-      std::vector<FilePath::StringType> target_components;
-      target.GetComponents(&target_components);
-      components.insert(components.begin(), target_components.begin(),
-                        target_components.end());
-      resolve_count++;
-    } else {
-      result = current;
-    }
-  }
-
-  if (resolve_count >= kMaxLinksToResolve)
-    result.clear();
-  return result;
-}
-
-}  // namespace
-
-FilePathWatcherFSEvents::FilePathWatcherFSEvents()
-    : queue_(dispatch_queue_create(
-          base::StringPrintf("org.chromium.base.FilePathWatcher.%p", this)
-              .c_str(),
-          DISPATCH_QUEUE_SERIAL)),
-      fsevent_stream_(nullptr),
-      weak_factory_(this) {}
-
-FilePathWatcherFSEvents::~FilePathWatcherFSEvents() {
-  DCHECK(!task_runner() || task_runner()->RunsTasksInCurrentSequence());
-  DCHECK(callback_.is_null())
-      << "Cancel() must be called before FilePathWatcher is destroyed.";
-}
-
-bool FilePathWatcherFSEvents::Watch(const FilePath& path,
-                                    bool recursive,
-                                    const FilePathWatcher::Callback& callback) {
-  DCHECK(!callback.is_null());
-  DCHECK(callback_.is_null());
-
-  // This class could support non-recursive watches, but that is currently
-  // left to FilePathWatcherKQueue.
-  if (!recursive)
-    return false;
-
-  set_task_runner(SequencedTaskRunnerHandle::Get());
-  callback_ = callback;
-
-  FSEventStreamEventId start_event = FSEventsGetCurrentEventId();
-  // The block runtime would implicitly capture the reference, not the object
-  // it's referencing. Copy the path into a local, so that the value is
-  // captured by the block's scope.
-  const FilePath path_copy(path);
-
-  dispatch_async(queue_, ^{
-      StartEventStream(start_event, path_copy);
-  });
-  return true;
-}
-
-void FilePathWatcherFSEvents::Cancel() {
-  set_cancelled();
-  callback_.Reset();
-
-  // Switch to the dispatch queue to tear down the event stream. As the queue is
-  // owned by |this|, and this method is called from the destructor, execute the
-  // block synchronously.
-  dispatch_sync(queue_, ^{
-    if (fsevent_stream_) {
-      DestroyEventStream();
-      target_.clear();
-      resolved_target_.clear();
-    }
-  });
-}
-
-// static
-void FilePathWatcherFSEvents::FSEventsCallback(
-    ConstFSEventStreamRef stream,
-    void* event_watcher,
-    size_t num_events,
-    void* event_paths,
-    const FSEventStreamEventFlags flags[],
-    const FSEventStreamEventId event_ids[]) {
-  FilePathWatcherFSEvents* watcher =
-      reinterpret_cast<FilePathWatcherFSEvents*>(event_watcher);
-  bool root_changed = watcher->ResolveTargetPath();
-  std::vector<FilePath> paths;
-  FSEventStreamEventId root_change_at = FSEventStreamGetLatestEventId(stream);
-  for (size_t i = 0; i < num_events; i++) {
-    if (flags[i] & kFSEventStreamEventFlagRootChanged)
-      root_changed = true;
-    if (event_ids[i])
-      root_change_at = std::min(root_change_at, event_ids[i]);
-    paths.push_back(FilePath(
-        reinterpret_cast<char**>(event_paths)[i]).StripTrailingSeparators());
-  }
-
-  // Reinitialize the event stream if we find changes to the root. This is
-  // necessary since FSEvents doesn't report any events for the subtree after
-  // the directory to be watched gets created.
-  if (root_changed) {
-    // Resetting the event stream from within the callback fails (FSEvents spews
-    // bad file descriptor errors), so do the reset asynchronously.
-    //
-    // We can't dispatch_async a call to UpdateEventStream() directly because
-    // there would be no guarantee that |watcher| still exists when it runs.
-    //
-    // Instead, bounce on task_runner() and use a WeakPtr to verify that
-    // |watcher| still exists. If it does, dispatch_async a call to
-    // UpdateEventStream(). Because the destructor of |watcher| runs on
-    // task_runner() and calls dispatch_sync, it is guaranteed that |watcher|
-    // still exists when UpdateEventStream() runs.
-    watcher->task_runner()->PostTask(
-        FROM_HERE, Bind(
-                       [](WeakPtr<FilePathWatcherFSEvents> weak_watcher,
-                          FSEventStreamEventId root_change_at) {
-                         if (!weak_watcher)
-                           return;
-                         FilePathWatcherFSEvents* watcher = weak_watcher.get();
-                         dispatch_async(watcher->queue_, ^{
-                           watcher->UpdateEventStream(root_change_at);
-                         });
-                       },
-                       watcher->weak_factory_.GetWeakPtr(), root_change_at));
-  }
-
-  watcher->OnFilePathsChanged(paths);
-}
-
-void FilePathWatcherFSEvents::OnFilePathsChanged(
-    const std::vector<FilePath>& paths) {
-  DCHECK(!resolved_target_.empty());
-  task_runner()->PostTask(
-      FROM_HERE,
-      Bind(&FilePathWatcherFSEvents::DispatchEvents, weak_factory_.GetWeakPtr(),
-           paths, target_, resolved_target_));
-}
-
-void FilePathWatcherFSEvents::DispatchEvents(const std::vector<FilePath>& paths,
-                                             const FilePath& target,
-                                             const FilePath& resolved_target) {
-  DCHECK(task_runner()->RunsTasksInCurrentSequence());
-
-  // Don't issue callbacks after Cancel() has been called.
-  if (is_cancelled() || callback_.is_null()) {
-    return;
-  }
-
-  for (const FilePath& path : paths) {
-    if (resolved_target.IsParent(path) || resolved_target == path) {
-      callback_.Run(target, false);
-      return;
-    }
-  }
-}
-
-void FilePathWatcherFSEvents::UpdateEventStream(
-    FSEventStreamEventId start_event) {
-  // It can happen that the watcher gets canceled while tasks that call this
-  // function are still in flight, so abort if this situation is detected.
-  if (resolved_target_.empty())
-    return;
-
-  if (fsevent_stream_)
-    DestroyEventStream();
-
-  ScopedCFTypeRef<CFStringRef> cf_path(CFStringCreateWithCString(
-      NULL, resolved_target_.value().c_str(), kCFStringEncodingMacHFS));
-  ScopedCFTypeRef<CFStringRef> cf_dir_path(CFStringCreateWithCString(
-      NULL, resolved_target_.DirName().value().c_str(),
-      kCFStringEncodingMacHFS));
-  CFStringRef paths_array[] = { cf_path.get(), cf_dir_path.get() };
-  ScopedCFTypeRef<CFArrayRef> watched_paths(CFArrayCreate(
-      NULL, reinterpret_cast<const void**>(paths_array), arraysize(paths_array),
-      &kCFTypeArrayCallBacks));
-
-  FSEventStreamContext context;
-  context.version = 0;
-  context.info = this;
-  context.retain = NULL;
-  context.release = NULL;
-  context.copyDescription = NULL;
-
-  fsevent_stream_ = FSEventStreamCreate(NULL, &FSEventsCallback, &context,
-                                        watched_paths,
-                                        start_event,
-                                        kEventLatencySeconds,
-                                        kFSEventStreamCreateFlagWatchRoot);
-  FSEventStreamSetDispatchQueue(fsevent_stream_, queue_);
-
-  if (!FSEventStreamStart(fsevent_stream_)) {
-    task_runner()->PostTask(FROM_HERE,
-                            Bind(&FilePathWatcherFSEvents::ReportError,
-                                 weak_factory_.GetWeakPtr(), target_));
-  }
-}
-
-bool FilePathWatcherFSEvents::ResolveTargetPath() {
-  FilePath resolved = ResolvePath(target_).StripTrailingSeparators();
-  bool changed = resolved != resolved_target_;
-  resolved_target_ = resolved;
-  if (resolved_target_.empty()) {
-    task_runner()->PostTask(FROM_HERE,
-                            Bind(&FilePathWatcherFSEvents::ReportError,
-                                 weak_factory_.GetWeakPtr(), target_));
-  }
-  return changed;
-}
-
-void FilePathWatcherFSEvents::ReportError(const FilePath& target) {
-  DCHECK(task_runner()->RunsTasksInCurrentSequence());
-  if (!callback_.is_null()) {
-    callback_.Run(target, true);
-  }
-}
-
-void FilePathWatcherFSEvents::DestroyEventStream() {
-  FSEventStreamStop(fsevent_stream_);
-  FSEventStreamInvalidate(fsevent_stream_);
-  FSEventStreamRelease(fsevent_stream_);
-  fsevent_stream_ = NULL;
-}
-
-void FilePathWatcherFSEvents::StartEventStream(FSEventStreamEventId start_event,
-                                               const FilePath& path) {
-  DCHECK(resolved_target_.empty());
-
-  target_ = path;
-  ResolveTargetPath();
-  UpdateEventStream(start_event);
-}
-
-}  // namespace base
diff --git a/base/files/file_path_watcher_fsevents.h b/base/files/file_path_watcher_fsevents.h
deleted file mode 100644
index dcdf2fb..0000000
--- a/base/files/file_path_watcher_fsevents.h
+++ /dev/null
@@ -1,99 +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.
-
-#ifndef BASE_FILES_FILE_PATH_WATCHER_FSEVENTS_H_
-#define BASE_FILES_FILE_PATH_WATCHER_FSEVENTS_H_
-
-#include <CoreServices/CoreServices.h>
-#include <stddef.h>
-
-#include <vector>
-
-#include "base/files/file_path.h"
-#include "base/files/file_path_watcher.h"
-#include "base/mac/scoped_dispatch_object.h"
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-
-namespace base {
-
-// Mac-specific file watcher implementation based on FSEvents.
-// There are trade-offs between the FSEvents implementation and a kqueue
-// implementation. The biggest issues are that FSEvents on 10.6 sometimes drops
-// events and kqueue does not trigger for modifications to a file in a watched
-// directory. See file_path_watcher_mac.cc for the code that decides when to
-// use which one.
-class FilePathWatcherFSEvents : public FilePathWatcher::PlatformDelegate {
- public:
-  FilePathWatcherFSEvents();
-  ~FilePathWatcherFSEvents() override;
-
-  // FilePathWatcher::PlatformDelegate overrides.
-  bool Watch(const FilePath& path,
-             bool recursive,
-             const FilePathWatcher::Callback& callback) override;
-  void Cancel() override;
-
- private:
-  static void FSEventsCallback(ConstFSEventStreamRef stream,
-                               void* event_watcher,
-                               size_t num_events,
-                               void* event_paths,
-                               const FSEventStreamEventFlags flags[],
-                               const FSEventStreamEventId event_ids[]);
-
-  // Called from FSEventsCallback whenever there is a change to the paths.
-  void OnFilePathsChanged(const std::vector<FilePath>& paths);
-
-  // Called on the message_loop() thread to dispatch path events. Can't access
-  // target_ and resolved_target_ directly as those are modified on the
-  // libdispatch thread.
-  void DispatchEvents(const std::vector<FilePath>& paths,
-                      const FilePath& target,
-                      const FilePath& resolved_target);
-
-  // (Re-)Initialize the event stream to start reporting events from
-  // |start_event|.
-  void UpdateEventStream(FSEventStreamEventId start_event);
-
-  // Returns true if resolving the target path got a different result than
-  // last time it was done.
-  bool ResolveTargetPath();
-
-  // Report an error watching the given target.
-  void ReportError(const FilePath& target);
-
-  // Destroy the event stream.
-  void DestroyEventStream();
-
-  // Start watching the FSEventStream.
-  void StartEventStream(FSEventStreamEventId start_event, const FilePath& path);
-
-  // Callback to notify upon changes.
-  // (Only accessed from the message_loop() thread.)
-  FilePathWatcher::Callback callback_;
-
-  // The dispatch queue on which the the event stream is scheduled.
-  ScopedDispatchObject<dispatch_queue_t> queue_;
-
-  // Target path to watch (passed to callback).
-  // (Only accessed from the libdispatch queue.)
-  FilePath target_;
-
-  // Target path with all symbolic links resolved.
-  // (Only accessed from the libdispatch queue.)
-  FilePath resolved_target_;
-
-  // Backend stream we receive event callbacks from (strong reference).
-  // (Only accessed from the libdispatch queue.)
-  FSEventStreamRef fsevent_stream_;
-
-  WeakPtrFactory<FilePathWatcherFSEvents> weak_factory_;
-
-  DISALLOW_COPY_AND_ASSIGN(FilePathWatcherFSEvents);
-};
-
-}  // namespace base
-
-#endif  // BASE_FILES_FILE_PATH_WATCHER_FSEVENTS_H_
diff --git a/base/files/file_path_watcher_kqueue.cc b/base/files/file_path_watcher_kqueue.cc
deleted file mode 100644
index 036809d..0000000
--- a/base/files/file_path_watcher_kqueue.cc
+++ /dev/null
@@ -1,372 +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 "base/files/file_path_watcher_kqueue.h"
-
-#include <fcntl.h>
-#include <stddef.h>
-#include <sys/param.h>
-
-#include "base/bind.h"
-#include "base/files/file_util.h"
-#include "base/logging.h"
-#include "base/strings/stringprintf.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-
-// On some platforms these are not defined.
-#if !defined(EV_RECEIPT)
-#define EV_RECEIPT 0
-#endif
-#if !defined(O_EVTONLY)
-#define O_EVTONLY O_RDONLY
-#endif
-
-namespace base {
-
-FilePathWatcherKQueue::FilePathWatcherKQueue() : kqueue_(-1) {}
-
-FilePathWatcherKQueue::~FilePathWatcherKQueue() {
-  DCHECK(!task_runner() || task_runner()->RunsTasksInCurrentSequence());
-}
-
-void FilePathWatcherKQueue::ReleaseEvent(struct kevent& event) {
-  CloseFileDescriptor(&event.ident);
-  EventData* entry = EventDataForKevent(event);
-  delete entry;
-  event.udata = NULL;
-}
-
-int FilePathWatcherKQueue::EventsForPath(FilePath path, EventVector* events) {
-  // Make sure that we are working with a clean slate.
-  DCHECK(events->empty());
-
-  std::vector<FilePath::StringType> components;
-  path.GetComponents(&components);
-
-  if (components.size() < 1) {
-    return -1;
-  }
-
-  int last_existing_entry = 0;
-  FilePath built_path;
-  bool path_still_exists = true;
-  for (std::vector<FilePath::StringType>::iterator i = components.begin();
-      i != components.end(); ++i) {
-    if (i == components.begin()) {
-      built_path = FilePath(*i);
-    } else {
-      built_path = built_path.Append(*i);
-    }
-    uintptr_t fd = kNoFileDescriptor;
-    if (path_still_exists) {
-      fd = FileDescriptorForPath(built_path);
-      if (fd == kNoFileDescriptor) {
-        path_still_exists = false;
-      } else {
-        ++last_existing_entry;
-      }
-    }
-    FilePath::StringType subdir = (i != (components.end() - 1)) ? *(i + 1) : "";
-    EventData* data = new EventData(built_path, subdir);
-    struct kevent event;
-    EV_SET(&event, fd, EVFILT_VNODE, (EV_ADD | EV_CLEAR | EV_RECEIPT),
-           (NOTE_DELETE | NOTE_WRITE | NOTE_ATTRIB |
-            NOTE_RENAME | NOTE_REVOKE | NOTE_EXTEND), 0, data);
-    events->push_back(event);
-  }
-  return last_existing_entry;
-}
-
-uintptr_t FilePathWatcherKQueue::FileDescriptorForPath(const FilePath& path) {
-  int fd = HANDLE_EINTR(open(path.value().c_str(), O_EVTONLY));
-  if (fd == -1)
-    return kNoFileDescriptor;
-  return fd;
-}
-
-void FilePathWatcherKQueue::CloseFileDescriptor(uintptr_t* fd) {
-  if (*fd == kNoFileDescriptor) {
-    return;
-  }
-
-  if (IGNORE_EINTR(close(*fd)) != 0) {
-    DPLOG(ERROR) << "close";
-  }
-  *fd = kNoFileDescriptor;
-}
-
-bool FilePathWatcherKQueue::AreKeventValuesValid(struct kevent* kevents,
-                                               int count) {
-  if (count < 0) {
-    DPLOG(ERROR) << "kevent";
-    return false;
-  }
-  bool valid = true;
-  for (int i = 0; i < count; ++i) {
-    if (kevents[i].flags & EV_ERROR && kevents[i].data) {
-      // Find the kevent in |events_| that matches the kevent with the error.
-      EventVector::iterator event = events_.begin();
-      for (; event != events_.end(); ++event) {
-        if (event->ident == kevents[i].ident) {
-          break;
-        }
-      }
-      std::string path_name;
-      if (event != events_.end()) {
-        EventData* event_data = EventDataForKevent(*event);
-        if (event_data != NULL) {
-          path_name = event_data->path_.value();
-        }
-      }
-      if (path_name.empty()) {
-        path_name = base::StringPrintf(
-            "fd %ld", reinterpret_cast<long>(&kevents[i].ident));
-      }
-      DLOG(ERROR) << "Error: " << kevents[i].data << " for " << path_name;
-      valid = false;
-    }
-  }
-  return valid;
-}
-
-void FilePathWatcherKQueue::HandleAttributesChange(
-    const EventVector::iterator& event,
-    bool* target_file_affected,
-    bool* update_watches) {
-  EventVector::iterator next_event = event + 1;
-  EventData* next_event_data = EventDataForKevent(*next_event);
-  // Check to see if the next item in path is still accessible.
-  uintptr_t have_access = FileDescriptorForPath(next_event_data->path_);
-  if (have_access == kNoFileDescriptor) {
-    *target_file_affected = true;
-    *update_watches = true;
-    EventVector::iterator local_event(event);
-    for (; local_event != events_.end(); ++local_event) {
-      // Close all nodes from the event down. This has the side effect of
-      // potentially rendering other events in |updates| invalid.
-      // There is no need to remove the events from |kqueue_| because this
-      // happens as a side effect of closing the file descriptor.
-      CloseFileDescriptor(&local_event->ident);
-    }
-  } else {
-    CloseFileDescriptor(&have_access);
-  }
-}
-
-void FilePathWatcherKQueue::HandleDeleteOrMoveChange(
-    const EventVector::iterator& event,
-    bool* target_file_affected,
-    bool* update_watches) {
-  *target_file_affected = true;
-  *update_watches = true;
-  EventVector::iterator local_event(event);
-  for (; local_event != events_.end(); ++local_event) {
-    // Close all nodes from the event down. This has the side effect of
-    // potentially rendering other events in |updates| invalid.
-    // There is no need to remove the events from |kqueue_| because this
-    // happens as a side effect of closing the file descriptor.
-    CloseFileDescriptor(&local_event->ident);
-  }
-}
-
-void FilePathWatcherKQueue::HandleCreateItemChange(
-    const EventVector::iterator& event,
-    bool* target_file_affected,
-    bool* update_watches) {
-  // Get the next item in the path.
-  EventVector::iterator next_event = event + 1;
-  // Check to see if it already has a valid file descriptor.
-  if (!IsKeventFileDescriptorOpen(*next_event)) {
-    EventData* next_event_data = EventDataForKevent(*next_event);
-    // If not, attempt to open a file descriptor for it.
-    next_event->ident = FileDescriptorForPath(next_event_data->path_);
-    if (IsKeventFileDescriptorOpen(*next_event)) {
-      *update_watches = true;
-      if (next_event_data->subdir_.empty()) {
-        *target_file_affected = true;
-      }
-    }
-  }
-}
-
-bool FilePathWatcherKQueue::UpdateWatches(bool* target_file_affected) {
-  // Iterate over events adding kevents for items that exist to the kqueue.
-  // Then check to see if new components in the path have been created.
-  // Repeat until no new components in the path are detected.
-  // This is to get around races in directory creation in a watched path.
-  bool update_watches = true;
-  while (update_watches) {
-    size_t valid;
-    for (valid = 0; valid < events_.size(); ++valid) {
-      if (!IsKeventFileDescriptorOpen(events_[valid])) {
-        break;
-      }
-    }
-    if (valid == 0) {
-      // The root of the file path is inaccessible?
-      return false;
-    }
-
-    EventVector updates(valid);
-    int count = HANDLE_EINTR(kevent(kqueue_, &events_[0], valid, &updates[0],
-                                    valid, NULL));
-    if (!AreKeventValuesValid(&updates[0], count)) {
-      return false;
-    }
-    update_watches = false;
-    for (; valid < events_.size(); ++valid) {
-      EventData* event_data = EventDataForKevent(events_[valid]);
-      events_[valid].ident = FileDescriptorForPath(event_data->path_);
-      if (IsKeventFileDescriptorOpen(events_[valid])) {
-        update_watches = true;
-        if (event_data->subdir_.empty()) {
-          *target_file_affected = true;
-        }
-      } else {
-        break;
-      }
-    }
-  }
-  return true;
-}
-
-bool FilePathWatcherKQueue::Watch(const FilePath& path,
-                                  bool recursive,
-                                  const FilePathWatcher::Callback& callback) {
-  DCHECK(target_.value().empty());  // Can only watch one path.
-  DCHECK(!callback.is_null());
-  DCHECK_EQ(kqueue_, -1);
-  // Recursive watch is not supported using kqueue.
-  DCHECK(!recursive);
-
-  callback_ = callback;
-  target_ = path;
-
-  set_task_runner(SequencedTaskRunnerHandle::Get());
-
-  kqueue_ = kqueue();
-  if (kqueue_ == -1) {
-    DPLOG(ERROR) << "kqueue";
-    return false;
-  }
-
-  int last_entry = EventsForPath(target_, &events_);
-  DCHECK_NE(last_entry, 0);
-
-  EventVector responses(last_entry);
-
-  int count = HANDLE_EINTR(kevent(kqueue_, &events_[0], last_entry,
-                                  &responses[0], last_entry, NULL));
-  if (!AreKeventValuesValid(&responses[0], count)) {
-    // Calling Cancel() here to close any file descriptors that were opened.
-    // This would happen in the destructor anyways, but FilePathWatchers tend to
-    // be long lived, and if an error has occurred, there is no reason to waste
-    // the file descriptors.
-    Cancel();
-    return false;
-  }
-
-  // It's safe to use Unretained() because the watch is cancelled and the
-  // callback cannot be invoked after |kqueue_watch_controller_| (which is a
-  // member of |this|) has been deleted.
-  kqueue_watch_controller_ = FileDescriptorWatcher::WatchReadable(
-      kqueue_,
-      Bind(&FilePathWatcherKQueue::OnKQueueReadable, Unretained(this)));
-
-  return true;
-}
-
-void FilePathWatcherKQueue::Cancel() {
-  if (!task_runner()) {
-    set_cancelled();
-    return;
-  }
-
-  DCHECK(task_runner()->RunsTasksInCurrentSequence());
-  if (!is_cancelled()) {
-    set_cancelled();
-    kqueue_watch_controller_.reset();
-    if (IGNORE_EINTR(close(kqueue_)) != 0) {
-      DPLOG(ERROR) << "close kqueue";
-    }
-    kqueue_ = -1;
-    std::for_each(events_.begin(), events_.end(), ReleaseEvent);
-    events_.clear();
-    callback_.Reset();
-  }
-}
-
-void FilePathWatcherKQueue::OnKQueueReadable() {
-  DCHECK(task_runner()->RunsTasksInCurrentSequence());
-  DCHECK(events_.size());
-
-  // Request the file system update notifications that have occurred and return
-  // them in |updates|. |count| will contain the number of updates that have
-  // occurred.
-  EventVector updates(events_.size());
-  struct timespec timeout = {0, 0};
-  int count = HANDLE_EINTR(kevent(kqueue_, NULL, 0, &updates[0], updates.size(),
-                                  &timeout));
-
-  // Error values are stored within updates, so check to make sure that no
-  // errors occurred.
-  if (!AreKeventValuesValid(&updates[0], count)) {
-    callback_.Run(target_, true /* error */);
-    Cancel();
-    return;
-  }
-
-  bool update_watches = false;
-  bool send_notification = false;
-
-  // Iterate through each of the updates and react to them.
-  for (int i = 0; i < count; ++i) {
-    // Find our kevent record that matches the update notification.
-    EventVector::iterator event = events_.begin();
-    for (; event != events_.end(); ++event) {
-      if (!IsKeventFileDescriptorOpen(*event) ||
-          event->ident == updates[i].ident) {
-        break;
-      }
-    }
-    if (event == events_.end() || !IsKeventFileDescriptorOpen(*event)) {
-      // The event may no longer exist in |events_| because another event
-      // modified |events_| in such a way to make it invalid. For example if
-      // the path is /foo/bar/bam and foo is deleted, NOTE_DELETE events for
-      // foo, bar and bam will be sent. If foo is processed first, then
-      // the file descriptors for bar and bam will already be closed and set
-      // to -1 before they get a chance to be processed.
-      continue;
-    }
-
-    EventData* event_data = EventDataForKevent(*event);
-
-    // If the subdir is empty, this is the last item on the path and is the
-    // target file.
-    bool target_file_affected = event_data->subdir_.empty();
-    if ((updates[i].fflags & NOTE_ATTRIB) && !target_file_affected) {
-      HandleAttributesChange(event, &target_file_affected, &update_watches);
-    }
-    if (updates[i].fflags & (NOTE_DELETE | NOTE_REVOKE | NOTE_RENAME)) {
-      HandleDeleteOrMoveChange(event, &target_file_affected, &update_watches);
-    }
-    if ((updates[i].fflags & NOTE_WRITE) && !target_file_affected) {
-      HandleCreateItemChange(event, &target_file_affected, &update_watches);
-    }
-    send_notification |= target_file_affected;
-  }
-
-  if (update_watches) {
-    if (!UpdateWatches(&send_notification)) {
-      callback_.Run(target_, true /* error */);
-      Cancel();
-    }
-  }
-
-  if (send_notification) {
-    callback_.Run(target_, false);
-  }
-}
-
-}  // namespace base
diff --git a/base/files/file_path_watcher_kqueue.h b/base/files/file_path_watcher_kqueue.h
deleted file mode 100644
index ef79be5..0000000
--- a/base/files/file_path_watcher_kqueue.h
+++ /dev/null
@@ -1,125 +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.
-
-#ifndef BASE_FILES_FILE_PATH_WATCHER_KQUEUE_H_
-#define BASE_FILES_FILE_PATH_WATCHER_KQUEUE_H_
-
-#include <sys/event.h>
-
-#include <memory>
-#include <vector>
-
-#include "base/files/file_descriptor_watcher_posix.h"
-#include "base/files/file_path.h"
-#include "base/files/file_path_watcher.h"
-#include "base/macros.h"
-
-namespace base {
-
-// Mac-specific file watcher implementation based on kqueue.
-// The Linux and Windows versions are able to detect:
-// - file creation/deletion/modification in a watched directory
-// - file creation/deletion/modification for a watched file
-// - modifications to the paths to a watched object that would affect the
-//   object such as renaming/attibute changes etc.
-// The kqueue implementation will handle all of the items in the list above
-// except for detecting modifications to files in a watched directory. It will
-// detect the creation and deletion of files, just not the modification of
-// files. It does however detect the attribute changes that the FSEvents impl
-// would miss.
-class FilePathWatcherKQueue : public FilePathWatcher::PlatformDelegate {
- public:
-  FilePathWatcherKQueue();
-  ~FilePathWatcherKQueue() override;
-
-  // FilePathWatcher::PlatformDelegate overrides.
-  bool Watch(const FilePath& path,
-             bool recursive,
-             const FilePathWatcher::Callback& callback) override;
-  void Cancel() override;
-
- private:
-  class EventData {
-   public:
-    EventData(const FilePath& path, const FilePath::StringType& subdir)
-        : path_(path), subdir_(subdir) { }
-    FilePath path_;  // Full path to this item.
-    FilePath::StringType subdir_;  // Path to any sub item.
-  };
-
-  typedef std::vector<struct kevent> EventVector;
-
-  // Called when data is available in |kqueue_|.
-  void OnKQueueReadable();
-
-  // Returns true if the kevent values are error free.
-  bool AreKeventValuesValid(struct kevent* kevents, int count);
-
-  // Respond to a change of attributes of the path component represented by
-  // |event|. Sets |target_file_affected| to true if |target_| is affected.
-  // Sets |update_watches| to true if |events_| need to be updated.
-  void HandleAttributesChange(const EventVector::iterator& event,
-                              bool* target_file_affected,
-                              bool* update_watches);
-
-  // Respond to a move or deletion of the path component represented by
-  // |event|. Sets |target_file_affected| to true if |target_| is affected.
-  // Sets |update_watches| to true if |events_| need to be updated.
-  void HandleDeleteOrMoveChange(const EventVector::iterator& event,
-                                bool* target_file_affected,
-                                bool* update_watches);
-
-  // Respond to a creation of an item in the path component represented by
-  // |event|. Sets |target_file_affected| to true if |target_| is affected.
-  // Sets |update_watches| to true if |events_| need to be updated.
-  void HandleCreateItemChange(const EventVector::iterator& event,
-                              bool* target_file_affected,
-                              bool* update_watches);
-
-  // Update |events_| with the current status of the system.
-  // Sets |target_file_affected| to true if |target_| is affected.
-  // Returns false if an error occurs.
-  bool UpdateWatches(bool* target_file_affected);
-
-  // Fills |events| with one kevent per component in |path|.
-  // Returns the number of valid events created where a valid event is
-  // defined as one that has a ident (file descriptor) field != -1.
-  static int EventsForPath(FilePath path, EventVector *events);
-
-  // Release a kevent generated by EventsForPath.
-  static void ReleaseEvent(struct kevent& event);
-
-  // Returns a file descriptor that will not block the system from deleting
-  // the file it references.
-  static uintptr_t FileDescriptorForPath(const FilePath& path);
-
-  static const uintptr_t kNoFileDescriptor = static_cast<uintptr_t>(-1);
-
-  // Closes |*fd| and sets |*fd| to -1.
-  static void CloseFileDescriptor(uintptr_t* fd);
-
-  // Returns true if kevent has open file descriptor.
-  static bool IsKeventFileDescriptorOpen(const struct kevent& event) {
-    return event.ident != kNoFileDescriptor;
-  }
-
-  static EventData* EventDataForKevent(const struct kevent& event) {
-    return reinterpret_cast<EventData*>(event.udata);
-  }
-
-  EventVector events_;
-  FilePathWatcher::Callback callback_;
-  FilePath target_;
-  int kqueue_;
-
-  // Throughout the lifetime of this, OnKQueueReadable() will be called when
-  // data is available in |kqueue_|.
-  std::unique_ptr<FileDescriptorWatcher::Controller> kqueue_watch_controller_;
-
-  DISALLOW_COPY_AND_ASSIGN(FilePathWatcherKQueue);
-};
-
-}  // namespace base
-
-#endif  // BASE_FILES_FILE_PATH_WATCHER_KQUEUE_H_
diff --git a/base/files/file_path_watcher_linux.cc b/base/files/file_path_watcher_linux.cc
deleted file mode 100644
index 75677d4..0000000
--- a/base/files/file_path_watcher_linux.cc
+++ /dev/null
@@ -1,679 +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 "base/files/file_path_watcher.h"
-
-#include <errno.h>
-#include <stddef.h>
-#include <string.h>
-#include <sys/inotify.h>
-#include <sys/ioctl.h>
-#include <sys/select.h>
-#include <unistd.h>
-
-#include <algorithm>
-#include <map>
-#include <memory>
-#include <set>
-#include <unordered_map>
-#include <utility>
-#include <vector>
-
-#include "base/bind.h"
-#include "base/files/file_enumerator.h"
-#include "base/files/file_path.h"
-#include "base/files/file_util.h"
-#include "base/lazy_instance.h"
-#include "base/location.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/memory/weak_ptr.h"
-#include "base/posix/eintr_wrapper.h"
-#include "base/single_thread_task_runner.h"
-#include "base/stl_util.h"
-#include "base/synchronization/lock.h"
-#include "base/threading/platform_thread.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-
-namespace base {
-
-namespace {
-
-class FilePathWatcherImpl;
-class InotifyReader;
-
-class InotifyReaderThreadDelegate final : public PlatformThread::Delegate {
- public:
-  InotifyReaderThreadDelegate(int inotify_fd) : inotify_fd_(inotify_fd){};
-
-  ~InotifyReaderThreadDelegate() override = default;
-
- private:
-  void ThreadMain() override;
-
-  int inotify_fd_;
-
-  DISALLOW_COPY_AND_ASSIGN(InotifyReaderThreadDelegate);
-};
-
-// Singleton to manage all inotify watches.
-// TODO(tony): It would be nice if this wasn't a singleton.
-// http://crbug.com/38174
-class InotifyReader {
- public:
-  typedef int Watch;  // Watch descriptor used by AddWatch and RemoveWatch.
-  static const Watch kInvalidWatch = -1;
-
-  // Watch directory |path| for changes. |watcher| will be notified on each
-  // change. Returns kInvalidWatch on failure.
-  Watch AddWatch(const FilePath& path, FilePathWatcherImpl* watcher);
-
-  // Remove |watch| if it's valid.
-  void RemoveWatch(Watch watch, FilePathWatcherImpl* watcher);
-
-  // Callback for InotifyReaderTask.
-  void OnInotifyEvent(const inotify_event* event);
-
- private:
-  friend struct LazyInstanceTraitsBase<InotifyReader>;
-
-  typedef std::set<FilePathWatcherImpl*> WatcherSet;
-
-  InotifyReader();
-  // There is no destructor because |g_inotify_reader| is a
-  // base::LazyInstace::Leaky object. Having a destructor causes build
-  // issues with GCC 6 (http://crbug.com/636346).
-
-  // Returns true on successful thread creation.
-  bool StartThread();
-
-  // We keep track of which delegates want to be notified on which watches.
-  std::unordered_map<Watch, WatcherSet> watchers_;
-
-  // Lock to protect watchers_.
-  Lock lock_;
-
-  // File descriptor returned by inotify_init.
-  const int inotify_fd_;
-
-  // Thread delegate for the Inotify thread.
-  InotifyReaderThreadDelegate thread_delegate_;
-
-  // Flag set to true when startup was successful.
-  bool valid_;
-
-  DISALLOW_COPY_AND_ASSIGN(InotifyReader);
-};
-
-class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate {
- public:
-  FilePathWatcherImpl();
-  ~FilePathWatcherImpl() override;
-
-  // Called for each event coming from the watch. |fired_watch| identifies the
-  // watch that fired, |child| indicates what has changed, and is relative to
-  // the currently watched path for |fired_watch|.
-  //
-  // |created| is true if the object appears.
-  // |deleted| is true if the object disappears.
-  // |is_dir| is true if the object is a directory.
-  void OnFilePathChanged(InotifyReader::Watch fired_watch,
-                         const FilePath::StringType& child,
-                         bool created,
-                         bool deleted,
-                         bool is_dir);
-
- private:
-  void OnFilePathChangedOnOriginSequence(InotifyReader::Watch fired_watch,
-                                         const FilePath::StringType& child,
-                                         bool created,
-                                         bool deleted,
-                                         bool is_dir);
-
-  // Start watching |path| for changes and notify |delegate| on each change.
-  // Returns true if watch for |path| has been added successfully.
-  bool Watch(const FilePath& path,
-             bool recursive,
-             const FilePathWatcher::Callback& callback) override;
-
-  // Cancel the watch. This unregisters the instance with InotifyReader.
-  void Cancel() override;
-
-  // Inotify watches are installed for all directory components of |target_|.
-  // A WatchEntry instance holds:
-  // - |watch|: the watch descriptor for a component.
-  // - |subdir|: the subdirectory that identifies the next component.
-  //   - For the last component, there is no next component, so it is empty.
-  // - |linkname|: the target of the symlink.
-  //   - Only if the target being watched is a symbolic link.
-  struct WatchEntry {
-    explicit WatchEntry(const FilePath::StringType& dirname)
-        : watch(InotifyReader::kInvalidWatch),
-          subdir(dirname) {}
-
-    InotifyReader::Watch watch;
-    FilePath::StringType subdir;
-    FilePath::StringType linkname;
-  };
-  typedef std::vector<WatchEntry> WatchVector;
-
-  // Reconfigure to watch for the most specific parent directory of |target_|
-  // that exists. Also calls UpdateRecursiveWatches() below.
-  void UpdateWatches();
-
-  // Reconfigure to recursively watch |target_| and all its sub-directories.
-  // - This is a no-op if the watch is not recursive.
-  // - If |target_| does not exist, then clear all the recursive watches.
-  // - Assuming |target_| exists, passing kInvalidWatch as |fired_watch| forces
-  //   addition of recursive watches for |target_|.
-  // - Otherwise, only the directory associated with |fired_watch| and its
-  //   sub-directories will be reconfigured.
-  void UpdateRecursiveWatches(InotifyReader::Watch fired_watch, bool is_dir);
-
-  // Enumerate recursively through |path| and add / update watches.
-  void UpdateRecursiveWatchesForPath(const FilePath& path);
-
-  // Do internal bookkeeping to update mappings between |watch| and its
-  // associated full path |path|.
-  void TrackWatchForRecursion(InotifyReader::Watch watch, const FilePath& path);
-
-  // Remove all the recursive watches.
-  void RemoveRecursiveWatches();
-
-  // |path| is a symlink to a non-existent target. Attempt to add a watch to
-  // the link target's parent directory. Update |watch_entry| on success.
-  void AddWatchForBrokenSymlink(const FilePath& path, WatchEntry* watch_entry);
-
-  bool HasValidWatchVector() const;
-
-  // Callback to notify upon changes.
-  FilePathWatcher::Callback callback_;
-
-  // The file or directory we're supposed to watch.
-  FilePath target_;
-
-  bool recursive_;
-
-  // The vector of watches and next component names for all path components,
-  // starting at the root directory. The last entry corresponds to the watch for
-  // |target_| and always stores an empty next component name in |subdir|.
-  WatchVector watches_;
-
-  std::unordered_map<InotifyReader::Watch, FilePath> recursive_paths_by_watch_;
-  std::map<FilePath, InotifyReader::Watch> recursive_watches_by_path_;
-
-  // Read only while INotifyReader::lock_ is held, and used to post asynchronous
-  // notifications to the Watcher on its home task_runner(). Ideally this should
-  // be const, but since it is initialized from |weak_factory_|, which must
-  // appear after it, that is not possible.
-  WeakPtr<FilePathWatcherImpl> weak_ptr_;
-
-  WeakPtrFactory<FilePathWatcherImpl> weak_factory_;
-
-  DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
-};
-
-LazyInstance<InotifyReader>::Leaky g_inotify_reader = LAZY_INSTANCE_INITIALIZER;
-
-void InotifyReaderThreadDelegate::ThreadMain() {
-  PlatformThread::SetName("inotify_reader");
-
-  // Make sure the file descriptors are good for use with select().
-  CHECK_LE(0, inotify_fd_);
-  CHECK_GT(FD_SETSIZE, inotify_fd_);
-
-  while (true) {
-    fd_set rfds;
-    FD_ZERO(&rfds);
-    FD_SET(inotify_fd_, &rfds);
-
-    // Wait until some inotify events are available.
-    int select_result =
-        HANDLE_EINTR(select(inotify_fd_ + 1, &rfds, nullptr, nullptr, nullptr));
-    if (select_result < 0) {
-      DPLOG(WARNING) << "select failed";
-      return;
-    }
-
-    // Adjust buffer size to current event queue size.
-    int buffer_size;
-    int ioctl_result = HANDLE_EINTR(ioctl(inotify_fd_, FIONREAD, &buffer_size));
-
-    if (ioctl_result != 0) {
-      DPLOG(WARNING) << "ioctl failed";
-      return;
-    }
-
-    std::vector<char> buffer(buffer_size);
-
-    ssize_t bytes_read =
-        HANDLE_EINTR(read(inotify_fd_, &buffer[0], buffer_size));
-
-    if (bytes_read < 0) {
-      DPLOG(WARNING) << "read from inotify fd failed";
-      return;
-    }
-
-    ssize_t i = 0;
-    while (i < bytes_read) {
-      inotify_event* event = reinterpret_cast<inotify_event*>(&buffer[i]);
-      size_t event_size = sizeof(inotify_event) + event->len;
-      DCHECK(i + event_size <= static_cast<size_t>(bytes_read));
-      g_inotify_reader.Get().OnInotifyEvent(event);
-      i += event_size;
-    }
-  }
-}
-
-InotifyReader::InotifyReader()
-    : inotify_fd_(inotify_init()),
-      thread_delegate_(inotify_fd_),
-      valid_(false) {
-  if (inotify_fd_ < 0) {
-    PLOG(ERROR) << "inotify_init() failed";
-    return;
-  }
-
-  if (!StartThread())
-    return;
-
-  valid_ = true;
-}
-
-bool InotifyReader::StartThread() {
-  // This object is LazyInstance::Leaky, so thread_delegate_ will outlive the
-  // thread.
-  return PlatformThread::CreateNonJoinable(0, &thread_delegate_);
-}
-
-InotifyReader::Watch InotifyReader::AddWatch(
-    const FilePath& path, FilePathWatcherImpl* watcher) {
-  if (!valid_)
-    return kInvalidWatch;
-
-  AutoLock auto_lock(lock_);
-
-  Watch watch = inotify_add_watch(inotify_fd_, path.value().c_str(),
-                                  IN_ATTRIB | IN_CREATE | IN_DELETE |
-                                  IN_CLOSE_WRITE | IN_MOVE |
-                                  IN_ONLYDIR);
-
-  if (watch == kInvalidWatch)
-    return kInvalidWatch;
-
-  watchers_[watch].insert(watcher);
-
-  return watch;
-}
-
-void InotifyReader::RemoveWatch(Watch watch, FilePathWatcherImpl* watcher) {
-  if (!valid_ || (watch == kInvalidWatch))
-    return;
-
-  AutoLock auto_lock(lock_);
-
-  watchers_[watch].erase(watcher);
-
-  if (watchers_[watch].empty()) {
-    watchers_.erase(watch);
-    inotify_rm_watch(inotify_fd_, watch);
-  }
-}
-
-void InotifyReader::OnInotifyEvent(const inotify_event* event) {
-  if (event->mask & IN_IGNORED)
-    return;
-
-  FilePath::StringType child(event->len ? event->name : FILE_PATH_LITERAL(""));
-  AutoLock auto_lock(lock_);
-
-  for (WatcherSet::iterator watcher = watchers_[event->wd].begin();
-       watcher != watchers_[event->wd].end();
-       ++watcher) {
-    (*watcher)->OnFilePathChanged(event->wd,
-                                  child,
-                                  event->mask & (IN_CREATE | IN_MOVED_TO),
-                                  event->mask & (IN_DELETE | IN_MOVED_FROM),
-                                  event->mask & IN_ISDIR);
-  }
-}
-
-FilePathWatcherImpl::FilePathWatcherImpl()
-    : recursive_(false), weak_factory_(this) {
-  weak_ptr_ = weak_factory_.GetWeakPtr();
-}
-
-FilePathWatcherImpl::~FilePathWatcherImpl() {
-  DCHECK(!task_runner() || task_runner()->RunsTasksInCurrentSequence());
-}
-
-void FilePathWatcherImpl::OnFilePathChanged(InotifyReader::Watch fired_watch,
-                                            const FilePath::StringType& child,
-                                            bool created,
-                                            bool deleted,
-                                            bool is_dir) {
-  DCHECK(!task_runner()->RunsTasksInCurrentSequence());
-
-  // This method is invoked on the Inotify thread. Switch to task_runner() to
-  // access |watches_| safely. Use a WeakPtr to prevent the callback from
-  // running after |this| is destroyed (i.e. after the watch is cancelled).
-  task_runner()->PostTask(
-      FROM_HERE,
-      BindOnce(&FilePathWatcherImpl::OnFilePathChangedOnOriginSequence,
-               weak_ptr_, fired_watch, child, created, deleted, is_dir));
-}
-
-void FilePathWatcherImpl::OnFilePathChangedOnOriginSequence(
-    InotifyReader::Watch fired_watch,
-    const FilePath::StringType& child,
-    bool created,
-    bool deleted,
-    bool is_dir) {
-  DCHECK(task_runner()->RunsTasksInCurrentSequence());
-  DCHECK(!watches_.empty());
-  DCHECK(HasValidWatchVector());
-
-  // Used below to avoid multiple recursive updates.
-  bool did_update = false;
-
-  // Find the entry in |watches_| that corresponds to |fired_watch|.
-  for (size_t i = 0; i < watches_.size(); ++i) {
-    const WatchEntry& watch_entry = watches_[i];
-    if (fired_watch != watch_entry.watch)
-      continue;
-
-    // Check whether a path component of |target_| changed.
-    bool change_on_target_path =
-        child.empty() ||
-        (child == watch_entry.linkname) ||
-        (child == watch_entry.subdir);
-
-    // Check if the change references |target_| or a direct child of |target_|.
-    bool target_changed;
-    if (watch_entry.subdir.empty()) {
-      // The fired watch is for a WatchEntry without a subdir. Thus for a given
-      // |target_| = "/path/to/foo", this is for "foo". Here, check either:
-      // - the target has no symlink: it is the target and it changed.
-      // - the target has a symlink, and it matches |child|.
-      target_changed = (watch_entry.linkname.empty() ||
-                        child == watch_entry.linkname);
-    } else {
-      // The fired watch is for a WatchEntry with a subdir. Thus for a given
-      // |target_| = "/path/to/foo", this is for {"/", "/path", "/path/to"}.
-      // So we can safely access the next WatchEntry since we have not reached
-      // the end yet. Check |watch_entry| is for "/path/to", i.e. the next
-      // element is "foo".
-      bool next_watch_may_be_for_target = watches_[i + 1].subdir.empty();
-      if (next_watch_may_be_for_target) {
-        // The current |watch_entry| is for "/path/to", so check if the |child|
-        // that changed is "foo".
-        target_changed = watch_entry.subdir == child;
-      } else {
-        // The current |watch_entry| is not for "/path/to", so the next entry
-        // cannot be "foo". Thus |target_| has not changed.
-        target_changed = false;
-      }
-    }
-
-    // Update watches if a directory component of the |target_| path
-    // (dis)appears. Note that we don't add the additional restriction of
-    // checking the event mask to see if it is for a directory here as changes
-    // to symlinks on the target path will not have IN_ISDIR set in the event
-    // masks. As a result we may sometimes call UpdateWatches() unnecessarily.
-    if (change_on_target_path && (created || deleted) && !did_update) {
-      UpdateWatches();
-      did_update = true;
-    }
-
-    // Report the following events:
-    //  - The target or a direct child of the target got changed (in case the
-    //    watched path refers to a directory).
-    //  - One of the parent directories got moved or deleted, since the target
-    //    disappears in this case.
-    //  - One of the parent directories appears. The event corresponding to
-    //    the target appearing might have been missed in this case, so recheck.
-    if (target_changed ||
-        (change_on_target_path && deleted) ||
-        (change_on_target_path && created && PathExists(target_))) {
-      if (!did_update) {
-        UpdateRecursiveWatches(fired_watch, is_dir);
-        did_update = true;
-      }
-      callback_.Run(target_, false /* error */);
-      return;
-    }
-  }
-
-  if (ContainsKey(recursive_paths_by_watch_, fired_watch)) {
-    if (!did_update)
-      UpdateRecursiveWatches(fired_watch, is_dir);
-    callback_.Run(target_, false /* error */);
-  }
-}
-
-bool FilePathWatcherImpl::Watch(const FilePath& path,
-                                bool recursive,
-                                const FilePathWatcher::Callback& callback) {
-  DCHECK(target_.empty());
-
-  set_task_runner(SequencedTaskRunnerHandle::Get());
-  callback_ = callback;
-  target_ = path;
-  recursive_ = recursive;
-
-  std::vector<FilePath::StringType> comps;
-  target_.GetComponents(&comps);
-  DCHECK(!comps.empty());
-  for (size_t i = 1; i < comps.size(); ++i)
-    watches_.push_back(WatchEntry(comps[i]));
-  watches_.push_back(WatchEntry(FilePath::StringType()));
-  UpdateWatches();
-  return true;
-}
-
-void FilePathWatcherImpl::Cancel() {
-  if (!callback_) {
-    // Watch() was never called.
-    set_cancelled();
-    return;
-  }
-
-  DCHECK(task_runner()->RunsTasksInCurrentSequence());
-  DCHECK(!is_cancelled());
-
-  set_cancelled();
-  callback_.Reset();
-
-  for (size_t i = 0; i < watches_.size(); ++i)
-    g_inotify_reader.Get().RemoveWatch(watches_[i].watch, this);
-  watches_.clear();
-  target_.clear();
-  RemoveRecursiveWatches();
-}
-
-void FilePathWatcherImpl::UpdateWatches() {
-  // Ensure this runs on the task_runner() exclusively in order to avoid
-  // concurrency issues.
-  DCHECK(task_runner()->RunsTasksInCurrentSequence());
-  DCHECK(HasValidWatchVector());
-
-  // Walk the list of watches and update them as we go.
-  FilePath path(FILE_PATH_LITERAL("/"));
-  for (size_t i = 0; i < watches_.size(); ++i) {
-    WatchEntry& watch_entry = watches_[i];
-    InotifyReader::Watch old_watch = watch_entry.watch;
-    watch_entry.watch = InotifyReader::kInvalidWatch;
-    watch_entry.linkname.clear();
-    watch_entry.watch = g_inotify_reader.Get().AddWatch(path, this);
-    if (watch_entry.watch == InotifyReader::kInvalidWatch) {
-      // Ignore the error code (beyond symlink handling) to attempt to add
-      // watches on accessible children of unreadable directories. Note that
-      // this is a best-effort attempt; we may not catch events in this
-      // scenario.
-      if (IsLink(path))
-        AddWatchForBrokenSymlink(path, &watch_entry);
-    }
-    if (old_watch != watch_entry.watch)
-      g_inotify_reader.Get().RemoveWatch(old_watch, this);
-    path = path.Append(watch_entry.subdir);
-  }
-
-  UpdateRecursiveWatches(InotifyReader::kInvalidWatch,
-                         false /* is directory? */);
-}
-
-void FilePathWatcherImpl::UpdateRecursiveWatches(
-    InotifyReader::Watch fired_watch,
-    bool is_dir) {
-  DCHECK(HasValidWatchVector());
-
-  if (!recursive_)
-    return;
-
-  if (!DirectoryExists(target_)) {
-    RemoveRecursiveWatches();
-    return;
-  }
-
-  // Check to see if this is a forced update or if some component of |target_|
-  // has changed. For these cases, redo the watches for |target_| and below.
-  if (!ContainsKey(recursive_paths_by_watch_, fired_watch) &&
-      fired_watch != watches_.back().watch) {
-    UpdateRecursiveWatchesForPath(target_);
-    return;
-  }
-
-  // Underneath |target_|, only directory changes trigger watch updates.
-  if (!is_dir)
-    return;
-
-  const FilePath& changed_dir =
-      ContainsKey(recursive_paths_by_watch_, fired_watch) ?
-      recursive_paths_by_watch_[fired_watch] :
-      target_;
-
-  std::map<FilePath, InotifyReader::Watch>::iterator start_it =
-      recursive_watches_by_path_.lower_bound(changed_dir);
-  std::map<FilePath, InotifyReader::Watch>::iterator end_it = start_it;
-  for (; end_it != recursive_watches_by_path_.end(); ++end_it) {
-    const FilePath& cur_path = end_it->first;
-    if (!changed_dir.IsParent(cur_path))
-      break;
-    if (!DirectoryExists(cur_path))
-      g_inotify_reader.Get().RemoveWatch(end_it->second, this);
-  }
-  recursive_watches_by_path_.erase(start_it, end_it);
-  UpdateRecursiveWatchesForPath(changed_dir);
-}
-
-void FilePathWatcherImpl::UpdateRecursiveWatchesForPath(const FilePath& path) {
-  DCHECK(recursive_);
-  DCHECK(!path.empty());
-  DCHECK(DirectoryExists(path));
-
-  // Note: SHOW_SYM_LINKS exposes symlinks as symlinks, so they are ignored
-  // rather than followed. Following symlinks can easily lead to the undesirable
-  // situation where the entire file system is being watched.
-  FileEnumerator enumerator(
-      path,
-      true /* recursive enumeration */,
-      FileEnumerator::DIRECTORIES | FileEnumerator::SHOW_SYM_LINKS);
-  for (FilePath current = enumerator.Next();
-       !current.empty();
-       current = enumerator.Next()) {
-    DCHECK(enumerator.GetInfo().IsDirectory());
-
-    if (!ContainsKey(recursive_watches_by_path_, current)) {
-      // Add new watches.
-      InotifyReader::Watch watch =
-          g_inotify_reader.Get().AddWatch(current, this);
-      TrackWatchForRecursion(watch, current);
-    } else {
-      // Update existing watches.
-      InotifyReader::Watch old_watch = recursive_watches_by_path_[current];
-      DCHECK_NE(InotifyReader::kInvalidWatch, old_watch);
-      InotifyReader::Watch watch =
-          g_inotify_reader.Get().AddWatch(current, this);
-      if (watch != old_watch) {
-        g_inotify_reader.Get().RemoveWatch(old_watch, this);
-        recursive_paths_by_watch_.erase(old_watch);
-        recursive_watches_by_path_.erase(current);
-        TrackWatchForRecursion(watch, current);
-      }
-    }
-  }
-}
-
-void FilePathWatcherImpl::TrackWatchForRecursion(InotifyReader::Watch watch,
-                                                 const FilePath& path) {
-  DCHECK(recursive_);
-  DCHECK(!path.empty());
-  DCHECK(target_.IsParent(path));
-
-  if (watch == InotifyReader::kInvalidWatch)
-    return;
-
-  DCHECK(!ContainsKey(recursive_paths_by_watch_, watch));
-  DCHECK(!ContainsKey(recursive_watches_by_path_, path));
-  recursive_paths_by_watch_[watch] = path;
-  recursive_watches_by_path_[path] = watch;
-}
-
-void FilePathWatcherImpl::RemoveRecursiveWatches() {
-  if (!recursive_)
-    return;
-
-  for (const auto& it : recursive_paths_by_watch_)
-    g_inotify_reader.Get().RemoveWatch(it.first, this);
-
-  recursive_paths_by_watch_.clear();
-  recursive_watches_by_path_.clear();
-}
-
-void FilePathWatcherImpl::AddWatchForBrokenSymlink(const FilePath& path,
-                                                   WatchEntry* watch_entry) {
-  DCHECK_EQ(InotifyReader::kInvalidWatch, watch_entry->watch);
-  FilePath link;
-  if (!ReadSymbolicLink(path, &link))
-    return;
-
-  if (!link.IsAbsolute())
-    link = path.DirName().Append(link);
-
-  // Try watching symlink target directory. If the link target is "/", then we
-  // shouldn't get here in normal situations and if we do, we'd watch "/" for
-  // changes to a component "/" which is harmless so no special treatment of
-  // this case is required.
-  InotifyReader::Watch watch =
-      g_inotify_reader.Get().AddWatch(link.DirName(), this);
-  if (watch == InotifyReader::kInvalidWatch) {
-    // TODO(craig) Symlinks only work if the parent directory for the target
-    // exist. Ideally we should make sure we've watched all the components of
-    // the symlink path for changes. See crbug.com/91561 for details.
-    DPLOG(WARNING) << "Watch failed for "  << link.DirName().value();
-    return;
-  }
-  watch_entry->watch = watch;
-  watch_entry->linkname = link.BaseName().value();
-}
-
-bool FilePathWatcherImpl::HasValidWatchVector() const {
-  if (watches_.empty())
-    return false;
-  for (size_t i = 0; i < watches_.size() - 1; ++i) {
-    if (watches_[i].subdir.empty())
-      return false;
-  }
-  return watches_.back().subdir.empty();
-}
-
-}  // namespace
-
-FilePathWatcher::FilePathWatcher() {
-  sequence_checker_.DetachFromSequence();
-  impl_ = std::make_unique<FilePathWatcherImpl>();
-}
-
-}  // namespace base
diff --git a/base/files/file_path_watcher_mac.cc b/base/files/file_path_watcher_mac.cc
deleted file mode 100644
index bd5a559..0000000
--- a/base/files/file_path_watcher_mac.cc
+++ /dev/null
@@ -1,63 +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 <memory>
-
-#include "base/files/file_path_watcher.h"
-#include "base/files/file_path_watcher_kqueue.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "build_config.h"
-
-#if !defined(OS_IOS)
-#include "base/files/file_path_watcher_fsevents.h"
-#endif
-
-namespace base {
-
-namespace {
-
-class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate {
- public:
-  FilePathWatcherImpl() = default;
-  ~FilePathWatcherImpl() override = default;
-
-  bool Watch(const FilePath& path,
-             bool recursive,
-             const FilePathWatcher::Callback& callback) override {
-    // Use kqueue for non-recursive watches and FSEvents for recursive ones.
-    DCHECK(!impl_.get());
-    if (recursive) {
-      if (!FilePathWatcher::RecursiveWatchAvailable())
-        return false;
-#if !defined(OS_IOS)
-      impl_ = std::make_unique<FilePathWatcherFSEvents>();
-#endif  // OS_IOS
-    } else {
-      impl_ = std::make_unique<FilePathWatcherKQueue>();
-    }
-    DCHECK(impl_.get());
-    return impl_->Watch(path, recursive, callback);
-  }
-
-  void Cancel() override {
-    if (impl_.get())
-      impl_->Cancel();
-    set_cancelled();
-  }
-
- private:
-  std::unique_ptr<PlatformDelegate> impl_;
-
-  DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
-};
-
-}  // namespace
-
-FilePathWatcher::FilePathWatcher() {
-  sequence_checker_.DetachFromSequence();
-  impl_ = std::make_unique<FilePathWatcherImpl>();
-}
-
-}  // namespace base
diff --git a/base/files/file_path_watcher_stub.cc b/base/files/file_path_watcher_stub.cc
deleted file mode 100644
index 93a5bab..0000000
--- a/base/files/file_path_watcher_stub.cc
+++ /dev/null
@@ -1,41 +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 file exists for Unix systems which don't have the inotify headers, and
-// thus cannot build file_watcher_inotify.cc
-
-#include "base/files/file_path_watcher.h"
-
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-
-namespace base {
-
-namespace {
-
-class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate {
- public:
-  FilePathWatcherImpl() = default;
-  ~FilePathWatcherImpl() override = default;
-
-  bool Watch(const FilePath& path,
-             bool recursive,
-             const FilePathWatcher::Callback& callback) override {
-    return false;
-  }
-
-  void Cancel() override {}
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
-};
-
-}  // namespace
-
-FilePathWatcher::FilePathWatcher() {
-  sequence_checker_.DetachFromSequence();
-  impl_ = std::make_unique<FilePathWatcherImpl>();
-}
-
-}  // namespace base
diff --git a/base/files/file_path_watcher_win.cc b/base/files/file_path_watcher_win.cc
deleted file mode 100644
index 4614750..0000000
--- a/base/files/file_path_watcher_win.cc
+++ /dev/null
@@ -1,290 +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 "base/files/file_path_watcher.h"
-
-#include "base/bind.h"
-#include "base/files/file.h"
-#include "base/files/file_path.h"
-#include "base/files/file_util.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-#include "base/time/time.h"
-#include "base/win/object_watcher.h"
-
-#include <windows.h>
-
-namespace base {
-
-namespace {
-
-class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate,
-                            public base::win::ObjectWatcher::Delegate {
- public:
-  FilePathWatcherImpl()
-      : handle_(INVALID_HANDLE_VALUE),
-        recursive_watch_(false) {}
-  ~FilePathWatcherImpl() override;
-
-  // FilePathWatcher::PlatformDelegate:
-  bool Watch(const FilePath& path,
-             bool recursive,
-             const FilePathWatcher::Callback& callback) override;
-  void Cancel() override;
-
-  // base::win::ObjectWatcher::Delegate:
-  void OnObjectSignaled(HANDLE object) override;
-
- private:
-  // Setup a watch handle for directory |dir|. Set |recursive| to true to watch
-  // the directory sub trees. Returns true if no fatal error occurs. |handle|
-  // will receive the handle value if |dir| is watchable, otherwise
-  // INVALID_HANDLE_VALUE.
-  static bool SetupWatchHandle(const FilePath& dir,
-                               bool recursive,
-                               HANDLE* handle) WARN_UNUSED_RESULT;
-
-  // (Re-)Initialize the watch handle.
-  bool UpdateWatch() WARN_UNUSED_RESULT;
-
-  // Destroy the watch handle.
-  void DestroyWatch();
-
-  // Callback to notify upon changes.
-  FilePathWatcher::Callback callback_;
-
-  // Path we're supposed to watch (passed to callback).
-  FilePath target_;
-
-  // Set to true in the destructor.
-  bool* was_deleted_ptr_ = nullptr;
-
-  // Handle for FindFirstChangeNotification.
-  HANDLE handle_;
-
-  // ObjectWatcher to watch handle_ for events.
-  base::win::ObjectWatcher watcher_;
-
-  // Set to true to watch the sub trees of the specified directory file path.
-  bool recursive_watch_;
-
-  // Keep track of the last modified time of the file.  We use nulltime
-  // to represent the file not existing.
-  Time last_modified_;
-
-  // The time at which we processed the first notification with the
-  // |last_modified_| time stamp.
-  Time first_notification_;
-
-  DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl);
-};
-
-FilePathWatcherImpl::~FilePathWatcherImpl() {
-  DCHECK(!task_runner() || task_runner()->RunsTasksInCurrentSequence());
-  if (was_deleted_ptr_)
-    *was_deleted_ptr_ = true;
-}
-
-bool FilePathWatcherImpl::Watch(const FilePath& path,
-                                bool recursive,
-                                const FilePathWatcher::Callback& callback) {
-  DCHECK(target_.value().empty());  // Can only watch one path.
-
-  set_task_runner(SequencedTaskRunnerHandle::Get());
-  callback_ = callback;
-  target_ = path;
-  recursive_watch_ = recursive;
-
-  File::Info file_info;
-  if (GetFileInfo(target_, &file_info)) {
-    last_modified_ = file_info.last_modified;
-    first_notification_ = Time::Now();
-  }
-
-  if (!UpdateWatch())
-    return false;
-
-  watcher_.StartWatchingOnce(handle_, this);
-
-  return true;
-}
-
-void FilePathWatcherImpl::Cancel() {
-  if (callback_.is_null()) {
-    // Watch was never called, or the |task_runner_| has already quit.
-    set_cancelled();
-    return;
-  }
-
-  DCHECK(task_runner()->RunsTasksInCurrentSequence());
-  set_cancelled();
-
-  if (handle_ != INVALID_HANDLE_VALUE)
-    DestroyWatch();
-
-  callback_.Reset();
-}
-
-void FilePathWatcherImpl::OnObjectSignaled(HANDLE object) {
-  DCHECK(task_runner()->RunsTasksInCurrentSequence());
-  DCHECK_EQ(object, handle_);
-  DCHECK(!was_deleted_ptr_);
-
-  bool was_deleted = false;
-  was_deleted_ptr_ = &was_deleted;
-
-  if (!UpdateWatch()) {
-    callback_.Run(target_, true /* error */);
-    return;
-  }
-
-  // Check whether the event applies to |target_| and notify the callback.
-  File::Info file_info;
-  bool file_exists = GetFileInfo(target_, &file_info);
-  if (recursive_watch_) {
-    // Only the mtime of |target_| is tracked but in a recursive watch,
-    // some other file or directory may have changed so all notifications
-    // are passed through. It is possible to figure out which file changed
-    // using ReadDirectoryChangesW() instead of FindFirstChangeNotification(),
-    // but that function is quite complicated:
-    // http://qualapps.blogspot.com/2010/05/understanding-readdirectorychangesw.html
-    callback_.Run(target_, false);
-  } else if (file_exists && (last_modified_.is_null() ||
-             last_modified_ != file_info.last_modified)) {
-    last_modified_ = file_info.last_modified;
-    first_notification_ = Time::Now();
-    callback_.Run(target_, false);
-  } else if (file_exists && last_modified_ == file_info.last_modified &&
-             !first_notification_.is_null()) {
-    // The target's last modification time is equal to what's on record. This
-    // means that either an unrelated event occurred, or the target changed
-    // again (file modification times only have a resolution of 1s). Comparing
-    // file modification times against the wall clock is not reliable to find
-    // out whether the change is recent, since this code might just run too
-    // late. Moreover, there's no guarantee that file modification time and wall
-    // clock times come from the same source.
-    //
-    // Instead, the time at which the first notification carrying the current
-    // |last_notified_| time stamp is recorded. Later notifications that find
-    // the same file modification time only need to be forwarded until wall
-    // clock has advanced one second from the initial notification. After that
-    // interval, client code is guaranteed to having seen the current revision
-    // of the file.
-    if (Time::Now() - first_notification_ > TimeDelta::FromSeconds(1)) {
-      // Stop further notifications for this |last_modification_| time stamp.
-      first_notification_ = Time();
-    }
-    callback_.Run(target_, false);
-  } else if (!file_exists && !last_modified_.is_null()) {
-    last_modified_ = Time();
-    callback_.Run(target_, false);
-  }
-
-  // The watch may have been cancelled by the callback.
-  if (!was_deleted) {
-    watcher_.StartWatchingOnce(handle_, this);
-    was_deleted_ptr_ = nullptr;
-  }
-}
-
-// static
-bool FilePathWatcherImpl::SetupWatchHandle(const FilePath& dir,
-                                           bool recursive,
-                                           HANDLE* handle) {
-  *handle = FindFirstChangeNotification(
-      dir.value().c_str(),
-      recursive,
-      FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_SIZE |
-      FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_DIR_NAME |
-      FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SECURITY);
-  if (*handle != INVALID_HANDLE_VALUE) {
-    // Make sure the handle we got points to an existing directory. It seems
-    // that windows sometimes hands out watches to directories that are
-    // about to go away, but doesn't sent notifications if that happens.
-    if (!DirectoryExists(dir)) {
-      FindCloseChangeNotification(*handle);
-      *handle = INVALID_HANDLE_VALUE;
-    }
-    return true;
-  }
-
-  // If FindFirstChangeNotification failed because the target directory
-  // doesn't exist, access is denied (happens if the file is already gone but
-  // there are still handles open), or the target is not a directory, try the
-  // immediate parent directory instead.
-  DWORD error_code = GetLastError();
-  if (error_code != ERROR_FILE_NOT_FOUND &&
-      error_code != ERROR_PATH_NOT_FOUND &&
-      error_code != ERROR_ACCESS_DENIED &&
-      error_code != ERROR_SHARING_VIOLATION &&
-      error_code != ERROR_DIRECTORY) {
-    DPLOG(ERROR) << "FindFirstChangeNotification failed for "
-                 << dir.value();
-    return false;
-  }
-
-  return true;
-}
-
-bool FilePathWatcherImpl::UpdateWatch() {
-  if (handle_ != INVALID_HANDLE_VALUE)
-    DestroyWatch();
-
-  // Start at the target and walk up the directory chain until we succesfully
-  // create a watch handle in |handle_|. |child_dirs| keeps a stack of child
-  // directories stripped from target, in reverse order.
-  std::vector<FilePath> child_dirs;
-  FilePath watched_path(target_);
-  while (true) {
-    if (!SetupWatchHandle(watched_path, recursive_watch_, &handle_))
-      return false;
-
-    // Break if a valid handle is returned. Try the parent directory otherwise.
-    if (handle_ != INVALID_HANDLE_VALUE)
-      break;
-
-    // Abort if we hit the root directory.
-    child_dirs.push_back(watched_path.BaseName());
-    FilePath parent(watched_path.DirName());
-    if (parent == watched_path) {
-      DLOG(ERROR) << "Reached the root directory";
-      return false;
-    }
-    watched_path = parent;
-  }
-
-  // At this point, handle_ is valid. However, the bottom-up search that the
-  // above code performs races against directory creation. So try to walk back
-  // down and see whether any children appeared in the mean time.
-  while (!child_dirs.empty()) {
-    watched_path = watched_path.Append(child_dirs.back());
-    child_dirs.pop_back();
-    HANDLE temp_handle = INVALID_HANDLE_VALUE;
-    if (!SetupWatchHandle(watched_path, recursive_watch_, &temp_handle))
-      return false;
-    if (temp_handle == INVALID_HANDLE_VALUE)
-      break;
-    FindCloseChangeNotification(handle_);
-    handle_ = temp_handle;
-  }
-
-  return true;
-}
-
-void FilePathWatcherImpl::DestroyWatch() {
-  watcher_.StopWatching();
-  FindCloseChangeNotification(handle_);
-  handle_ = INVALID_HANDLE_VALUE;
-}
-
-}  // namespace
-
-FilePathWatcher::FilePathWatcher() {
-  sequence_checker_.DetachFromSequence();
-  impl_ = std::make_unique<FilePathWatcherImpl>();
-}
-
-}  // namespace base
diff --git a/base/files/file_posix.cc b/base/files/file_posix.cc
index b7a3e9d..630f1ff 100644
--- a/base/files/file_posix.cc
+++ b/base/files/file_posix.cc
@@ -13,7 +13,6 @@
 #include "base/logging.h"
 #include "base/posix/eintr_wrapper.h"
 #include "base/strings/utf_string_conversions.h"
-#include "base/threading/thread_restrictions.h"
 #include "build_config.h"
 
 namespace base {
@@ -28,12 +27,10 @@
 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL) || \
     defined(OS_ANDROID) && __ANDROID_API__ < 21
 int CallFstat(int fd, stat_wrapper_t *sb) {
-  AssertBlockingAllowed();
   return fstat(fd, sb);
 }
 #else
 int CallFstat(int fd, stat_wrapper_t *sb) {
-  AssertBlockingAllowed();
   return fstat64(fd, sb);
 }
 #endif
@@ -173,17 +170,12 @@
   if (!IsValid())
     return;
 
-  SCOPED_FILE_TRACE("Close");
-  AssertBlockingAllowed();
   file_.reset();
 }
 
 int64_t File::Seek(Whence whence, int64_t offset) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
 
-  SCOPED_FILE_TRACE_WITH_SIZE("Seek", offset);
-
 #if defined(OS_ANDROID)
   static_assert(sizeof(int64_t) == sizeof(off64_t), "off64_t must be 64 bits");
   return lseek64(file_.get(), static_cast<off64_t>(offset),
@@ -196,13 +188,10 @@
 }
 
 int File::Read(int64_t offset, char* data, int size) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
   if (size < 0)
     return -1;
 
-  SCOPED_FILE_TRACE_WITH_SIZE("Read", size);
-
   int bytes_read = 0;
   int rv;
   do {
@@ -218,13 +207,10 @@
 }
 
 int File::ReadAtCurrentPos(char* data, int size) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
   if (size < 0)
     return -1;
 
-  SCOPED_FILE_TRACE_WITH_SIZE("ReadAtCurrentPos", size);
-
   int bytes_read = 0;
   int rv;
   do {
@@ -239,25 +225,19 @@
 }
 
 int File::ReadNoBestEffort(int64_t offset, char* data, int size) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
-  SCOPED_FILE_TRACE_WITH_SIZE("ReadNoBestEffort", size);
   return HANDLE_EINTR(pread(file_.get(), data, size, offset));
 }
 
 int File::ReadAtCurrentPosNoBestEffort(char* data, int size) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
   if (size < 0)
     return -1;
 
-  SCOPED_FILE_TRACE_WITH_SIZE("ReadAtCurrentPosNoBestEffort", size);
   return HANDLE_EINTR(read(file_.get(), data, size));
 }
 
 int File::Write(int64_t offset, const char* data, int size) {
-  AssertBlockingAllowed();
-
   if (IsOpenAppend(file_.get()))
     return WriteAtCurrentPos(data, size);
 
@@ -265,8 +245,6 @@
   if (size < 0)
     return -1;
 
-  SCOPED_FILE_TRACE_WITH_SIZE("Write", size);
-
   int bytes_written = 0;
   int rv;
   do {
@@ -282,13 +260,10 @@
 }
 
 int File::WriteAtCurrentPos(const char* data, int size) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
   if (size < 0)
     return -1;
 
-  SCOPED_FILE_TRACE_WITH_SIZE("WriteAtCurrentPos", size);
-
   int bytes_written = 0;
   int rv;
   do {
@@ -304,20 +279,16 @@
 }
 
 int File::WriteAtCurrentPosNoBestEffort(const char* data, int size) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
   if (size < 0)
     return -1;
 
-  SCOPED_FILE_TRACE_WITH_SIZE("WriteAtCurrentPosNoBestEffort", size);
   return HANDLE_EINTR(write(file_.get(), data, size));
 }
 
 int64_t File::GetLength() {
   DCHECK(IsValid());
 
-  SCOPED_FILE_TRACE("GetLength");
-
   stat_wrapper_t file_info;
   if (CallFstat(file_.get(), &file_info))
     return -1;
@@ -326,19 +297,14 @@
 }
 
 bool File::SetLength(int64_t length) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
 
-  SCOPED_FILE_TRACE_WITH_SIZE("SetLength", length);
   return !CallFtruncate(file_.get(), length);
 }
 
 bool File::SetTimes(Time last_access_time, Time last_modified_time) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
 
-  SCOPED_FILE_TRACE("SetTimes");
-
   timeval times[2];
   times[0] = last_access_time.ToTimeVal();
   times[1] = last_modified_time.ToTimeVal();
@@ -349,8 +315,6 @@
 bool File::GetInfo(Info* info) {
   DCHECK(IsValid());
 
-  SCOPED_FILE_TRACE("GetInfo");
-
   stat_wrapper_t file_info;
   if (CallFstat(file_.get(), &file_info))
     return false;
@@ -361,12 +325,10 @@
 
 #if !defined(OS_FUCHSIA)
 File::Error File::Lock() {
-  SCOPED_FILE_TRACE("Lock");
   return CallFcntlFlock(file_.get(), true);
 }
 
 File::Error File::Unlock() {
-  SCOPED_FILE_TRACE("Unlock");
   return CallFcntlFlock(file_.get(), false);
 }
 #endif
@@ -375,8 +337,6 @@
   if (!IsValid())
     return File();
 
-  SCOPED_FILE_TRACE("Duplicate");
-
   PlatformFile other_fd = HANDLE_EINTR(dup(GetPlatformFile()));
   if (other_fd == -1)
     return File(File::GetLastFileError());
@@ -426,7 +386,6 @@
 #if !defined(OS_NACL)
 // TODO(erikkay): does it make sense to support FLAG_EXCLUSIVE_* here?
 void File::DoInitialize(const FilePath& path, uint32_t flags) {
-  AssertBlockingAllowed();
   DCHECK(!IsValid());
 
   int open_flags = 0;
@@ -512,9 +471,7 @@
 #endif  // !defined(OS_NACL)
 
 bool File::Flush() {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
-  SCOPED_FILE_TRACE("Flush");
 
 #if defined(OS_NACL)
   NOTIMPLEMENTED();  // NaCl doesn't implement fsync.
diff --git a/base/files/file_tracing.cc b/base/files/file_tracing.cc
deleted file mode 100644
index 48f5741..0000000
--- a/base/files/file_tracing.cc
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2015 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/files/file_tracing.h"
-
-#include "base/atomicops.h"
-#include "base/files/file.h"
-
-using base::subtle::AtomicWord;
-
-namespace base {
-
-namespace {
-AtomicWord g_provider;
-}
-
-FileTracing::Provider* GetProvider() {
-  AtomicWord provider = base::subtle::Acquire_Load(&g_provider);
-  return reinterpret_cast<FileTracing::Provider*>(provider);
-}
-
-// static
-bool FileTracing::IsCategoryEnabled() {
-  FileTracing::Provider* provider = GetProvider();
-  return provider && provider->FileTracingCategoryIsEnabled();
-}
-
-// static
-void FileTracing::SetProvider(FileTracing::Provider* provider) {
-  base::subtle::Release_Store(&g_provider,
-                              reinterpret_cast<AtomicWord>(provider));
-}
-
-FileTracing::ScopedEnabler::ScopedEnabler() {
-  FileTracing::Provider* provider = GetProvider();
-  if (provider)
-    provider->FileTracingEnable(this);
-}
-
-FileTracing::ScopedEnabler::~ScopedEnabler() {
-  FileTracing::Provider* provider = GetProvider();
-  if (provider)
-    provider->FileTracingDisable(this);
-}
-
-FileTracing::ScopedTrace::ScopedTrace() : id_(nullptr) {}
-
-FileTracing::ScopedTrace::~ScopedTrace() {
-  if (id_) {
-    FileTracing::Provider* provider = GetProvider();
-    if (provider)
-      provider->FileTracingEventEnd(name_, id_);
-  }
-}
-
-void FileTracing::ScopedTrace::Initialize(const char* name,
-                                          const File* file,
-                                          int64_t size) {
-  id_ = &file->trace_enabler_;
-  name_ = name;
-  GetProvider()->FileTracingEventBegin(name_, id_, file->tracing_path_, size);
-}
-
-}  // namespace base
diff --git a/base/files/file_tracing.h b/base/files/file_tracing.h
deleted file mode 100644
index 1fbfcd4..0000000
--- a/base/files/file_tracing.h
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2015 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_FILES_FILE_TRACING_H_
-#define BASE_FILES_FILE_TRACING_H_
-
-#include <stdint.h>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-
-#define FILE_TRACING_PREFIX "File"
-
-#define SCOPED_FILE_TRACE_WITH_SIZE(name, size) \
-    FileTracing::ScopedTrace scoped_file_trace; \
-    if (FileTracing::IsCategoryEnabled()) \
-      scoped_file_trace.Initialize(FILE_TRACING_PREFIX "::" name, this, size)
-
-#define SCOPED_FILE_TRACE(name) SCOPED_FILE_TRACE_WITH_SIZE(name, 0)
-
-namespace base {
-
-class File;
-class FilePath;
-
-class BASE_EXPORT FileTracing {
- public:
-  // Whether the file tracing category is enabled.
-  static bool IsCategoryEnabled();
-
-  class Provider {
-   public:
-    virtual ~Provider() = default;
-
-    // Whether the file tracing category is currently enabled.
-    virtual bool FileTracingCategoryIsEnabled() const = 0;
-
-    // Enables file tracing for |id|. Must be called before recording events.
-    virtual void FileTracingEnable(const void* id) = 0;
-
-    // Disables file tracing for |id|.
-    virtual void FileTracingDisable(const void* id) = 0;
-
-    // Begins an event for |id| with |name|. |path| tells where in the directory
-    // structure the event is happening (and may be blank). |size| is the number
-    // of bytes involved in the event.
-    virtual void FileTracingEventBegin(const char* name,
-                                       const void* id,
-                                       const FilePath& path,
-                                       int64_t size) = 0;
-
-    // Ends an event for |id| with |name|.
-    virtual void FileTracingEventEnd(const char* name, const void* id) = 0;
-  };
-
-  // Sets a global file tracing provider to query categories and record events.
-  static void SetProvider(Provider* provider);
-
-  // Enables file tracing while in scope.
-  class ScopedEnabler {
-   public:
-    ScopedEnabler();
-    ~ScopedEnabler();
-  };
-
-  class ScopedTrace {
-   public:
-    ScopedTrace();
-    ~ScopedTrace();
-
-    // Called only if the tracing category is enabled. |name| is the name of the
-    // event to trace (e.g. "Read", "Write") and must have an application
-    // lifetime (e.g. static or literal). |file| is the file being traced; must
-    // outlive this class. |size| is the size (in bytes) of this event.
-    void Initialize(const char* name, const File* file, int64_t size);
-
-   private:
-    // The ID of this trace. Based on the |file| passed to |Initialize()|. Must
-    // outlive this class.
-    const void* id_;
-
-    // The name of the event to trace (e.g. "Read", "Write"). Prefixed with
-    // "File".
-    const char* name_;
-
-    DISALLOW_COPY_AND_ASSIGN(ScopedTrace);
-  };
-
-  DISALLOW_COPY_AND_ASSIGN(FileTracing);
-};
-
-}  // namespace base
-
-#endif  // BASE_FILES_FILE_TRACING_H_
diff --git a/base/files/file_util_mac.mm b/base/files/file_util_mac.mm
index 392fbce..0b2e2a0 100644
--- a/base/files/file_util_mac.mm
+++ b/base/files/file_util_mac.mm
@@ -13,12 +13,10 @@
 #include "base/logging.h"
 #include "base/mac/foundation_util.h"
 #include "base/strings/string_util.h"
-#include "base/threading/thread_restrictions.h"
 
 namespace base {
 
 bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
-  AssertBlockingAllowed();
   if (from_path.ReferencesParent() || to_path.ReferencesParent())
     return false;
   return (copyfile(from_path.value().c_str(),
diff --git a/base/files/file_util_posix.cc b/base/files/file_util_posix.cc
index ac327c3..774735c 100644
--- a/base/files/file_util_posix.cc
+++ b/base/files/file_util_posix.cc
@@ -21,7 +21,6 @@
 #include <time.h>
 #include <unistd.h>
 
-#include "base/base_switches.h"
 #include "base/command_line.h"
 #include "base/containers/stack.h"
 #include "base/environment.h"
@@ -30,7 +29,6 @@
 #include "base/files/scoped_file.h"
 #include "base/logging.h"
 #include "base/macros.h"
-#include "base/memory/singleton.h"
 #include "base/posix/eintr_wrapper.h"
 #include "base/stl_util.h"
 #include "base/strings/string_split.h"
@@ -38,8 +36,6 @@
 #include "base/strings/stringprintf.h"
 #include "base/strings/sys_string_conversions.h"
 #include "base/strings/utf_string_conversions.h"
-#include "base/sys_info.h"
-#include "base/threading/thread_restrictions.h"
 #include "base/time/time.h"
 #include "build_config.h"
 
@@ -65,20 +61,16 @@
 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL) || \
     defined(OS_ANDROID) && __ANDROID_API__ < 21
 int CallStat(const char* path, stat_wrapper_t* sb) {
-  AssertBlockingAllowed();
   return stat(path, sb);
 }
 int CallLstat(const char* path, stat_wrapper_t* sb) {
-  AssertBlockingAllowed();
   return lstat(path, sb);
 }
 #else
 int CallStat(const char* path, stat_wrapper_t* sb) {
-  AssertBlockingAllowed();
   return stat64(path, sb);
 }
 int CallLstat(const char* path, stat_wrapper_t* sb) {
-  AssertBlockingAllowed();
   return lstat64(path, sb);
 }
 #endif
@@ -204,7 +196,6 @@
                      const FilePath& to_path,
                      bool recursive,
                      bool open_exclusive) {
-  AssertBlockingAllowed();
   // Some old callers of CopyDirectory want it to support wildcards.
   // After some discussion, we decided to fix those callers.
   // Break loudly here if anyone tries to do this.
@@ -358,7 +349,6 @@
 
 #if !defined(OS_NACL_NONSFI)
 FilePath MakeAbsoluteFilePath(const FilePath& input) {
-  AssertBlockingAllowed();
   char full_path[PATH_MAX];
   if (realpath(input.value().c_str(), full_path) == nullptr)
     return FilePath();
@@ -370,7 +360,6 @@
 // that functionality. If not, remove from file_util_win.cc, otherwise add it
 // here.
 bool DeleteFile(const FilePath& path, bool recursive) {
-  AssertBlockingAllowed();
   const char* path_str = path.value().c_str();
   stat_wrapper_t file_info;
   if (CallLstat(path_str, &file_info) != 0) {
@@ -407,7 +396,6 @@
 bool ReplaceFile(const FilePath& from_path,
                  const FilePath& to_path,
                  File::Error* error) {
-  AssertBlockingAllowed();
   if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
     return true;
   if (error)
@@ -478,7 +466,6 @@
 }
 
 bool PathExists(const FilePath& path) {
-  AssertBlockingAllowed();
 #if defined(OS_ANDROID)
   if (path.IsContentUri()) {
     return ContentUriExists(path);
@@ -489,13 +476,11 @@
 
 #if !defined(OS_NACL_NONSFI)
 bool PathIsWritable(const FilePath& path) {
-  AssertBlockingAllowed();
   return access(path.value().c_str(), W_OK) == 0;
 }
 #endif  // !defined(OS_NACL_NONSFI)
 
 bool DirectoryExists(const FilePath& path) {
-  AssertBlockingAllowed();
   stat_wrapper_t file_info;
   if (CallStat(path.value().c_str(), &file_info) != 0)
     return false;
@@ -518,7 +503,6 @@
 
 int CreateAndOpenFdForTemporaryFileInDir(const FilePath& directory,
                                          FilePath* path) {
-  AssertBlockingAllowed();  // For call to mkstemp().
   *path = directory.Append(TempFileName());
   const std::string& tmpdir_string = path->value();
   // this should be OK since mkstemp just replaces characters in place
@@ -552,7 +536,6 @@
 }
 
 bool GetPosixFilePermissions(const FilePath& path, int* mode) {
-  AssertBlockingAllowed();
   DCHECK(mode);
 
   stat_wrapper_t file_info;
@@ -567,7 +550,6 @@
 
 bool SetPosixFilePermissions(const FilePath& path,
                              int mode) {
-  AssertBlockingAllowed();
   DCHECK_EQ(mode & ~FILE_PERMISSION_MASK, 0);
 
   // Calls stat() so that we can preserve the higher bits like S_ISGID.
@@ -622,14 +604,6 @@
 
 #if !defined(OS_MACOSX)  // Mac implementation is in file_util_mac.mm.
 FilePath GetHomeDir() {
-#if defined(OS_CHROMEOS)
-  if (SysInfo::IsRunningOnChromeOS()) {
-    // On Chrome OS chrome::DIR_USER_DATA is overridden with a primary user
-    // homedir once it becomes available. Return / as the safe option.
-    return FilePath("/");
-  }
-#endif
-
   const char* home_dir = getenv("HOME");
   if (home_dir && home_dir[0])
     return FilePath(home_dir);
@@ -648,7 +622,6 @@
 #endif  // !defined(OS_MACOSX)
 
 bool CreateTemporaryFile(FilePath* path) {
-  AssertBlockingAllowed();  // For call to close().
   FilePath directory;
   if (!GetTempDir(&directory))
     return false;
@@ -671,7 +644,6 @@
 }
 
 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
-  AssertBlockingAllowed();  // For call to close().
   int fd = CreateAndOpenFdForTemporaryFileInDir(dir, temp_file);
   return ((fd >= 0) && !IGNORE_EINTR(close(fd)));
 }
@@ -679,7 +651,6 @@
 static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
                                         const FilePath::StringType& name_tmpl,
                                         FilePath* new_dir) {
-  AssertBlockingAllowed();  // For call to mkdtemp().
   DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
       << "Directory name template must contain \"XXXXXX\".";
 
@@ -716,7 +687,6 @@
 
 bool CreateDirectoryAndGetError(const FilePath& full_path,
                                 File::Error* error) {
-  AssertBlockingAllowed();  // For call to mkdir().
   std::vector<FilePath> subpaths;
 
   // Collect a list of all parent directories.
@@ -801,7 +771,6 @@
   DCHECK(
       strchr(mode, 'e') == nullptr ||
       (strchr(mode, ',') != nullptr && strchr(mode, 'e') > strchr(mode, ',')));
-  AssertBlockingAllowed();
   FILE* result = nullptr;
 #if defined(OS_MACOSX)
   // macOS does not provide a mode character to set O_CLOEXEC; see
@@ -833,7 +802,6 @@
 #endif  // !defined(OS_NACL)
 
 int ReadFile(const FilePath& filename, char* data, int max_size) {
-  AssertBlockingAllowed();
   int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
   if (fd < 0)
     return -1;
@@ -845,7 +813,6 @@
 }
 
 int WriteFile(const FilePath& filename, const char* data, int size) {
-  AssertBlockingAllowed();
   int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
   if (fd < 0)
     return -1;
@@ -874,7 +841,6 @@
 #if !defined(OS_NACL_NONSFI)
 
 bool AppendToFile(const FilePath& filename, const char* data, int size) {
-  AssertBlockingAllowed();
   bool ret = true;
   int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
   if (fd < 0) {
@@ -894,9 +860,6 @@
 }
 
 bool GetCurrentDirectory(FilePath* dir) {
-  // getcwd can return ENOENT, which implies it checks against the disk.
-  AssertBlockingAllowed();
-
   char system_buffer[PATH_MAX] = "";
   if (!getcwd(system_buffer, sizeof(system_buffer))) {
     NOTREACHED();
@@ -907,7 +870,6 @@
 }
 
 bool SetCurrentDirectory(const FilePath& path) {
-  AssertBlockingAllowed();
   return chdir(path.value().c_str()) == 0;
 }
 
@@ -961,9 +923,6 @@
     "wheel"
   };
 
-  // Reading the groups database may touch the file system.
-  AssertBlockingAllowed();
-
   std::set<gid_t> allowed_group_ids;
   for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
     struct group *group_record = getgrnam(kAdminGroupNames[i]);
@@ -987,7 +946,6 @@
   // enough to guard against e.g. bugs causing multi-megabyte paths.
   return 1024;
 #else
-  AssertBlockingAllowed();
   return pathconf(path.value().c_str(), _PC_NAME_MAX);
 #endif
 }
@@ -996,17 +954,12 @@
 // This is implemented in file_util_android.cc for that platform.
 bool GetShmemTempDir(bool executable, FilePath* path) {
 #if defined(OS_LINUX) || defined(OS_AIX)
-  bool disable_dev_shm = false;
-#if !defined(OS_CHROMEOS)
-  disable_dev_shm = CommandLine::ForCurrentProcess()->HasSwitch(
-      switches::kDisableDevShmUsage);
-#endif
   bool use_dev_shm = true;
   if (executable) {
     static const bool s_dev_shm_executable = DetermineDevShmExecutable();
     use_dev_shm = s_dev_shm_executable;
   }
-  if (use_dev_shm && !disable_dev_shm) {
+  if (use_dev_shm) {
     *path = FilePath("/dev/shm");
     return true;
   }
@@ -1018,7 +971,6 @@
 #if !defined(OS_MACOSX)
 // Mac has its own implementation, this is for all other Posix systems.
 bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
-  AssertBlockingAllowed();
   File infile;
 #if defined(OS_ANDROID)
   if (from_path.IsContentUri()) {
@@ -1045,7 +997,6 @@
 namespace internal {
 
 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
-  AssertBlockingAllowed();
   // Windows compatibility: if |to_path| exists, |from_path| and |to_path|
   // must be the same type, either both files, or both directories.
   stat_wrapper_t to_file_info;
diff --git a/base/files/file_util_win.cc b/base/files/file_util_win.cc
index 23b3e26..c1a5ced 100644
--- a/base/files/file_util_win.cc
+++ b/base/files/file_util_win.cc
@@ -29,7 +29,6 @@
 #include "base/strings/string_util.h"
 #include "base/strings/stringprintf.h"
 #include "base/strings/utf_string_conversions.h"
-#include "base/threading/thread_restrictions.h"
 #include "base/time/time.h"
 #include "base/win/scoped_handle.h"
 #include "base/win/windows_version.h"
@@ -91,7 +90,6 @@
 bool DoCopyFile(const FilePath& from_path,
                 const FilePath& to_path,
                 bool fail_if_exists) {
-  AssertBlockingAllowed();
   if (from_path.ReferencesParent() || to_path.ReferencesParent())
     return false;
 
@@ -125,13 +123,6 @@
                      const FilePath& to_path,
                      bool recursive,
                      bool fail_if_exists) {
-  // NOTE(maruel): Previous version of this function used to call
-  // SHFileOperation().  This used to copy the file attributes and extended
-  // attributes, OLE structured storage, NTFS file system alternate data
-  // streams, SECURITY_DESCRIPTOR. In practice, this is not what we want, we
-  // want the containing directory to propagate its SECURITY_DESCRIPTOR.
-  AssertBlockingAllowed();
-
   // NOTE: I suspect we could support longer paths, but that would involve
   // analyzing all our usage of files.
   if (from_path.value().length() >= MAX_PATH ||
@@ -213,8 +204,6 @@
 
 // Returns ERROR_SUCCESS on success, or a Windows error code on failure.
 DWORD DoDeleteFile(const FilePath& path, bool recursive) {
-  AssertBlockingAllowed();
-
   if (path.empty())
     return ERROR_SUCCESS;
 
@@ -294,7 +283,6 @@
 }  // namespace
 
 FilePath MakeAbsoluteFilePath(const FilePath& input) {
-  AssertBlockingAllowed();
   wchar_t file_path[MAX_PATH];
   if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH))
     return FilePath();
@@ -306,8 +294,6 @@
   static constexpr char kNonRecursive[] = "DeleteFile.NonRecursive";
   const StringPiece operation(recursive ? kRecursive : kNonRecursive);
 
-  AssertBlockingAllowed();
-
   // Metrics for delete failures tracked in https://crbug.com/599084. Delete may
   // fail for a number of reasons. Log some metrics relating to failures in the
   // current code so that any improvements or regressions resulting from
@@ -317,8 +303,6 @@
 }
 
 bool DeleteFileAfterReboot(const FilePath& path) {
-  AssertBlockingAllowed();
-
   if (path.value().length() >= MAX_PATH)
     return false;
 
@@ -330,7 +314,6 @@
 bool ReplaceFile(const FilePath& from_path,
                  const FilePath& to_path,
                  File::Error* error) {
-  AssertBlockingAllowed();
   // Try a simple move first.  It will only succeed when |to_path| doesn't
   // already exist.
   if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
@@ -369,12 +352,10 @@
 }
 
 bool PathExists(const FilePath& path) {
-  AssertBlockingAllowed();
   return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
 }
 
 bool PathIsWritable(const FilePath& path) {
-  AssertBlockingAllowed();
   HANDLE dir =
       CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll,
                  NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
@@ -387,7 +368,6 @@
 }
 
 bool DirectoryExists(const FilePath& path) {
-  AssertBlockingAllowed();
   DWORD fileattr = GetFileAttributes(path.value().c_str());
   if (fileattr != INVALID_FILE_ATTRIBUTES)
     return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
@@ -424,8 +404,6 @@
 }
 
 bool CreateTemporaryFile(FilePath* path) {
-  AssertBlockingAllowed();
-
   FilePath temp_file;
 
   if (!GetTempDir(path))
@@ -444,7 +422,6 @@
 // TODO(jrg): is there equivalent call to use on Windows instead of
 // going 2-step?
 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
-  AssertBlockingAllowed();
   if (!CreateTemporaryFileInDir(dir, path)) {
     return NULL;
   }
@@ -455,8 +432,6 @@
 }
 
 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
-  AssertBlockingAllowed();
-
   // Use GUID instead of ::GetTempFileName() to generate unique file names.
   // "Due to the algorithm used to generate file names, GetTempFileName can
   // perform poorly when creating a large number of files with the same prefix.
@@ -504,8 +479,6 @@
 bool CreateTemporaryDirInDir(const FilePath& base_dir,
                              const FilePath::StringType& prefix,
                              FilePath* new_dir) {
-  AssertBlockingAllowed();
-
   FilePath path_to_create;
 
   for (int count = 0; count < 50; ++count) {
@@ -530,8 +503,6 @@
 
 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
                             FilePath* new_temp_path) {
-  AssertBlockingAllowed();
-
   FilePath system_temp_dir;
   if (!GetTempDir(&system_temp_dir))
     return false;
@@ -541,8 +512,6 @@
 
 bool CreateDirectoryAndGetError(const FilePath& full_path,
                                 File::Error* error) {
-  AssertBlockingAllowed();
-
   // If the path exists, we've succeeded if it's a directory, failed otherwise.
   const wchar_t* full_path_str = full_path.value().c_str();
   DWORD fileattr = ::GetFileAttributes(full_path_str);
@@ -599,7 +568,6 @@
 }
 
 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
-  AssertBlockingAllowed();
   FilePath mapped_file;
   if (!NormalizeToNativeFilePath(path, &mapped_file))
     return false;
@@ -612,8 +580,6 @@
 
 bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
                                  FilePath* out_drive_letter_path) {
-  AssertBlockingAllowed();
-
   // Get the mapping of drive letters to device paths.
   const int kDriveMappingSize = 1024;
   wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
@@ -655,7 +621,6 @@
 }
 
 bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
-  AssertBlockingAllowed();
   // In Vista, GetFinalPathNameByHandle() would give us the real path
   // from a file handle.  If we ever deprecate XP, consider changing the
   // code below to a call to GetFinalPathNameByHandle().  The method this
@@ -716,8 +681,6 @@
 }
 
 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
-  AssertBlockingAllowed();
-
   WIN32_FILE_ATTRIBUTE_DATA attr;
   if (!GetFileAttributesEx(file_path.value().c_str(),
                            GetFileExInfoStandard, &attr)) {
@@ -744,7 +707,6 @@
   DCHECK(
       strchr(mode, 'N') == nullptr ||
       (strchr(mode, ',') != nullptr && strchr(mode, 'N') > strchr(mode, ',')));
-  AssertBlockingAllowed();
   string16 w_mode = ASCIIToUTF16(mode);
   AppendModeCharacter(L'N', &w_mode);
   return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
@@ -765,7 +727,6 @@
 }
 
 int ReadFile(const FilePath& filename, char* data, int max_size) {
-  AssertBlockingAllowed();
   win::ScopedHandle file(CreateFile(filename.value().c_str(),
                                     GENERIC_READ,
                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
@@ -784,7 +745,6 @@
 }
 
 int WriteFile(const FilePath& filename, const char* data, int size) {
-  AssertBlockingAllowed();
   win::ScopedHandle file(CreateFile(filename.value().c_str(), GENERIC_WRITE, 0,
                                     NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
                                     NULL));
@@ -812,7 +772,6 @@
 }
 
 bool AppendToFile(const FilePath& filename, const char* data, int size) {
-  AssertBlockingAllowed();
   win::ScopedHandle file(CreateFile(filename.value().c_str(),
                                     FILE_APPEND_DATA,
                                     0,
@@ -833,8 +792,6 @@
 }
 
 bool GetCurrentDirectory(FilePath* dir) {
-  AssertBlockingAllowed();
-
   wchar_t system_buffer[MAX_PATH];
   system_buffer[0] = 0;
   DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
@@ -849,13 +806,10 @@
 }
 
 bool SetCurrentDirectory(const FilePath& directory) {
-  AssertBlockingAllowed();
   return ::SetCurrentDirectory(directory.value().c_str()) != 0;
 }
 
 int GetMaximumPathComponentLength(const FilePath& path) {
-  AssertBlockingAllowed();
-
   wchar_t volume_path[MAX_PATH];
   if (!GetVolumePathNameW(path.NormalizePathSeparators().value().c_str(),
                           volume_path,
@@ -893,8 +847,6 @@
 namespace internal {
 
 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
-  AssertBlockingAllowed();
-
   // NOTE: I suspect we could support longer paths, but that would involve
   // analyzing all our usage of files.
   if (from_path.value().length() >= MAX_PATH ||
@@ -928,7 +880,6 @@
 
 bool CopyAndDeleteDirectory(const FilePath& from_path,
                             const FilePath& to_path) {
-  AssertBlockingAllowed();
   if (CopyDirectory(from_path, to_path, true)) {
     if (DeleteFile(from_path, true))
       return true;
diff --git a/base/files/file_win.cc b/base/files/file_win.cc
index 46b4b75..e922ad8 100644
--- a/base/files/file_win.cc
+++ b/base/files/file_win.cc
@@ -8,7 +8,6 @@
 #include <stdint.h>
 
 #include "base/logging.h"
-#include "base/threading/thread_restrictions.h"
 
 #include <windows.h>
 
@@ -36,17 +35,12 @@
   if (!file_.IsValid())
     return;
 
-  AssertBlockingAllowed();
-  SCOPED_FILE_TRACE("Close");
   file_.Close();
 }
 
 int64_t File::Seek(Whence whence, int64_t offset) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
 
-  SCOPED_FILE_TRACE_WITH_SIZE("Seek", offset);
-
   LARGE_INTEGER distance, res;
   distance.QuadPart = offset;
   DWORD move_method = static_cast<DWORD>(whence);
@@ -56,14 +50,11 @@
 }
 
 int File::Read(int64_t offset, char* data, int size) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
   DCHECK(!async_);
   if (size < 0)
     return -1;
 
-  SCOPED_FILE_TRACE_WITH_SIZE("Read", size);
-
   LARGE_INTEGER offset_li;
   offset_li.QuadPart = offset;
 
@@ -81,14 +72,11 @@
 }
 
 int File::ReadAtCurrentPos(char* data, int size) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
   DCHECK(!async_);
   if (size < 0)
     return -1;
 
-  SCOPED_FILE_TRACE_WITH_SIZE("ReadAtCurrentPos", size);
-
   DWORD bytes_read;
   if (::ReadFile(file_.Get(), data, size, &bytes_read, NULL))
     return bytes_read;
@@ -109,12 +97,9 @@
 }
 
 int File::Write(int64_t offset, const char* data, int size) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
   DCHECK(!async_);
 
-  SCOPED_FILE_TRACE_WITH_SIZE("Write", size);
-
   LARGE_INTEGER offset_li;
   offset_li.QuadPart = offset;
 
@@ -130,14 +115,11 @@
 }
 
 int File::WriteAtCurrentPos(const char* data, int size) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
   DCHECK(!async_);
   if (size < 0)
     return -1;
 
-  SCOPED_FILE_TRACE_WITH_SIZE("WriteAtCurrentPos", size);
-
   DWORD bytes_written;
   if (::WriteFile(file_.Get(), data, size, &bytes_written, NULL))
     return bytes_written;
@@ -150,11 +132,8 @@
 }
 
 int64_t File::GetLength() {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
 
-  SCOPED_FILE_TRACE("GetLength");
-
   LARGE_INTEGER size;
   if (!::GetFileSizeEx(file_.Get(), &size))
     return -1;
@@ -163,11 +142,8 @@
 }
 
 bool File::SetLength(int64_t length) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
 
-  SCOPED_FILE_TRACE_WITH_SIZE("SetLength", length);
-
   // Get the current file pointer.
   LARGE_INTEGER file_pointer;
   LARGE_INTEGER zero;
@@ -194,11 +170,8 @@
 }
 
 bool File::SetTimes(Time last_access_time, Time last_modified_time) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
 
-  SCOPED_FILE_TRACE("SetTimes");
-
   FILETIME last_access_filetime = last_access_time.ToFileTime();
   FILETIME last_modified_filetime = last_modified_time.ToFileTime();
   return (::SetFileTime(file_.Get(), NULL, &last_access_filetime,
@@ -206,11 +179,8 @@
 }
 
 bool File::GetInfo(Info* info) {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
 
-  SCOPED_FILE_TRACE("GetInfo");
-
   BY_HANDLE_FILE_INFORMATION file_info;
   if (!GetFileInformationByHandle(file_.Get(), &file_info))
     return false;
@@ -231,8 +201,6 @@
 File::Error File::Lock() {
   DCHECK(IsValid());
 
-  SCOPED_FILE_TRACE("Lock");
-
   BOOL result = LockFile(file_.Get(), 0, 0, MAXDWORD, MAXDWORD);
   if (!result)
     return GetLastFileError();
@@ -242,8 +210,6 @@
 File::Error File::Unlock() {
   DCHECK(IsValid());
 
-  SCOPED_FILE_TRACE("Unlock");
-
   BOOL result = UnlockFile(file_.Get(), 0, 0, MAXDWORD, MAXDWORD);
   if (!result)
     return GetLastFileError();
@@ -254,8 +220,6 @@
   if (!IsValid())
     return File();
 
-  SCOPED_FILE_TRACE("Duplicate");
-
   HANDLE other_handle = nullptr;
 
   if (!::DuplicateHandle(GetCurrentProcess(),  // hSourceProcessHandle
@@ -319,7 +283,6 @@
 }
 
 void File::DoInitialize(const FilePath& path, uint32_t flags) {
-  AssertBlockingAllowed();
   DCHECK(!IsValid());
 
   DWORD disposition = 0;
@@ -409,9 +372,7 @@
 }
 
 bool File::Flush() {
-  AssertBlockingAllowed();
   DCHECK(IsValid());
-  SCOPED_FILE_TRACE("Flush");
   return ::FlushFileBuffers(file_.Get()) != FALSE;
 }
 
diff --git a/base/files/memory_mapped_file.cc b/base/files/memory_mapped_file.cc
deleted file mode 100644
index 8a07e49..0000000
--- a/base/files/memory_mapped_file.cc
+++ /dev/null
@@ -1,130 +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 "base/files/memory_mapped_file.h"
-
-#include <utility>
-
-#include "base/files/file_path.h"
-#include "base/logging.h"
-#include "base/numerics/safe_math.h"
-#include "base/sys_info.h"
-#include "build_config.h"
-
-namespace base {
-
-const MemoryMappedFile::Region MemoryMappedFile::Region::kWholeFile = {0, 0};
-
-bool MemoryMappedFile::Region::operator==(
-    const MemoryMappedFile::Region& other) const {
-  return other.offset == offset && other.size == size;
-}
-
-bool MemoryMappedFile::Region::operator!=(
-    const MemoryMappedFile::Region& other) const {
-  return other.offset != offset || other.size != size;
-}
-
-MemoryMappedFile::~MemoryMappedFile() {
-  CloseHandles();
-}
-
-#if !defined(OS_NACL)
-bool MemoryMappedFile::Initialize(const FilePath& file_name, Access access) {
-  if (IsValid())
-    return false;
-
-  uint32_t flags = 0;
-  switch (access) {
-    case READ_ONLY:
-      flags = File::FLAG_OPEN | File::FLAG_READ;
-      break;
-    case READ_WRITE:
-      flags = File::FLAG_OPEN | File::FLAG_READ | File::FLAG_WRITE;
-      break;
-    case READ_WRITE_EXTEND:
-      // Can't open with "extend" because no maximum size is known.
-      NOTREACHED();
-  }
-  file_.Initialize(file_name, flags);
-
-  if (!file_.IsValid()) {
-    DLOG(ERROR) << "Couldn't open " << file_name.AsUTF8Unsafe();
-    return false;
-  }
-
-  if (!MapFileRegionToMemory(Region::kWholeFile, access)) {
-    CloseHandles();
-    return false;
-  }
-
-  return true;
-}
-
-bool MemoryMappedFile::Initialize(File file, Access access) {
-  DCHECK_NE(READ_WRITE_EXTEND, access);
-  return Initialize(std::move(file), Region::kWholeFile, access);
-}
-
-bool MemoryMappedFile::Initialize(File file,
-                                  const Region& region,
-                                  Access access) {
-  switch (access) {
-    case READ_WRITE_EXTEND:
-      DCHECK(Region::kWholeFile != region);
-      {
-        CheckedNumeric<int64_t> region_end(region.offset);
-        region_end += region.size;
-        if (!region_end.IsValid()) {
-          DLOG(ERROR) << "Region bounds exceed maximum for base::File.";
-          return false;
-        }
-      }
-      FALLTHROUGH;
-    case READ_ONLY:
-    case READ_WRITE:
-      // Ensure that the region values are valid.
-      if (region.offset < 0) {
-        DLOG(ERROR) << "Region bounds are not valid.";
-        return false;
-      }
-      break;
-  }
-
-  if (IsValid())
-    return false;
-
-  if (region != Region::kWholeFile)
-    DCHECK_GE(region.offset, 0);
-
-  file_ = std::move(file);
-
-  if (!MapFileRegionToMemory(region, access)) {
-    CloseHandles();
-    return false;
-  }
-
-  return true;
-}
-
-bool MemoryMappedFile::IsValid() const {
-  return data_ != nullptr;
-}
-
-// static
-void MemoryMappedFile::CalculateVMAlignedBoundaries(int64_t start,
-                                                    size_t size,
-                                                    int64_t* aligned_start,
-                                                    size_t* aligned_size,
-                                                    int32_t* offset) {
-  // Sadly, on Windows, the mmap alignment is not just equal to the page size.
-  auto mask = SysInfo::VMAllocationGranularity() - 1;
-  DCHECK(IsValueInRangeForNumericType<int32_t>(mask));
-  *offset = start & mask;
-  *aligned_start = start & ~mask;
-  *aligned_size = (size + *offset + mask) & ~mask;
-}
-#endif  // !defined(OS_NACL)
-
-}  // namespace base
diff --git a/base/files/memory_mapped_file.h b/base/files/memory_mapped_file.h
deleted file mode 100644
index 012f091..0000000
--- a/base/files/memory_mapped_file.h
+++ /dev/null
@@ -1,136 +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_FILES_MEMORY_MAPPED_FILE_H_
-#define BASE_FILES_MEMORY_MAPPED_FILE_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "base/base_export.h"
-#include "base/files/file.h"
-#include "base/macros.h"
-#include "build_config.h"
-
-#if defined(OS_WIN)
-#include <windows.h>
-#endif
-
-namespace base {
-
-class FilePath;
-
-class BASE_EXPORT MemoryMappedFile {
- public:
-  enum Access {
-    // Mapping a file into memory effectively allows for file I/O on any thread.
-    // The accessing thread could be paused while data from the file is paged
-    // into memory. Worse, a corrupted filesystem could cause a SEGV within the
-    // program instead of just an I/O error.
-    READ_ONLY,
-
-    // This provides read/write access to a file and must be used with care of
-    // the additional subtleties involved in doing so. Though the OS will do
-    // the writing of data on its own time, too many dirty pages can cause
-    // the OS to pause the thread while it writes them out. The pause can
-    // be as much as 1s on some systems.
-    READ_WRITE,
-
-    // This provides read/write access but with the ability to write beyond
-    // the end of the existing file up to a maximum size specified as the
-    // "region". Depending on the OS, the file may or may not be immediately
-    // extended to the maximum size though it won't be loaded in RAM until
-    // needed. Note, however, that the maximum size will still be reserved
-    // in the process address space.
-    READ_WRITE_EXTEND,
-  };
-
-  // The default constructor sets all members to invalid/null values.
-  MemoryMappedFile();
-  ~MemoryMappedFile();
-
-  // Used to hold information about a region [offset + size] of a file.
-  struct BASE_EXPORT Region {
-    static const Region kWholeFile;
-
-    bool operator==(const Region& other) const;
-    bool operator!=(const Region& other) const;
-
-    // Start of the region (measured in bytes from the beginning of the file).
-    int64_t offset;
-
-    // Length of the region in bytes.
-    size_t size;
-  };
-
-  // Opens an existing file and maps it into memory. |access| can be read-only
-  // or read/write but not read/write+extend. If this object already points
-  // to a valid memory mapped file then this method will fail and return
-  // false. If it cannot open the file, the file does not exist, or the
-  // memory mapping fails, it will return false.
-  bool Initialize(const FilePath& file_name, Access access);
-  bool Initialize(const FilePath& file_name) {
-    return Initialize(file_name, READ_ONLY);
-  }
-
-  // As above, but works with an already-opened file. |access| can be read-only
-  // or read/write but not read/write+extend. MemoryMappedFile takes ownership
-  // of |file| and closes it when done. |file| must have been opened with
-  // permissions suitable for |access|. If the memory mapping fails, it will
-  // return false.
-  bool Initialize(File file, Access access);
-  bool Initialize(File file) {
-    return Initialize(std::move(file), READ_ONLY);
-  }
-
-  // As above, but works with a region of an already-opened file. All forms of
-  // |access| are allowed. If READ_WRITE_EXTEND is specified then |region|
-  // provides the maximum size of the file. If the memory mapping fails, it
-  // return false.
-  bool Initialize(File file, const Region& region, Access access);
-  bool Initialize(File file, const Region& region) {
-    return Initialize(std::move(file), region, READ_ONLY);
-  }
-
-  const uint8_t* data() const { return data_; }
-  uint8_t* data() { return data_; }
-  size_t length() const { return length_; }
-
-  // Is file_ a valid file handle that points to an open, memory mapped file?
-  bool IsValid() const;
-
- private:
-  // Given the arbitrarily aligned memory region [start, size], returns the
-  // boundaries of the region aligned to the granularity specified by the OS,
-  // (a page on Linux, ~32k on Windows) as follows:
-  // - |aligned_start| is page aligned and <= |start|.
-  // - |aligned_size| is a multiple of the VM granularity and >= |size|.
-  // - |offset| is the displacement of |start| w.r.t |aligned_start|.
-  static void CalculateVMAlignedBoundaries(int64_t start,
-                                           size_t size,
-                                           int64_t* aligned_start,
-                                           size_t* aligned_size,
-                                           int32_t* offset);
-
-  // Map the file to memory, set data_ to that memory address. Return true on
-  // success, false on any kind of failure. This is a helper for Initialize().
-  bool MapFileRegionToMemory(const Region& region, Access access);
-
-  // Closes all open handles.
-  void CloseHandles();
-
-  File file_;
-  uint8_t* data_;
-  size_t length_;
-
-#if defined(OS_WIN)
-  win::ScopedHandle file_mapping_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(MemoryMappedFile);
-};
-
-}  // namespace base
-
-#endif  // BASE_FILES_MEMORY_MAPPED_FILE_H_
diff --git a/base/files/memory_mapped_file_posix.cc b/base/files/memory_mapped_file_posix.cc
deleted file mode 100644
index e51c7e3..0000000
--- a/base/files/memory_mapped_file_posix.cc
+++ /dev/null
@@ -1,185 +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 "base/files/memory_mapped_file.h"
-
-#include <fcntl.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <sys/mman.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include "base/logging.h"
-#include "base/numerics/safe_conversions.h"
-#include "base/threading/thread_restrictions.h"
-#include "build_config.h"
-
-#if defined(OS_ANDROID)
-#include <android/api-level.h>
-#endif
-
-namespace base {
-
-MemoryMappedFile::MemoryMappedFile() : data_(nullptr), length_(0) {}
-
-#if !defined(OS_NACL)
-bool MemoryMappedFile::MapFileRegionToMemory(
-    const MemoryMappedFile::Region& region,
-    Access access) {
-  AssertBlockingAllowed();
-
-  off_t map_start = 0;
-  size_t map_size = 0;
-  int32_t data_offset = 0;
-
-  if (region == MemoryMappedFile::Region::kWholeFile) {
-    int64_t file_len = file_.GetLength();
-    if (file_len < 0) {
-      DPLOG(ERROR) << "fstat " << file_.GetPlatformFile();
-      return false;
-    }
-    if (!IsValueInRangeForNumericType<size_t>(file_len))
-      return false;
-    map_size = static_cast<size_t>(file_len);
-    length_ = map_size;
-  } else {
-    // The region can be arbitrarily aligned. mmap, instead, requires both the
-    // start and size to be page-aligned. Hence, we map here the page-aligned
-    // outer region [|aligned_start|, |aligned_start| + |size|] which contains
-    // |region| and then add up the |data_offset| displacement.
-    int64_t aligned_start = 0;
-    size_t aligned_size = 0;
-    CalculateVMAlignedBoundaries(region.offset,
-                                 region.size,
-                                 &aligned_start,
-                                 &aligned_size,
-                                 &data_offset);
-
-    // Ensure that the casts in the mmap call below are sane.
-    if (aligned_start < 0 ||
-        !IsValueInRangeForNumericType<off_t>(aligned_start)) {
-      DLOG(ERROR) << "Region bounds are not valid for mmap";
-      return false;
-    }
-
-    map_start = static_cast<off_t>(aligned_start);
-    map_size = aligned_size;
-    length_ = region.size;
-  }
-
-  int flags = 0;
-  switch (access) {
-    case READ_ONLY:
-      flags |= PROT_READ;
-      break;
-
-    case READ_WRITE:
-      flags |= PROT_READ | PROT_WRITE;
-      break;
-
-    case READ_WRITE_EXTEND:
-      flags |= PROT_READ | PROT_WRITE;
-
-      const int64_t new_file_len = region.offset + region.size;
-
-      // POSIX won't auto-extend the file when it is written so it must first
-      // be explicitly extended to the maximum size. Zeros will fill the new
-      // space. It is assumed that the existing file is fully realized as
-      // otherwise the entire file would have to be read and possibly written.
-      const int64_t original_file_len = file_.GetLength();
-      if (original_file_len < 0) {
-        DPLOG(ERROR) << "fstat " << file_.GetPlatformFile();
-        return false;
-      }
-
-      // Increase the actual length of the file, if necessary. This can fail if
-      // the disk is full and the OS doesn't support sparse files.
-      if (!file_.SetLength(std::max(original_file_len, new_file_len))) {
-        DPLOG(ERROR) << "ftruncate " << file_.GetPlatformFile();
-        return false;
-      }
-
-      // Realize the extent of the file so that it can't fail (and crash) later
-      // when trying to write to a memory page that can't be created. This can
-      // fail if the disk is full and the file is sparse.
-      bool do_manual_extension = false;
-
-#if defined(OS_ANDROID) && __ANDROID_API__ < 21
-      // Only Android API>=21 supports the fallocate call. Older versions need
-      // to manually extend the file by writing zeros at block intervals.
-      do_manual_extension = true;
-#elif defined(OS_MACOSX)
-      // MacOS doesn't support fallocate even though their new APFS filesystem
-      // does support sparse files. It does, however, have the functionality
-      // available via fcntl.
-      // See also: https://openradar.appspot.com/32720223
-      fstore_t params = {F_ALLOCATEALL, F_PEOFPOSMODE, region.offset,
-                         region.size, 0};
-      if (fcntl(file_.GetPlatformFile(), F_PREALLOCATE, &params) != 0) {
-        DPLOG(ERROR) << "F_PREALLOCATE";
-        // This can fail because the filesystem doesn't support it so don't
-        // give up just yet. Try the manual method below.
-        do_manual_extension = true;
-      }
-#else
-      if (posix_fallocate(file_.GetPlatformFile(), region.offset,
-                          region.size) != 0) {
-        DPLOG(ERROR) << "posix_fallocate";
-        // This can fail because the filesystem doesn't support it so don't
-        // give up just yet. Try the manual method below.
-        do_manual_extension = true;
-      }
-#endif
-
-      // Manually realize the extended file by writing bytes to it at intervals.
-      if (do_manual_extension) {
-        int64_t block_size = 512;  // Start with something safe.
-        struct stat statbuf;
-        if (fstat(file_.GetPlatformFile(), &statbuf) == 0 &&
-            statbuf.st_blksize > 0) {
-          block_size = statbuf.st_blksize;
-        }
-
-        // Write starting at the next block boundary after the old file length.
-        const int64_t extension_start =
-            (original_file_len + block_size - 1) & ~(block_size - 1);
-        for (int64_t i = extension_start; i < new_file_len; i += block_size) {
-          char existing_byte;
-          if (pread(file_.GetPlatformFile(), &existing_byte, 1, i) != 1)
-            return false;  // Can't read? Not viable.
-          if (existing_byte != 0)
-            continue;  // Block has data so must already exist.
-          if (pwrite(file_.GetPlatformFile(), &existing_byte, 1, i) != 1)
-            return false;  // Can't write? Not viable.
-        }
-      }
-
-      break;
-  }
-
-  data_ = static_cast<uint8_t*>(mmap(nullptr, map_size, flags, MAP_SHARED,
-                                     file_.GetPlatformFile(), map_start));
-  if (data_ == MAP_FAILED) {
-    DPLOG(ERROR) << "mmap " << file_.GetPlatformFile();
-    return false;
-  }
-
-  data_ += data_offset;
-  return true;
-}
-#endif
-
-void MemoryMappedFile::CloseHandles() {
-  AssertBlockingAllowed();
-
-  if (data_ != nullptr)
-    munmap(data_, length_);
-  file_.Close();
-
-  data_ = nullptr;
-  length_ = 0;
-}
-
-}  // namespace base
diff --git a/base/files/memory_mapped_file_win.cc b/base/files/memory_mapped_file_win.cc
deleted file mode 100644
index 26869f6..0000000
--- a/base/files/memory_mapped_file_win.cc
+++ /dev/null
@@ -1,109 +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 "base/files/memory_mapped_file.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <limits>
-
-#include "base/files/file_path.h"
-#include "base/strings/string16.h"
-#include "base/threading/thread_restrictions.h"
-
-#include <windows.h>
-
-namespace base {
-
-MemoryMappedFile::MemoryMappedFile() : data_(NULL), length_(0) {
-}
-
-bool MemoryMappedFile::MapFileRegionToMemory(
-    const MemoryMappedFile::Region& region,
-    Access access) {
-  AssertBlockingAllowed();
-
-  if (!file_.IsValid())
-    return false;
-
-  int flags = 0;
-  ULARGE_INTEGER size = {};
-  switch (access) {
-    case READ_ONLY:
-      flags |= PAGE_READONLY;
-      break;
-    case READ_WRITE:
-      flags |= PAGE_READWRITE;
-      break;
-    case READ_WRITE_EXTEND:
-      flags |= PAGE_READWRITE;
-      size.QuadPart = region.size;
-      break;
-  }
-
-  file_mapping_.Set(::CreateFileMapping(file_.GetPlatformFile(), NULL, flags,
-                                        size.HighPart, size.LowPart, NULL));
-  if (!file_mapping_.IsValid())
-    return false;
-
-  LARGE_INTEGER map_start = {};
-  SIZE_T map_size = 0;
-  int32_t data_offset = 0;
-
-  if (region == MemoryMappedFile::Region::kWholeFile) {
-    DCHECK_NE(READ_WRITE_EXTEND, access);
-    int64_t file_len = file_.GetLength();
-    if (file_len <= 0 || !IsValueInRangeForNumericType<size_t>(file_len))
-      return false;
-    length_ = static_cast<size_t>(file_len);
-  } else {
-    // The region can be arbitrarily aligned. MapViewOfFile, instead, requires
-    // that the start address is aligned to the VM granularity (which is
-    // typically larger than a page size, for instance 32k).
-    // Also, conversely to POSIX's mmap, the |map_size| doesn't have to be
-    // aligned and must be less than or equal the mapped file size.
-    // We map here the outer region [|aligned_start|, |aligned_start+size|]
-    // which contains |region| and then add up the |data_offset| displacement.
-    int64_t aligned_start = 0;
-    size_t ignored = 0U;
-    CalculateVMAlignedBoundaries(
-        region.offset, region.size, &aligned_start, &ignored, &data_offset);
-    int64_t full_map_size = region.size + data_offset;
-
-    // Ensure that the casts below in the MapViewOfFile call are sane.
-    if (aligned_start < 0 || full_map_size < 0 ||
-        !IsValueInRangeForNumericType<SIZE_T>(
-            static_cast<uint64_t>(full_map_size))) {
-      DLOG(ERROR) << "Region bounds are not valid for MapViewOfFile";
-      return false;
-    }
-    map_start.QuadPart = aligned_start;
-    map_size = static_cast<SIZE_T>(full_map_size);
-    length_ = region.size;
-  }
-
-  data_ = static_cast<uint8_t*>(
-      ::MapViewOfFile(file_mapping_.Get(),
-                      (flags & PAGE_READONLY) ? FILE_MAP_READ : FILE_MAP_WRITE,
-                      map_start.HighPart, map_start.LowPart, map_size));
-  if (data_ == NULL)
-    return false;
-  data_ += data_offset;
-  return true;
-}
-
-void MemoryMappedFile::CloseHandles() {
-  if (data_)
-    ::UnmapViewOfFile(data_);
-  if (file_mapping_.IsValid())
-    file_mapping_.Close();
-  if (file_.IsValid())
-    file_.Close();
-
-  data_ = NULL;
-  length_ = 0;
-}
-
-}  // namespace base
diff --git a/base/json/json_parser.cc b/base/json/json_parser.cc
index dfe246c..e6483ee 100644
--- a/base/json/json_parser.cc
+++ b/base/json/json_parser.cc
@@ -680,12 +680,6 @@
   if (StringToInt(num_string, &num_int))
     return Value(num_int);
 
-  double num_double;
-  if (StringToDouble(num_string.as_string(), &num_double) &&
-      std::isfinite(num_double)) {
-    return Value(num_double);
-  }
-
   return nullopt;
 }
 
diff --git a/base/json/json_writer.cc b/base/json/json_writer.cc
index 86af250..76035db 100644
--- a/base/json/json_writer.cc
+++ b/base/json/json_writer.cc
@@ -78,38 +78,6 @@
       return result;
     }
 
-    case Value::Type::DOUBLE: {
-      double value;
-      bool result = node.GetAsDouble(&value);
-      DCHECK(result);
-      if (omit_double_type_preservation_ &&
-          value <= std::numeric_limits<int64_t>::max() &&
-          value >= std::numeric_limits<int64_t>::min() &&
-          std::floor(value) == value) {
-        json_string_->append(Int64ToString(static_cast<int64_t>(value)));
-        return result;
-      }
-      std::string real = NumberToString(value);
-      // Ensure that the number has a .0 if there's no decimal or 'e'.  This
-      // makes sure that when we read the JSON back, it's interpreted as a
-      // real rather than an int.
-      if (real.find('.') == std::string::npos &&
-          real.find('e') == std::string::npos &&
-          real.find('E') == std::string::npos) {
-        real.append(".0");
-      }
-      // The JSON spec requires that non-integer values in the range (-1,1)
-      // have a zero before the decimal point - ".52" is not valid, "0.52" is.
-      if (real[0] == '.') {
-        real.insert(static_cast<size_t>(0), static_cast<size_t>(1), '0');
-      } else if (real.length() > 1 && real[0] == '-' && real[1] == '.') {
-        // "-.1" bad "-0.1" good
-        real.insert(static_cast<size_t>(1), static_cast<size_t>(1), '0');
-      }
-      json_string_->append(real);
-      return result;
-    }
-
     case Value::Type::STRING: {
       std::string value;
       bool result = node.GetAsString(&value);
diff --git a/base/lazy_instance.h b/base/lazy_instance.h
deleted file mode 100644
index 456b431..0000000
--- a/base/lazy_instance.h
+++ /dev/null
@@ -1,208 +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.
-//
-// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! DEPRECATED !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-// Please don't introduce new instances of LazyInstance<T>. Use a function-local
-// static of type base::NoDestructor<T> instead:
-//
-// Factory& Factory::GetInstance() {
-//   static base::NoDestructor<Factory> instance;
-//   return *instance;
-// }
-// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-//
-// The LazyInstance<Type, Traits> class manages a single instance of Type,
-// which will be lazily created on the first time it's accessed.  This class is
-// useful for places you would normally use a function-level static, but you
-// need to have guaranteed thread-safety.  The Type constructor will only ever
-// be called once, even if two threads are racing to create the object.  Get()
-// and Pointer() will always return the same, completely initialized instance.
-// When the instance is constructed it is registered with AtExitManager.  The
-// destructor will be called on program exit.
-//
-// LazyInstance is completely thread safe, assuming that you create it safely.
-// The class was designed to be POD initialized, so it shouldn't require a
-// static constructor.  It really only makes sense to declare a LazyInstance as
-// a global variable using the LAZY_INSTANCE_INITIALIZER initializer.
-//
-// LazyInstance is similar to Singleton, except it does not have the singleton
-// property.  You can have multiple LazyInstance's of the same type, and each
-// will manage a unique instance.  It also preallocates the space for Type, as
-// to avoid allocating the Type instance on the heap.  This may help with the
-// performance of creating the instance, and reducing heap fragmentation.  This
-// requires that Type be a complete type so we can determine the size.
-//
-// Example usage:
-//   static LazyInstance<MyClass>::Leaky inst = LAZY_INSTANCE_INITIALIZER;
-//   void SomeMethod() {
-//     inst.Get().SomeMethod();  // MyClass::SomeMethod()
-//
-//     MyClass* ptr = inst.Pointer();
-//     ptr->DoDoDo();  // MyClass::DoDoDo
-//   }
-
-#ifndef BASE_LAZY_INSTANCE_H_
-#define BASE_LAZY_INSTANCE_H_
-
-#include <new>  // For placement new.
-
-#include "base/atomicops.h"
-#include "base/lazy_instance_helpers.h"
-#include "base/logging.h"
-#include "base/threading/thread_restrictions.h"
-
-// LazyInstance uses its own struct initializer-list style static
-// initialization, which does not require a constructor.
-#define LAZY_INSTANCE_INITIALIZER {0}
-
-namespace base {
-
-template <typename Type>
-struct LazyInstanceTraitsBase {
-  static Type* New(void* instance) {
-    DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (alignof(Type) - 1), 0u);
-    // Use placement new to initialize our instance in our preallocated space.
-    // The parenthesis is very important here to force POD type initialization.
-    return new (instance) Type();
-  }
-
-  static void CallDestructor(Type* instance) {
-    // Explicitly call the destructor.
-    instance->~Type();
-  }
-};
-
-// We pull out some of the functionality into non-templated functions, so we
-// can implement the more complicated pieces out of line in the .cc file.
-namespace internal {
-
-// This traits class causes destruction the contained Type at process exit via
-// AtExitManager. This is probably generally not what you want. Instead, prefer
-// Leaky below.
-template <typename Type>
-struct DestructorAtExitLazyInstanceTraits {
-  static const bool kRegisterOnExit = true;
-#if DCHECK_IS_ON()
-  static const bool kAllowedToAccessOnNonjoinableThread = false;
-#endif
-
-  static Type* New(void* instance) {
-    return LazyInstanceTraitsBase<Type>::New(instance);
-  }
-
-  static void Delete(Type* instance) {
-    LazyInstanceTraitsBase<Type>::CallDestructor(instance);
-  }
-};
-
-// Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.:
-// base::LazyInstance<T>::Leaky my_leaky_lazy_instance;
-// instead of:
-// base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> >
-// my_leaky_lazy_instance;
-// (especially when T is MyLongTypeNameImplClientHolderFactory).
-// Only use this internal::-qualified verbose form to extend this traits class
-// (depending on its implementation details).
-template <typename Type>
-struct LeakyLazyInstanceTraits {
-  static const bool kRegisterOnExit = false;
-#if DCHECK_IS_ON()
-  static const bool kAllowedToAccessOnNonjoinableThread = true;
-#endif
-
-  static Type* New(void* instance) {
-    return LazyInstanceTraitsBase<Type>::New(instance);
-  }
-  static void Delete(Type* instance) {
-  }
-};
-
-template <typename Type>
-struct ErrorMustSelectLazyOrDestructorAtExitForLazyInstance {};
-
-}  // namespace internal
-
-template <
-    typename Type,
-    typename Traits =
-        internal::ErrorMustSelectLazyOrDestructorAtExitForLazyInstance<Type>>
-class LazyInstance {
- public:
-  // Do not define a destructor, as doing so makes LazyInstance a
-  // non-POD-struct. We don't want that because then a static initializer will
-  // be created to register the (empty) destructor with atexit() under MSVC, for
-  // example. We handle destruction of the contained Type class explicitly via
-  // the OnExit member function, where needed.
-  // ~LazyInstance() {}
-
-  // Convenience typedef to avoid having to repeat Type for leaky lazy
-  // instances.
-  typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type>> Leaky;
-  typedef LazyInstance<Type, internal::DestructorAtExitLazyInstanceTraits<Type>>
-      DestructorAtExit;
-
-  Type& Get() {
-    return *Pointer();
-  }
-
-  Type* Pointer() {
-#if DCHECK_IS_ON()
-    if (!Traits::kAllowedToAccessOnNonjoinableThread)
-      ThreadRestrictions::AssertSingletonAllowed();
-#endif
-
-    return subtle::GetOrCreateLazyPointer(
-        &private_instance_, &Traits::New, private_buf_,
-        Traits::kRegisterOnExit ? OnExit : nullptr, this);
-  }
-
-  // Returns true if the lazy instance has been created.  Unlike Get() and
-  // Pointer(), calling IsCreated() will not instantiate the object of Type.
-  bool IsCreated() {
-    // Return true (i.e. "created") if |private_instance_| is either being
-    // created right now (i.e. |private_instance_| has value of
-    // internal::kLazyInstanceStateCreating) or was already created (i.e.
-    // |private_instance_| has any other non-zero value).
-    return 0 != subtle::NoBarrier_Load(&private_instance_);
-  }
-
-  // MSVC gives a warning that the alignment expands the size of the
-  // LazyInstance struct to make the size a multiple of the alignment. This
-  // is expected in this case.
-#if defined(OS_WIN)
-#pragma warning(push)
-#pragma warning(disable: 4324)
-#endif
-
-  // Effectively private: member data is only public to allow the linker to
-  // statically initialize it and to maintain a POD class. DO NOT USE FROM
-  // OUTSIDE THIS CLASS.
-  subtle::AtomicWord private_instance_;
-
-  // Preallocated space for the Type instance.
-  alignas(Type) char private_buf_[sizeof(Type)];
-
-#if defined(OS_WIN)
-#pragma warning(pop)
-#endif
-
- private:
-  Type* instance() {
-    return reinterpret_cast<Type*>(subtle::NoBarrier_Load(&private_instance_));
-  }
-
-  // Adapter function for use with AtExit.  This should be called single
-  // threaded, so don't synchronize across threads.
-  // Calling OnExit while the instance is in use by other threads is a mistake.
-  static void OnExit(void* lazy_instance) {
-    LazyInstance<Type, Traits>* me =
-        reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance);
-    Traits::Delete(me->instance());
-    subtle::NoBarrier_Store(&me->private_instance_, 0);
-  }
-};
-
-}  // namespace base
-
-#endif  // BASE_LAZY_INSTANCE_H_
diff --git a/base/lazy_instance_helpers.cc b/base/lazy_instance_helpers.cc
deleted file mode 100644
index 7b9e0de..0000000
--- a/base/lazy_instance_helpers.cc
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright 2018 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/lazy_instance_helpers.h"
-
-#include "base/at_exit.h"
-#include "base/atomicops.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-namespace internal {
-
-bool NeedsLazyInstance(subtle::AtomicWord* state) {
-  // Try to create the instance, if we're the first, will go from 0 to
-  // kLazyInstanceStateCreating, otherwise we've already been beaten here.
-  // The memory access has no memory ordering as state 0 and
-  // kLazyInstanceStateCreating have no associated data (memory barriers are
-  // all about ordering of memory accesses to *associated* data).
-  if (subtle::NoBarrier_CompareAndSwap(state, 0, kLazyInstanceStateCreating) ==
-      0) {
-    // Caller must create instance
-    return true;
-  }
-
-  // It's either in the process of being created, or already created. Spin.
-  // The load has acquire memory ordering as a thread which sees
-  // state_ == STATE_CREATED needs to acquire visibility over
-  // the associated data (buf_). Pairing Release_Store is in
-  // CompleteLazyInstance().
-  if (subtle::Acquire_Load(state) == kLazyInstanceStateCreating) {
-    const base::TimeTicks start = base::TimeTicks::Now();
-    do {
-      const base::TimeDelta elapsed = base::TimeTicks::Now() - start;
-      // Spin with YieldCurrentThread for at most one ms - this ensures maximum
-      // responsiveness. After that spin with Sleep(1ms) so that we don't burn
-      // excessive CPU time - this also avoids infinite loops due to priority
-      // inversions (https://crbug.com/797129).
-      if (elapsed < TimeDelta::FromMilliseconds(1))
-        PlatformThread::YieldCurrentThread();
-      else
-        PlatformThread::Sleep(TimeDelta::FromMilliseconds(1));
-    } while (subtle::Acquire_Load(state) == kLazyInstanceStateCreating);
-  }
-  // Someone else created the instance.
-  return false;
-}
-
-void CompleteLazyInstance(subtle::AtomicWord* state,
-                          subtle::AtomicWord new_instance,
-                          void (*destructor)(void*),
-                          void* destructor_arg) {
-  // Instance is created, go from CREATING to CREATED (or reset it if
-  // |new_instance| is null). Releases visibility over |private_buf_| to
-  // readers. Pairing Acquire_Load is in NeedsLazyInstance().
-  subtle::Release_Store(state, new_instance);
-
-  // Make sure that the lazily instantiated object will get destroyed at exit.
-  if (new_instance && destructor)
-    AtExitManager::RegisterCallback(destructor, destructor_arg);
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/lazy_instance_helpers.h b/base/lazy_instance_helpers.h
deleted file mode 100644
index 5a43d8b..0000000
--- a/base/lazy_instance_helpers.h
+++ /dev/null
@@ -1,101 +0,0 @@
-// Copyright 2018 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_LAZY_INSTANCE_INTERNAL_H_
-#define BASE_LAZY_INSTANCE_INTERNAL_H_
-
-#include "base/atomicops.h"
-#include "base/base_export.h"
-#include "base/logging.h"
-
-// Helper methods used by LazyInstance and a few other base APIs for thread-safe
-// lazy construction.
-
-namespace base {
-namespace internal {
-
-// Our AtomicWord doubles as a spinlock, where a value of
-// kLazyInstanceStateCreating means the spinlock is being held for creation.
-constexpr subtle::AtomicWord kLazyInstanceStateCreating = 1;
-
-// Helper for GetOrCreateLazyPointer(). Checks if instance needs to be created.
-// If so returns true otherwise if another thread has beat us, waits for
-// instance to be created and returns false.
-BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state);
-
-// Helper for GetOrCreateLazyPointer(). After creating an instance, this is
-// called to register the dtor to be called at program exit and to update the
-// atomic state to hold the |new_instance|
-BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state,
-                                      subtle::AtomicWord new_instance,
-                                      void (*destructor)(void*),
-                                      void* destructor_arg);
-
-}  // namespace internal
-
-namespace subtle {
-
-// If |state| is uninitialized (zero), constructs a value using
-// |creator_func(creator_arg)|, stores it into |state| and registers
-// |destructor(destructor_arg)| to be called when the current AtExitManager goes
-// out of scope. Then, returns the value stored in |state|. It is safe to have
-// concurrent calls to this function with the same |state|. |creator_func| may
-// return nullptr if it doesn't want to create an instance anymore (e.g. on
-// shutdown), it is from then on required to return nullptr to all callers (ref.
-// StaticMemorySingletonTraits). In that case, callers need to synchronize
-// before |creator_func| may return a non-null instance again (ref.
-// StaticMemorySingletonTraits::ResurectForTesting()).
-// Implementation note on |creator_func/creator_arg|. It makes for ugly adapters
-// but it avoids redundant template instantiations (e.g. saves 27KB in
-// chrome.dll) because linker is able to fold these for multiple Types but
-// couldn't with the more advanced CreatorFunc template type which in turn
-// improves code locality (and application startup) -- ref.
-// https://chromium-review.googlesource.com/c/chromium/src/+/530984/5/base/lazy_instance.h#140,
-// worsened by https://chromium-review.googlesource.com/c/chromium/src/+/868013
-// and caught then as https://crbug.com/804034.
-template <typename Type>
-Type* GetOrCreateLazyPointer(subtle::AtomicWord* state,
-                             Type* (*creator_func)(void*),
-                             void* creator_arg,
-                             void (*destructor)(void*),
-                             void* destructor_arg) {
-  DCHECK(state);
-  DCHECK(creator_func);
-
-  // If any bit in the created mask is true, the instance has already been
-  // fully constructed.
-  constexpr subtle::AtomicWord kLazyInstanceCreatedMask =
-      ~internal::kLazyInstanceStateCreating;
-
-  // We will hopefully have fast access when the instance is already created.
-  // Since a thread sees |state| == 0 or kLazyInstanceStateCreating at most
-  // once, the load is taken out of NeedsLazyInstance() as a fast-path. The load
-  // has acquire memory ordering as a thread which sees |state| > creating needs
-  // to acquire visibility over the associated data. Pairing Release_Store is in
-  // CompleteLazyInstance().
-  subtle::AtomicWord instance = subtle::Acquire_Load(state);
-  if (!(instance & kLazyInstanceCreatedMask)) {
-    if (internal::NeedsLazyInstance(state)) {
-      // This thread won the race and is now responsible for creating the
-      // instance and storing it back into |state|.
-      instance =
-          reinterpret_cast<subtle::AtomicWord>((*creator_func)(creator_arg));
-      internal::CompleteLazyInstance(state, instance, destructor,
-                                     destructor_arg);
-    } else {
-      // This thread lost the race but now has visibility over the constructed
-      // instance (NeedsLazyInstance() doesn't return until the constructing
-      // thread releases the instance via CompleteLazyInstance()).
-      instance = subtle::Acquire_Load(state);
-      DCHECK(instance & kLazyInstanceCreatedMask);
-    }
-  }
-  return reinterpret_cast<Type*>(instance);
-}
-
-}  // namespace subtle
-
-}  // namespace base
-
-#endif  // BASE_LAZY_INSTANCE_INTERNAL_H_
diff --git a/base/location.cc b/base/location.cc
deleted file mode 100644
index 59d6728..0000000
--- a/base/location.cc
+++ /dev/null
@@ -1,77 +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 "base/location.h"
-
-#if defined(COMPILER_MSVC)
-#include <intrin.h>
-#endif
-
-#include "base/compiler_specific.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/stringprintf.h"
-#include "build_config.h"
-
-namespace base {
-
-Location::Location() = default;
-Location::Location(const Location& other) = default;
-
-Location::Location(const char* file_name, const void* program_counter)
-    : file_name_(file_name), program_counter_(program_counter) {}
-
-Location::Location(const char* function_name,
-                   const char* file_name,
-                   int line_number,
-                   const void* program_counter)
-    : function_name_(function_name),
-      file_name_(file_name),
-      line_number_(line_number),
-      program_counter_(program_counter) {
-#if !defined(OS_NACL)
-  // The program counter should not be null except in a default constructed
-  // (empty) Location object. This value is used for identity, so if it doesn't
-  // uniquely identify a location, things will break.
-  //
-  // The program counter isn't supported in NaCl so location objects won't work
-  // properly in that context.
-  DCHECK(program_counter);
-#endif
-}
-
-std::string Location::ToString() const {
-  if (has_source_info()) {
-    return std::string(function_name_) + "@" + file_name_ + ":" +
-           IntToString(line_number_);
-  }
-  return StringPrintf("pc:%p", program_counter_);
-}
-
-#if defined(COMPILER_MSVC)
-#define RETURN_ADDRESS() _ReturnAddress()
-#elif defined(COMPILER_GCC) && !defined(OS_NACL)
-#define RETURN_ADDRESS() \
-  __builtin_extract_return_addr(__builtin_return_address(0))
-#else
-#define RETURN_ADDRESS() nullptr
-#endif
-
-// static
-NOINLINE Location Location::CreateFromHere(const char* file_name) {
-  return Location(file_name, RETURN_ADDRESS());
-}
-
-// static
-NOINLINE Location Location::CreateFromHere(const char* function_name,
-                                           const char* file_name,
-                                           int line_number) {
-  return Location(function_name, file_name, line_number, RETURN_ADDRESS());
-}
-
-//------------------------------------------------------------------------------
-NOINLINE const void* GetProgramCounter() {
-  return RETURN_ADDRESS();
-}
-
-}  // namespace base
diff --git a/base/location.h b/base/location.h
deleted file mode 100644
index 3f6b804..0000000
--- a/base/location.h
+++ /dev/null
@@ -1,105 +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_LOCATION_H_
-#define BASE_LOCATION_H_
-
-#include <stddef.h>
-
-#include <cassert>
-#include <string>
-
-#include "base/base_export.h"
-#include "base/hash.h"
-
-namespace base {
-
-// Location provides basic info where of an object was constructed, or was
-// significantly brought to life.
-class BASE_EXPORT Location {
- public:
-  Location();
-  Location(const Location& other);
-
-  // Only initializes the file name and program counter, the source information
-  // will be null for the strings, and -1 for the line number.
-  // TODO(http://crbug.com/760702) remove file name from this constructor.
-  Location(const char* file_name, const void* program_counter);
-
-  // Constructor should be called with a long-lived char*, such as __FILE__.
-  // It assumes the provided value will persist as a global constant, and it
-  // will not make a copy of it.
-  Location(const char* function_name,
-           const char* file_name,
-           int line_number,
-           const void* program_counter);
-
-  // Comparator for hash map insertion. The program counter should uniquely
-  // identify a location.
-  bool operator==(const Location& other) const {
-    return program_counter_ == other.program_counter_;
-  }
-
-  // Returns true if there is source code location info. If this is false,
-  // the Location object only contains a program counter or is
-  // default-initialized (the program counter is also null).
-  bool has_source_info() const { return function_name_ && file_name_; }
-
-  // Will be nullptr for default initialized Location objects and when source
-  // names are disabled.
-  const char* function_name() const { return function_name_; }
-
-  // Will be nullptr for default initialized Location objects and when source
-  // names are disabled.
-  const char* file_name() const { return file_name_; }
-
-  // Will be -1 for default initialized Location objects and when source names
-  // are disabled.
-  int line_number() const { return line_number_; }
-
-  // The address of the code generating this Location object. Should always be
-  // valid except for default initialized Location objects, which will be
-  // nullptr.
-  const void* program_counter() const { return program_counter_; }
-
-  // Converts to the most user-readable form possible. If function and filename
-  // are not available, this will return "pc:<hex address>".
-  std::string ToString() const;
-
-  static Location CreateFromHere(const char* file_name);
-  static Location CreateFromHere(const char* function_name,
-                                 const char* file_name,
-                                 int line_number);
-
- private:
-  const char* function_name_ = nullptr;
-  const char* file_name_ = nullptr;
-  int line_number_ = -1;
-  const void* program_counter_ = nullptr;
-};
-
-BASE_EXPORT const void* GetProgramCounter();
-
-// The macros defined here will expand to the current function.
-// TODO(http://crbug.com/760702) remove the __FILE__ argument from these calls.
-#define FROM_HERE ::base::Location::CreateFromHere(__FILE__)
-#define FROM_HERE_WITH_EXPLICIT_FUNCTION(function_name) \
-  ::base::Location::CreateFromHere(function_name, __FILE__, -1)
-
-}  // namespace base
-
-namespace std {
-
-// Specialization for using Location in hash tables.
-template <>
-struct hash<::base::Location> {
-  std::size_t operator()(const ::base::Location& loc) const {
-    const void* program_counter = loc.program_counter();
-    return base::Hash(&program_counter, sizeof(void*));
-  }
-};
-
-}  // namespace std
-
-#endif  // BASE_LOCATION_H_
diff --git a/base/logging.cc b/base/logging.cc
index 281b469..83ad556 100644
--- a/base/logging.cc
+++ b/base/logging.cc
@@ -84,10 +84,8 @@
 #include <string>
 #include <utility>
 
-#include "base/base_switches.h"
 #include "base/callback.h"
 #include "base/containers/stack.h"
-#include "base/lazy_instance.h"
 #include "base/posix/eintr_wrapper.h"
 #include "base/strings/string_piece.h"
 #include "base/strings/string_util.h"
@@ -144,12 +142,6 @@
 // Should we pop up fatal debug messages in a dialog?
 bool show_error_dialogs = false;
 
-// An assert handler override specified by the client to be called instead of
-// the debug message dialog and process termination. Assert handlers are stored
-// in stack to allow overriding and restoring.
-base::LazyInstance<base::stack<LogAssertHandlerFunction>>::Leaky
-    log_assert_handler_stack = LAZY_INSTANCE_INITIALIZER;
-
 // A log message handler that gets notified of every log message we process.
 LogMessageHandlerFunction log_message_handler = nullptr;
 
@@ -453,15 +445,6 @@
   show_error_dialogs = enable_dialogs;
 }
 
-ScopedLogAssertHandler::ScopedLogAssertHandler(
-    LogAssertHandlerFunction handler) {
-  log_assert_handler_stack.Get().push(std::move(handler));
-}
-
-ScopedLogAssertHandler::~ScopedLogAssertHandler() {
-  log_assert_handler_stack.Get().pop();
-}
-
 void SetLogMessageHandler(LogMessageHandlerFunction handler) {
   log_message_handler = handler;
 }
@@ -544,7 +527,6 @@
 }
 
 LogMessage::~LogMessage() {
-  size_t stack_start = stream_.tellp();
 #if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
     !defined(OS_AIX)
   if (severity_ == LOG_FATAL) {
@@ -773,32 +755,18 @@
   }
 
   if (severity_ == LOG_FATAL) {
-    if (log_assert_handler_stack.IsCreated() &&
-        !log_assert_handler_stack.Get().empty()) {
-      LogAssertHandlerFunction log_assert_handler =
-          log_assert_handler_stack.Get().top();
-
-      if (log_assert_handler) {
-        log_assert_handler.Run(
-            file_, line_,
-            base::StringPiece(str_newline.c_str() + message_start_,
-                              stack_start - message_start_),
-            base::StringPiece(str_newline.c_str() + stack_start));
-      }
-    } else {
-      // Don't use the string with the newline, get a fresh version to send to
-      // the debug message process. We also don't display assertions to the
-      // user in release mode. The enduser can't do anything with this
-      // information, and displaying message boxes when the application is
-      // hosed can cause additional problems.
+// Don't use the string with the newline, get a fresh version to send to
+// the debug message process. We also don't display assertions to the
+// user in release mode. The enduser can't do anything with this
+// information, and displaying message boxes when the application is
+// hosed can cause additional problems.
 #ifndef NDEBUG
-      // Displaying a dialog is unnecessary when debugging and can complicate
-      // debugging.
-      DisplayDebugMessageInDialog(stream_.str());
+    // Displaying a dialog is unnecessary when debugging and can complicate
+    // debugging.
+    DisplayDebugMessageInDialog(stream_.str());
 #endif
-      // Crash the process to generate a dump.
-      abort();
-    }
+    // Crash the process to generate a dump.
+    abort();
   }
 }
 
diff --git a/base/logging.h b/base/logging.h
index 8bfe97d..13c30ab 100644
--- a/base/logging.h
+++ b/base/logging.h
@@ -219,26 +219,6 @@
 // Dialogs are not shown by default.
 BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
 
-// Sets the Log Assert Handler that will be used to notify of check failures.
-// Resets Log Assert Handler on object destruction.
-// The default handler shows a dialog box and then terminate the process,
-// however clients can use this function to override with their own handling
-// (e.g. a silent one for Unit Tests)
-using LogAssertHandlerFunction =
-    base::Callback<void(const char* file,
-                        int line,
-                        const base::StringPiece message,
-                        const base::StringPiece stack_trace)>;
-
-class BASE_EXPORT ScopedLogAssertHandler {
- public:
-  explicit ScopedLogAssertHandler(LogAssertHandlerFunction handler);
-  ~ScopedLogAssertHandler();
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(ScopedLogAssertHandler);
-};
-
 // Sets the Log Message Handler that gets passed every log message before
 // it's sent to other log destinations (if any).
 // Returns true to signal that it handled the message and the message
diff --git a/base/logging_win.cc b/base/logging_win.cc
deleted file mode 100644
index fbf73e6..0000000
--- a/base/logging_win.cc
+++ /dev/null
@@ -1,136 +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 "base/logging_win.h"
-#include "base/memory/singleton.h"
-#include <initguid.h>  // NOLINT
-
-namespace logging {
-
-using base::win::EtwEventLevel;
-using base::win::EtwMofEvent;
-
-DEFINE_GUID(kLogEventId,
-    0x7fe69228, 0x633e, 0x4f06, 0x80, 0xc1, 0x52, 0x7f, 0xea, 0x23, 0xe3, 0xa7);
-
-LogEventProvider::LogEventProvider() : old_log_level_(LOG_NONE) {
-}
-
-LogEventProvider* LogEventProvider::GetInstance() {
-  return base::Singleton<LogEventProvider, base::StaticMemorySingletonTraits<
-                                               LogEventProvider>>::get();
-}
-
-bool LogEventProvider::LogMessage(logging::LogSeverity severity,
-    const char* file, int line, size_t message_start,
-    const std::string& message) {
-  EtwEventLevel level = TRACE_LEVEL_NONE;
-
-  // Convert the log severity to the most appropriate ETW trace level.
-  if (severity >= 0) {
-    switch (severity) {
-      case LOG_INFO:
-        level = TRACE_LEVEL_INFORMATION;
-        break;
-      case LOG_WARNING:
-        level = TRACE_LEVEL_WARNING;
-        break;
-      case LOG_ERROR:
-        level = TRACE_LEVEL_ERROR;
-        break;
-      case LOG_FATAL:
-        level = TRACE_LEVEL_FATAL;
-        break;
-    }
-  }
-
-  // Bail if we're not logging, not at that level,
-  // or if we're post-atexit handling.
-  LogEventProvider* provider = LogEventProvider::GetInstance();
-  if (provider == NULL || level > provider->enable_level())
-    return false;
-
-  // And now log the event.
-  if (provider->enable_flags() & ENABLE_LOG_MESSAGE_ONLY) {
-    EtwMofEvent<1> event(kLogEventId, LOG_MESSAGE, level);
-    event.SetField(0, message.length() + 1 - message_start,
-        message.c_str() + message_start);
-
-    provider->Log(event.get());
-  } else {
-    const size_t kMaxBacktraceDepth = 32;
-    void* backtrace[kMaxBacktraceDepth];
-    DWORD depth = 0;
-
-    // Capture a stack trace if one is requested.
-    // requested per our enable flags.
-    if (provider->enable_flags() & ENABLE_STACK_TRACE_CAPTURE)
-      depth = CaptureStackBackTrace(2, kMaxBacktraceDepth, backtrace, NULL);
-
-    EtwMofEvent<5> event(kLogEventId, LOG_MESSAGE_FULL, level);
-    if (file == NULL)
-      file = "";
-
-    // Add the stack trace.
-    event.SetField(0, sizeof(depth), &depth);
-    event.SetField(1, sizeof(backtrace[0]) * depth, &backtrace);
-    // The line.
-    event.SetField(2, sizeof(line), &line);
-    // The file.
-    event.SetField(3, strlen(file) + 1, file);
-    // And finally the message.
-    event.SetField(4, message.length() + 1 - message_start,
-        message.c_str() + message_start);
-
-    provider->Log(event.get());
-  }
-
-  // Don't increase verbosity in other log destinations.
-  if (severity < provider->old_log_level_)
-    return true;
-
-  return false;
-}
-
-void LogEventProvider::Initialize(const GUID& provider_name) {
-  LogEventProvider* provider = LogEventProvider::GetInstance();
-
-  provider->set_provider_name(provider_name);
-  provider->Register();
-
-  // Register our message handler with logging.
-  SetLogMessageHandler(LogMessage);
-}
-
-void LogEventProvider::Uninitialize() {
-  LogEventProvider::GetInstance()->Unregister();
-}
-
-void LogEventProvider::OnEventsEnabled() {
-  // Grab the old log level so we can restore it later.
-  old_log_level_ = GetMinLogLevel();
-
-  // Convert the new trace level to a logging severity
-  // and enable logging at that level.
-  EtwEventLevel level = enable_level();
-  if (level == TRACE_LEVEL_NONE || level == TRACE_LEVEL_FATAL) {
-    SetMinLogLevel(LOG_FATAL);
-  } else if (level == TRACE_LEVEL_ERROR) {
-    SetMinLogLevel(LOG_ERROR);
-  } else if (level == TRACE_LEVEL_WARNING) {
-    SetMinLogLevel(LOG_WARNING);
-  } else if (level == TRACE_LEVEL_INFORMATION) {
-    SetMinLogLevel(LOG_INFO);
-  } else if (level >= TRACE_LEVEL_VERBOSE) {
-    // Above INFO, we enable verbose levels with negative severities.
-    SetMinLogLevel(TRACE_LEVEL_INFORMATION - level);
-  }
-}
-
-void LogEventProvider::OnEventsDisabled() {
-  // Restore the old log level.
-  SetMinLogLevel(old_log_level_);
-}
-
-}  // namespace logging
diff --git a/base/logging_win.h b/base/logging_win.h
deleted file mode 100644
index cdde7bb..0000000
--- a/base/logging_win.h
+++ /dev/null
@@ -1,84 +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_LOGGING_WIN_H_
-#define BASE_LOGGING_WIN_H_
-
-#include <stddef.h>
-
-#include <string>
-
-#include "base/base_export.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/win/event_trace_provider.h"
-
-namespace base {
-template <typename Type>
-struct StaticMemorySingletonTraits;
-}  // namespace base
-
-namespace logging {
-
-// Event ID for the log messages we generate.
-EXTERN_C BASE_EXPORT const GUID kLogEventId;
-
-// Feature enable mask for LogEventProvider.
-enum LogEnableMask {
-  // If this bit is set in our provider enable mask, we will include
-  // a stack trace with every log message.
-  ENABLE_STACK_TRACE_CAPTURE = 0x0001,
-  // If this bit is set in our provider enable mask, the provider will log
-  // a LOG message with only the textual content of the message, and no
-  // stack trace.
-  ENABLE_LOG_MESSAGE_ONLY = 0x0002,
-};
-
-// The message types our log event provider generates.
-// ETW likes user message types to start at 10.
-enum LogMessageTypes {
-  // A textual only log message, contains a zero-terminated string.
-  LOG_MESSAGE = 10,
-  // A message with a stack trace, followed by the zero-terminated
-  // message text.
-  LOG_MESSAGE_WITH_STACKTRACE = 11,
-  // A message with:
-  //  a stack trace,
-  //  the line number as a four byte integer,
-  //  the file as a zero terminated UTF8 string,
-  //  the zero-terminated UTF8 message text.
-  LOG_MESSAGE_FULL = 12,
-};
-
-// Trace provider class to drive log control and transport
-// with Event Tracing for Windows.
-class BASE_EXPORT LogEventProvider : public base::win::EtwTraceProvider {
- public:
-  static LogEventProvider* GetInstance();
-
-  static bool LogMessage(logging::LogSeverity severity, const char* file,
-      int line, size_t message_start, const std::string& str);
-
-  static void Initialize(const GUID& provider_name);
-  static void Uninitialize();
-
- protected:
-  // Overridden to manipulate the log level on ETW control callbacks.
-  void OnEventsEnabled() override;
-  void OnEventsDisabled() override;
-
- private:
-  LogEventProvider();
-
-  // The log severity prior to OnEventsEnabled,
-  // restored in OnEventsDisabled.
-  logging::LogSeverity old_log_level_;
-
-  friend struct base::StaticMemorySingletonTraits<LogEventProvider>;
-  DISALLOW_COPY_AND_ASSIGN(LogEventProvider);
-};
-
-}  // namespace logging
-
-#endif  // BASE_LOGGING_WIN_H_
diff --git a/base/memory/ref_counted.cc b/base/memory/ref_counted.cc
index b9fa15f..c2d40ef 100644
--- a/base/memory/ref_counted.cc
+++ b/base/memory/ref_counted.cc
@@ -7,13 +7,6 @@
 #include "base/threading/thread_collision_warner.h"
 
 namespace base {
-namespace {
-
-#if DCHECK_IS_ON()
-std::atomic_int g_cross_thread_ref_count_access_allow_count(0);
-#endif
-
-}  // namespace
 
 namespace subtle {
 
@@ -21,13 +14,6 @@
   return ref_count_.IsOne();
 }
 
-#if DCHECK_IS_ON()
-RefCountedThreadSafeBase::~RefCountedThreadSafeBase() {
-  DCHECK(in_dtor_) << "RefCountedThreadSafe object deleted without "
-                      "calling Release()";
-}
-#endif
-
 #if defined(ARCH_CPU_64_BIT)
 void RefCountedBase::AddRefImpl() const {
   // Check if |ref_count_| overflow only on 64 bit archs since the number of
@@ -46,23 +32,6 @@
 }
 #endif
 
-#if DCHECK_IS_ON()
-bool RefCountedBase::CalledOnValidSequence() const {
-  return sequence_checker_.CalledOnValidSequence() ||
-         g_cross_thread_ref_count_access_allow_count.load() != 0;
-}
-#endif
-
 }  // namespace subtle
 
-#if DCHECK_IS_ON()
-ScopedAllowCrossThreadRefCountAccess::ScopedAllowCrossThreadRefCountAccess() {
-  ++g_cross_thread_ref_count_access_allow_count;
-}
-
-ScopedAllowCrossThreadRefCountAccess::~ScopedAllowCrossThreadRefCountAccess() {
-  --g_cross_thread_ref_count_access_allow_count;
-}
-#endif
-
 }  // namespace base
diff --git a/base/memory/ref_counted.h b/base/memory/ref_counted.h
index 26a8437..6466c19 100644
--- a/base/memory/ref_counted.h
+++ b/base/memory/ref_counted.h
@@ -15,7 +15,6 @@
 #include "base/logging.h"
 #include "base/macros.h"
 #include "base/memory/scoped_refptr.h"
-#include "base/sequence_checker.h"
 #include "base/threading/thread_collision_warner.h"
 #include "build_config.h"
 
@@ -28,40 +27,15 @@
 
  protected:
   explicit RefCountedBase(StartRefCountFromZeroTag) {
-#if DCHECK_IS_ON()
-    sequence_checker_.DetachFromSequence();
-#endif
   }
 
   explicit RefCountedBase(StartRefCountFromOneTag) : ref_count_(1) {
-#if DCHECK_IS_ON()
-    needs_adopt_ref_ = true;
-    sequence_checker_.DetachFromSequence();
-#endif
   }
 
   ~RefCountedBase() {
-#if DCHECK_IS_ON()
-    DCHECK(in_dtor_) << "RefCounted object deleted without calling Release()";
-#endif
   }
 
   void AddRef() const {
-    // TODO(maruel): Add back once it doesn't assert 500 times/sec.
-    // Current thread books the critical section "AddRelease"
-    // without release it.
-    // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_);
-#if DCHECK_IS_ON()
-    DCHECK(!in_dtor_);
-    DCHECK(!needs_adopt_ref_)
-        << "This RefCounted object is created with non-zero reference count."
-        << " The first reference to such a object has to be made by AdoptRef or"
-        << " MakeRefCounted.";
-    if (ref_count_ >= 1) {
-      DCHECK(CalledOnValidSequence());
-    }
-#endif
-
     AddRefImpl();
   }
 
@@ -74,17 +48,6 @@
     // without release it.
     // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_);
 
-#if DCHECK_IS_ON()
-    DCHECK(!in_dtor_);
-    if (ref_count_ == 0)
-      in_dtor_ = true;
-
-    if (ref_count_ >= 1)
-      DCHECK(CalledOnValidSequence());
-    if (ref_count_ == 1)
-      sequence_checker_.DetachFromSequence();
-#endif
-
     return ref_count_ == 0;
   }
 
@@ -102,11 +65,7 @@
   // reference, or if the object is accessed from multiple threads
   // simultaneously.
   bool IsOnValidSequence() const {
-#if DCHECK_IS_ON()
-    return ref_count_ <= 1 || CalledOnValidSequence();
-#else
     return true;
-#endif
   }
 
  private:
@@ -114,10 +73,6 @@
   friend scoped_refptr<U> base::AdoptRef(U*);
 
   void Adopted() const {
-#if DCHECK_IS_ON()
-    DCHECK(needs_adopt_ref_);
-    needs_adopt_ref_ = false;
-#endif
   }
 
 #if defined(ARCH_CPU_64_BIT)
@@ -126,20 +81,8 @@
   void AddRefImpl() const { ++ref_count_; }
 #endif
 
-#if DCHECK_IS_ON()
-  bool CalledOnValidSequence() const;
-#endif
-
   mutable uint32_t ref_count_ = 0;
 
-#if DCHECK_IS_ON()
-  mutable bool needs_adopt_ref_ = false;
-  mutable bool in_dtor_ = false;
-  mutable SequenceChecker sequence_checker_;
-#endif
-
-  DFAKE_MUTEX(add_release_);
-
   DISALLOW_COPY_AND_ASSIGN(RefCountedBase);
 };
 
@@ -151,16 +94,9 @@
   explicit constexpr RefCountedThreadSafeBase(StartRefCountFromZeroTag) {}
   explicit constexpr RefCountedThreadSafeBase(StartRefCountFromOneTag)
       : ref_count_(1) {
-#if DCHECK_IS_ON()
-    needs_adopt_ref_ = true;
-#endif
   }
 
-#if DCHECK_IS_ON()
-  ~RefCountedThreadSafeBase();
-#else
   ~RefCountedThreadSafeBase() = default;
-#endif
 
 // Release and AddRef are suitable for inlining on X86 because they generate
 // very small code sequences. On other platforms (ARM), it causes a size
@@ -180,42 +116,20 @@
   friend scoped_refptr<U> base::AdoptRef(U*);
 
   void Adopted() const {
-#if DCHECK_IS_ON()
-    DCHECK(needs_adopt_ref_);
-    needs_adopt_ref_ = false;
-#endif
   }
 
   ALWAYS_INLINE void AddRefImpl() const {
-#if DCHECK_IS_ON()
-    DCHECK(!in_dtor_);
-    DCHECK(!needs_adopt_ref_)
-        << "This RefCounted object is created with non-zero reference count."
-        << " The first reference to such a object has to be made by AdoptRef or"
-        << " MakeRefCounted.";
-#endif
     ref_count_.Increment();
   }
 
   ALWAYS_INLINE bool ReleaseImpl() const {
-#if DCHECK_IS_ON()
-    DCHECK(!in_dtor_);
-    DCHECK(!ref_count_.IsZero());
-#endif
     if (!ref_count_.Decrement()) {
-#if DCHECK_IS_ON()
-      in_dtor_ = true;
-#endif
       return true;
     }
     return false;
   }
 
   mutable AtomicRefCount ref_count_{0};
-#if DCHECK_IS_ON()
-  mutable bool needs_adopt_ref_ = false;
-  mutable bool in_dtor_ = false;
-#endif
 
   DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafeBase);
 };
@@ -234,13 +148,8 @@
 // ScopedAllowCrossThreadRefCountAccess.
 class BASE_EXPORT ScopedAllowCrossThreadRefCountAccess final {
  public:
-#if DCHECK_IS_ON()
-  ScopedAllowCrossThreadRefCountAccess();
-  ~ScopedAllowCrossThreadRefCountAccess();
-#else
   ScopedAllowCrossThreadRefCountAccess() {}
   ~ScopedAllowCrossThreadRefCountAccess() {}
-#endif
 };
 
 //
diff --git a/base/memory/singleton.h b/base/memory/singleton.h
deleted file mode 100644
index 880ef0a..0000000
--- a/base/memory/singleton.h
+++ /dev/null
@@ -1,262 +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.
-//
-// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-// PLEASE READ: Do you really need a singleton? If possible, use a
-// function-local static of type base::NoDestructor<T> instead:
-//
-// Factory& Factory::GetInstance() {
-//   static base::NoDestructor<Factory> instance;
-//   return *instance;
-// }
-// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-//
-// Singletons make it hard to determine the lifetime of an object, which can
-// lead to buggy code and spurious crashes.
-//
-// Instead of adding another singleton into the mix, try to identify either:
-//   a) An existing singleton that can manage your object's lifetime
-//   b) Locations where you can deterministically create the object and pass
-//      into other objects
-//
-// If you absolutely need a singleton, please keep them as trivial as possible
-// and ideally a leaf dependency. Singletons get problematic when they attempt
-// to do too much in their destructor or have circular dependencies.
-
-#ifndef BASE_MEMORY_SINGLETON_H_
-#define BASE_MEMORY_SINGLETON_H_
-
-#include "base/at_exit.h"
-#include "base/atomicops.h"
-#include "base/base_export.h"
-#include "base/lazy_instance_helpers.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/threading/thread_restrictions.h"
-
-namespace base {
-
-// Default traits for Singleton<Type>. Calls operator new and operator delete on
-// the object. Registers automatic deletion at process exit.
-// Overload if you need arguments or another memory allocation function.
-template<typename Type>
-struct DefaultSingletonTraits {
-  // Allocates the object.
-  static Type* New() {
-    // The parenthesis is very important here; it forces POD type
-    // initialization.
-    return new Type();
-  }
-
-  // Destroys the object.
-  static void Delete(Type* x) {
-    delete x;
-  }
-
-  // Set to true to automatically register deletion of the object on process
-  // exit. See below for the required call that makes this happen.
-  static const bool kRegisterAtExit = true;
-
-#if DCHECK_IS_ON()
-  // Set to false to disallow access on a non-joinable thread.  This is
-  // different from kRegisterAtExit because StaticMemorySingletonTraits allows
-  // access on non-joinable threads, and gracefully handles this.
-  static const bool kAllowedToAccessOnNonjoinableThread = false;
-#endif
-};
-
-
-// Alternate traits for use with the Singleton<Type>.  Identical to
-// DefaultSingletonTraits except that the Singleton will not be cleaned up
-// at exit.
-template<typename Type>
-struct LeakySingletonTraits : public DefaultSingletonTraits<Type> {
-  static const bool kRegisterAtExit = false;
-#if DCHECK_IS_ON()
-  static const bool kAllowedToAccessOnNonjoinableThread = true;
-#endif
-};
-
-// Alternate traits for use with the Singleton<Type>.  Allocates memory
-// for the singleton instance from a static buffer.  The singleton will
-// be cleaned up at exit, but can't be revived after destruction unless
-// the ResurrectForTesting() method is called.
-//
-// This is useful for a certain category of things, notably logging and
-// tracing, where the singleton instance is of a type carefully constructed to
-// be safe to access post-destruction.
-// In logging and tracing you'll typically get stray calls at odd times, like
-// during static destruction, thread teardown and the like, and there's a
-// termination race on the heap-based singleton - e.g. if one thread calls
-// get(), but then another thread initiates AtExit processing, the first thread
-// may call into an object residing in unallocated memory. If the instance is
-// allocated from the data segment, then this is survivable.
-//
-// The destructor is to deallocate system resources, in this case to unregister
-// a callback the system will invoke when logging levels change. Note that
-// this is also used in e.g. Chrome Frame, where you have to allow for the
-// possibility of loading briefly into someone else's process space, and
-// so leaking is not an option, as that would sabotage the state of your host
-// process once you've unloaded.
-template <typename Type>
-struct StaticMemorySingletonTraits {
-  // WARNING: User has to support a New() which returns null.
-  static Type* New() {
-    // Only constructs once and returns pointer; otherwise returns null.
-    if (subtle::NoBarrier_AtomicExchange(&dead_, 1))
-      return nullptr;
-
-    return new (buffer_) Type();
-  }
-
-  static void Delete(Type* p) {
-    if (p)
-      p->Type::~Type();
-  }
-
-  static const bool kRegisterAtExit = true;
-
-#if DCHECK_IS_ON()
-  static const bool kAllowedToAccessOnNonjoinableThread = true;
-#endif
-
-  static void ResurrectForTesting() { subtle::NoBarrier_Store(&dead_, 0); }
-
- private:
-  alignas(Type) static char buffer_[sizeof(Type)];
-  // Signal the object was already deleted, so it is not revived.
-  static subtle::Atomic32 dead_;
-};
-
-template <typename Type>
-alignas(Type) char StaticMemorySingletonTraits<Type>::buffer_[sizeof(Type)];
-template <typename Type>
-subtle::Atomic32 StaticMemorySingletonTraits<Type>::dead_ = 0;
-
-// The Singleton<Type, Traits, DifferentiatingType> class manages a single
-// instance of Type which will be created on first use and will be destroyed at
-// normal process exit). The Trait::Delete function will not be called on
-// abnormal process exit.
-//
-// DifferentiatingType is used as a key to differentiate two different
-// singletons having the same memory allocation functions but serving a
-// different purpose. This is mainly used for Locks serving different purposes.
-//
-// Example usage:
-//
-// In your header:
-//   namespace base {
-//   template <typename T>
-//   struct DefaultSingletonTraits;
-//   }
-//   class FooClass {
-//    public:
-//     static FooClass* GetInstance();  <-- See comment below on this.
-//     void Bar() { ... }
-//    private:
-//     FooClass() { ... }
-//     friend struct base::DefaultSingletonTraits<FooClass>;
-//
-//     DISALLOW_COPY_AND_ASSIGN(FooClass);
-//   };
-//
-// In your source file:
-//  #include "base/memory/singleton.h"
-//  FooClass* FooClass::GetInstance() {
-//    return base::Singleton<FooClass>::get();
-//  }
-//
-// Or for leaky singletons:
-//  #include "base/memory/singleton.h"
-//  FooClass* FooClass::GetInstance() {
-//    return base::Singleton<
-//        FooClass, base::LeakySingletonTraits<FooClass>>::get();
-//  }
-//
-// And to call methods on FooClass:
-//   FooClass::GetInstance()->Bar();
-//
-// NOTE: The method accessing Singleton<T>::get() has to be named as GetInstance
-// and it is important that FooClass::GetInstance() is not inlined in the
-// header. This makes sure that when source files from multiple targets include
-// this header they don't end up with different copies of the inlined code
-// creating multiple copies of the singleton.
-//
-// Singleton<> has no non-static members and doesn't need to actually be
-// instantiated.
-//
-// This class is itself thread-safe. The underlying Type must of course be
-// thread-safe if you want to use it concurrently. Two parameters may be tuned
-// depending on the user's requirements.
-//
-// Glossary:
-//   RAE = kRegisterAtExit
-//
-// On every platform, if Traits::RAE is true, the singleton will be destroyed at
-// process exit. More precisely it uses AtExitManager which requires an
-// object of this type to be instantiated. AtExitManager mimics the semantics
-// of atexit() such as LIFO order but under Windows is safer to call. For more
-// information see at_exit.h.
-//
-// If Traits::RAE is false, the singleton will not be freed at process exit,
-// thus the singleton will be leaked if it is ever accessed. Traits::RAE
-// shouldn't be false unless absolutely necessary. Remember that the heap where
-// the object is allocated may be destroyed by the CRT anyway.
-//
-// Caveats:
-// (a) Every call to get(), operator->() and operator*() incurs some overhead
-//     (16ns on my P4/2.8GHz) to check whether the object has already been
-//     initialized.  You may wish to cache the result of get(); it will not
-//     change.
-//
-// (b) Your factory function must never throw an exception. This class is not
-//     exception-safe.
-//
-
-template <typename Type,
-          typename Traits = DefaultSingletonTraits<Type>,
-          typename DifferentiatingType = Type>
-class Singleton {
- private:
-  // Classes using the Singleton<T> pattern should declare a GetInstance()
-  // method and call Singleton::get() from within that.
-  friend Type* Type::GetInstance();
-
-  // This class is safe to be constructed and copy-constructed since it has no
-  // member.
-
-  // Return a pointer to the one true instance of the class.
-  static Type* get() {
-#if DCHECK_IS_ON()
-    if (!Traits::kAllowedToAccessOnNonjoinableThread)
-      ThreadRestrictions::AssertSingletonAllowed();
-#endif
-
-    return subtle::GetOrCreateLazyPointer(
-        &instance_, &CreatorFunc, nullptr,
-        Traits::kRegisterAtExit ? OnExit : nullptr, nullptr);
-  }
-
-  // Internal method used as an adaptor for GetOrCreateLazyPointer(). Do not use
-  // outside of that use case.
-  static Type* CreatorFunc(void* /* creator_arg*/) { return Traits::New(); }
-
-  // Adapter function for use with AtExit().  This should be called single
-  // threaded, so don't use atomic operations.
-  // Calling OnExit while singleton is in use by other threads is a mistake.
-  static void OnExit(void* /*unused*/) {
-    // AtExit should only ever be register after the singleton instance was
-    // created.  We should only ever get here with a valid instance_ pointer.
-    Traits::Delete(reinterpret_cast<Type*>(subtle::NoBarrier_Load(&instance_)));
-    instance_ = 0;
-  }
-  static subtle::AtomicWord instance_;
-};
-
-template <typename Type, typename Traits, typename DifferentiatingType>
-subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>::instance_ = 0;
-
-}  // namespace base
-
-#endif  // BASE_MEMORY_SINGLETON_H_
diff --git a/base/memory/weak_ptr.cc b/base/memory/weak_ptr.cc
index d2a7d89..1186829 100644
--- a/base/memory/weak_ptr.cc
+++ b/base/memory/weak_ptr.cc
@@ -8,23 +8,13 @@
 namespace internal {
 
 WeakReference::Flag::Flag() : is_valid_(true) {
-  // Flags only become bound when checked for validity, or invalidated,
-  // so that we can check that later validity/invalidation operations on
-  // the same Flag take place on the same sequenced thread.
-  sequence_checker_.DetachFromSequence();
 }
 
 void WeakReference::Flag::Invalidate() {
-  // The flag being invalidated with a single ref implies that there are no
-  // weak pointers in existence. Allow deletion on other thread in this case.
-  DCHECK(sequence_checker_.CalledOnValidSequence() || HasOneRef())
-      << "WeakPtrs must be invalidated on the same sequenced thread.";
   is_valid_ = false;
 }
 
 bool WeakReference::Flag::IsValid() const {
-  DCHECK(sequence_checker_.CalledOnValidSequence())
-      << "WeakPtrs must be checked on the same sequenced thread.";
   return is_valid_;
 }
 
diff --git a/base/memory/weak_ptr.h b/base/memory/weak_ptr.h
index 34e7d2e..fcacec1 100644
--- a/base/memory/weak_ptr.h
+++ b/base/memory/weak_ptr.h
@@ -77,7 +77,6 @@
 #include "base/logging.h"
 #include "base/macros.h"
 #include "base/memory/ref_counted.h"
-#include "base/sequence_checker.h"
 
 namespace base {
 
@@ -104,7 +103,6 @@
 
     ~Flag();
 
-    SequenceChecker sequence_checker_;
     bool is_valid_;
   };
 
diff --git a/base/message_loop/incoming_task_queue.cc b/base/message_loop/incoming_task_queue.cc
deleted file mode 100644
index 7a43e92..0000000
--- a/base/message_loop/incoming_task_queue.cc
+++ /dev/null
@@ -1,371 +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 "base/message_loop/incoming_task_queue.h"
-
-#include <limits>
-#include <utility>
-
-#include "base/location.h"
-#include "base/message_loop/message_loop.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/time/time.h"
-#include "build_config.h"
-
-namespace base {
-namespace internal {
-
-namespace {
-
-#if DCHECK_IS_ON()
-// Delays larger than this are often bogus, and a warning should be emitted in
-// debug builds to warn developers.  http://crbug.com/450045
-constexpr TimeDelta kTaskDelayWarningThreshold = TimeDelta::FromDays(14);
-#endif
-
-// Returns true if MessagePump::ScheduleWork() must be called one
-// time for every task that is added to the MessageLoop incoming queue.
-bool AlwaysNotifyPump(MessageLoop::Type type) {
-#if defined(OS_ANDROID)
-  // The Android UI message loop needs to get notified each time a task is
-  // added
-  // to the incoming queue.
-  return type == MessageLoop::TYPE_UI || type == MessageLoop::TYPE_JAVA;
-#else
-  return false;
-#endif
-}
-
-TimeTicks CalculateDelayedRuntime(TimeDelta delay) {
-  TimeTicks delayed_run_time;
-  if (delay > TimeDelta())
-    delayed_run_time = TimeTicks::Now() + delay;
-  else
-    DCHECK_EQ(delay.InMilliseconds(), 0) << "delay should not be negative";
-  return delayed_run_time;
-}
-
-}  // namespace
-
-IncomingTaskQueue::IncomingTaskQueue(MessageLoop* message_loop)
-    : always_schedule_work_(AlwaysNotifyPump(message_loop->type())),
-      triage_tasks_(this),
-      delayed_tasks_(this),
-      deferred_tasks_(this),
-      message_loop_(message_loop) {
-  // The constructing sequence is not necessarily the running sequence in the
-  // case of base::Thread.
-  DETACH_FROM_SEQUENCE(sequence_checker_);
-}
-
-bool IncomingTaskQueue::AddToIncomingQueue(const Location& from_here,
-                                           OnceClosure task,
-                                           TimeDelta delay,
-                                           Nestable nestable) {
-  // Use CHECK instead of DCHECK to crash earlier. See http://crbug.com/711167
-  // for details.
-  CHECK(task);
-  DLOG_IF(WARNING, delay > kTaskDelayWarningThreshold)
-      << "Requesting super-long task delay period of " << delay.InSeconds()
-      << " seconds from here: " << from_here.ToString();
-
-  PendingTask pending_task(from_here, std::move(task),
-                           CalculateDelayedRuntime(delay), nestable);
-#if defined(OS_WIN)
-  // We consider the task needs a high resolution timer if the delay is
-  // more than 0 and less than 32ms. This caps the relative error to
-  // less than 50% : a 33ms wait can wake at 48ms since the default
-  // resolution on Windows is between 10 and 15ms.
-  if (delay > TimeDelta() &&
-      delay.InMilliseconds() < (2 * Time::kMinLowResolutionThresholdMs)) {
-    pending_task.is_high_res = true;
-  }
-#endif
-  return PostPendingTask(&pending_task);
-}
-
-void IncomingTaskQueue::WillDestroyCurrentMessageLoop() {
-  {
-    AutoLock auto_lock(incoming_queue_lock_);
-    accept_new_tasks_ = false;
-  }
-  {
-    AutoLock auto_lock(message_loop_lock_);
-    message_loop_ = nullptr;
-  }
-}
-
-void IncomingTaskQueue::StartScheduling() {
-  bool schedule_work;
-  {
-    AutoLock lock(incoming_queue_lock_);
-    DCHECK(!is_ready_for_scheduling_);
-    DCHECK(!message_loop_scheduled_);
-    is_ready_for_scheduling_ = true;
-    schedule_work = !incoming_queue_.empty();
-    if (schedule_work)
-      message_loop_scheduled_ = true;
-  }
-  if (schedule_work) {
-    DCHECK(message_loop_);
-    AutoLock auto_lock(message_loop_lock_);
-    message_loop_->ScheduleWork();
-  }
-}
-
-IncomingTaskQueue::~IncomingTaskQueue() {
-  // Verify that WillDestroyCurrentMessageLoop() has been called.
-  DCHECK(!message_loop_);
-}
-
-void IncomingTaskQueue::RunTask(PendingTask* pending_task) {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-  std::move(pending_task->task).Run();
-}
-
-IncomingTaskQueue::TriageQueue::TriageQueue(IncomingTaskQueue* outer)
-    : outer_(outer) {}
-
-IncomingTaskQueue::TriageQueue::~TriageQueue() = default;
-
-const PendingTask& IncomingTaskQueue::TriageQueue::Peek() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-  ReloadFromIncomingQueueIfEmpty();
-  DCHECK(!queue_.empty());
-  return queue_.front();
-}
-
-PendingTask IncomingTaskQueue::TriageQueue::Pop() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-  ReloadFromIncomingQueueIfEmpty();
-  DCHECK(!queue_.empty());
-  PendingTask pending_task = std::move(queue_.front());
-  queue_.pop();
-
-  if (pending_task.is_high_res)
-    --outer_->pending_high_res_tasks_;
-
-  return pending_task;
-}
-
-bool IncomingTaskQueue::TriageQueue::HasTasks() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-  ReloadFromIncomingQueueIfEmpty();
-  return !queue_.empty();
-}
-
-void IncomingTaskQueue::TriageQueue::Clear() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-  // Previously, MessageLoop would delete all tasks including delayed and
-  // deferred tasks in a single round before attempting to reload from the
-  // incoming queue to see if more tasks remained. This gave it a chance to
-  // assess whether or not clearing should continue. As a result, while
-  // reloading is automatic for getting and seeing if tasks exist, it is not
-  // automatic for Clear().
-  while (!queue_.empty()) {
-    PendingTask pending_task = std::move(queue_.front());
-    queue_.pop();
-
-    if (pending_task.is_high_res)
-      --outer_->pending_high_res_tasks_;
-
-    if (!pending_task.delayed_run_time.is_null()) {
-      outer_->delayed_tasks().Push(std::move(pending_task));
-    }
-  }
-}
-
-void IncomingTaskQueue::TriageQueue::ReloadFromIncomingQueueIfEmpty() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-  if (queue_.empty()) {
-    // TODO(robliao): Since these high resolution tasks aren't yet in the
-    // delayed queue, they technically shouldn't trigger high resolution timers
-    // until they are.
-    outer_->pending_high_res_tasks_ += outer_->ReloadWorkQueue(&queue_);
-  }
-}
-
-IncomingTaskQueue::DelayedQueue::DelayedQueue(IncomingTaskQueue* outer)
-    : outer_(outer) {}
-
-IncomingTaskQueue::DelayedQueue::~DelayedQueue() = default;
-
-void IncomingTaskQueue::DelayedQueue::Push(PendingTask pending_task) {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-
-  if (pending_task.is_high_res)
-    ++outer_->pending_high_res_tasks_;
-
-  queue_.push(std::move(pending_task));
-}
-
-const PendingTask& IncomingTaskQueue::DelayedQueue::Peek() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-  DCHECK(!queue_.empty());
-  return queue_.top();
-}
-
-PendingTask IncomingTaskQueue::DelayedQueue::Pop() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-  DCHECK(!queue_.empty());
-  PendingTask delayed_task = std::move(const_cast<PendingTask&>(queue_.top()));
-  queue_.pop();
-
-  if (delayed_task.is_high_res)
-    --outer_->pending_high_res_tasks_;
-
-  return delayed_task;
-}
-
-bool IncomingTaskQueue::DelayedQueue::HasTasks() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-  // TODO(robliao): The other queues don't check for IsCancelled(). Should they?
-  while (!queue_.empty() && Peek().task.IsCancelled())
-    Pop();
-
-  return !queue_.empty();
-}
-
-void IncomingTaskQueue::DelayedQueue::Clear() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-  while (!queue_.empty())
-    Pop();
-}
-
-IncomingTaskQueue::DeferredQueue::DeferredQueue(IncomingTaskQueue* outer)
-    : outer_(outer) {}
-
-IncomingTaskQueue::DeferredQueue::~DeferredQueue() = default;
-
-void IncomingTaskQueue::DeferredQueue::Push(PendingTask pending_task) {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-
-  // TODO(robliao): These tasks should not count towards the high res task count
-  // since they are no longer in the delayed queue.
-  if (pending_task.is_high_res)
-    ++outer_->pending_high_res_tasks_;
-
-  queue_.push(std::move(pending_task));
-}
-
-const PendingTask& IncomingTaskQueue::DeferredQueue::Peek() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-  DCHECK(!queue_.empty());
-  return queue_.front();
-}
-
-PendingTask IncomingTaskQueue::DeferredQueue::Pop() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-  DCHECK(!queue_.empty());
-  PendingTask deferred_task = std::move(queue_.front());
-  queue_.pop();
-
-  if (deferred_task.is_high_res)
-    --outer_->pending_high_res_tasks_;
-
-  return deferred_task;
-}
-
-bool IncomingTaskQueue::DeferredQueue::HasTasks() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-  return !queue_.empty();
-}
-
-void IncomingTaskQueue::DeferredQueue::Clear() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(outer_->sequence_checker_);
-  while (!queue_.empty())
-    Pop();
-}
-
-bool IncomingTaskQueue::PostPendingTask(PendingTask* pending_task) {
-  // Warning: Don't try to short-circuit, and handle this thread's tasks more
-  // directly, as it could starve handling of foreign threads.  Put every task
-  // into this queue.
-  bool accept_new_tasks;
-  bool schedule_work = false;
-  {
-    AutoLock auto_lock(incoming_queue_lock_);
-    accept_new_tasks = accept_new_tasks_;
-    if (accept_new_tasks)
-      schedule_work = PostPendingTaskLockRequired(pending_task);
-  }
-
-  if (!accept_new_tasks) {
-    // Clear the pending task outside of |incoming_queue_lock_| to prevent any
-    // chance of self-deadlock if destroying a task also posts a task to this
-    // queue.
-    DCHECK(!schedule_work);
-    pending_task->task.Reset();
-    return false;
-  }
-
-  // Wake up the message loop and schedule work. This is done outside
-  // |incoming_queue_lock_| to allow for multiple post tasks to occur while
-  // ScheduleWork() is running. For platforms (e.g. Android) that require one
-  // call to ScheduleWork() for each task, all pending tasks may serialize
-  // within the ScheduleWork() call. As a result, holding a lock to maintain the
-  // lifetime of |message_loop_| is less of a concern.
-  if (schedule_work) {
-    // Ensures |message_loop_| isn't destroyed while running.
-    AutoLock auto_lock(message_loop_lock_);
-    if (message_loop_)
-      message_loop_->ScheduleWork();
-  }
-
-  return true;
-}
-
-bool IncomingTaskQueue::PostPendingTaskLockRequired(PendingTask* pending_task) {
-  incoming_queue_lock_.AssertAcquired();
-
-#if defined(OS_WIN)
-  if (pending_task->is_high_res)
-    ++high_res_task_count_;
-#endif
-
-  // Initialize the sequence number. The sequence number is used for delayed
-  // tasks (to facilitate FIFO sorting when two tasks have the same
-  // delayed_run_time value) and for identifying the task in about:tracing.
-  pending_task->sequence_num = next_sequence_num_++;
-
-  bool was_empty = incoming_queue_.empty();
-  incoming_queue_.push(std::move(*pending_task));
-
-  if (is_ready_for_scheduling_ &&
-      (always_schedule_work_ || (!message_loop_scheduled_ && was_empty))) {
-    // After we've scheduled the message loop, we do not need to do so again
-    // until we know it has processed all of the work in our queue and is
-    // waiting for more work again. The message loop will always attempt to
-    // reload from the incoming queue before waiting again so we clear this
-    // flag in ReloadWorkQueue().
-    message_loop_scheduled_ = true;
-    return true;
-  }
-  return false;
-}
-
-int IncomingTaskQueue::ReloadWorkQueue(TaskQueue* work_queue) {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
-  // Make sure no tasks are lost.
-  DCHECK(work_queue->empty());
-
-  // Acquire all we can from the inter-thread queue with one lock acquisition.
-  AutoLock lock(incoming_queue_lock_);
-  if (incoming_queue_.empty()) {
-    // If the loop attempts to reload but there are no tasks in the incoming
-    // queue, that means it will go to sleep waiting for more work. If the
-    // incoming queue becomes nonempty we need to schedule it again.
-    message_loop_scheduled_ = false;
-  } else {
-    incoming_queue_.swap(*work_queue);
-  }
-  // Reset the count of high resolution tasks since our queue is now empty.
-  int high_res_tasks = high_res_task_count_;
-  high_res_task_count_ = 0;
-  return high_res_tasks;
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/message_loop/incoming_task_queue.h b/base/message_loop/incoming_task_queue.h
deleted file mode 100644
index b4d8185..0000000
--- a/base/message_loop/incoming_task_queue.h
+++ /dev/null
@@ -1,262 +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_MESSAGE_LOOP_INCOMING_TASK_QUEUE_H_
-#define BASE_MESSAGE_LOOP_INCOMING_TASK_QUEUE_H_
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/pending_task.h"
-#include "base/sequence_checker.h"
-#include "base/synchronization/lock.h"
-#include "base/time/time.h"
-
-namespace base {
-
-class MessageLoop;
-class PostTaskTest;
-
-namespace internal {
-
-// Implements a queue of tasks posted to the message loop running on the current
-// thread. This class takes care of synchronizing posting tasks from different
-// threads and together with MessageLoop ensures clean shutdown.
-class BASE_EXPORT IncomingTaskQueue
-    : public RefCountedThreadSafe<IncomingTaskQueue> {
- public:
-  // Provides a read and remove only view into a task queue.
-  class ReadAndRemoveOnlyQueue {
-   public:
-    ReadAndRemoveOnlyQueue() = default;
-    virtual ~ReadAndRemoveOnlyQueue() = default;
-
-    // Returns the next task. HasTasks() is assumed to be true.
-    virtual const PendingTask& Peek() = 0;
-
-    // Removes and returns the next task. HasTasks() is assumed to be true.
-    virtual PendingTask Pop() = 0;
-
-    // Whether this queue has tasks.
-    virtual bool HasTasks() = 0;
-
-    // Removes all tasks.
-    virtual void Clear() = 0;
-
-   private:
-    DISALLOW_COPY_AND_ASSIGN(ReadAndRemoveOnlyQueue);
-  };
-
-  // Provides a read-write task queue.
-  class Queue : public ReadAndRemoveOnlyQueue {
-   public:
-    Queue() = default;
-    ~Queue() override = default;
-
-    // Adds the task to the end of the queue.
-    virtual void Push(PendingTask pending_task) = 0;
-
-   private:
-    DISALLOW_COPY_AND_ASSIGN(Queue);
-  };
-
-  explicit IncomingTaskQueue(MessageLoop* message_loop);
-
-  // Appends a task to the incoming queue. Posting of all tasks is routed though
-  // AddToIncomingQueue() or TryAddToIncomingQueue() to make sure that posting
-  // task is properly synchronized between different threads.
-  //
-  // Returns true if the task was successfully added to the queue, otherwise
-  // returns false. In all cases, the ownership of |task| is transferred to the
-  // called method.
-  bool AddToIncomingQueue(const Location& from_here,
-                          OnceClosure task,
-                          TimeDelta delay,
-                          Nestable nestable);
-
-  // Disconnects |this| from the parent message loop.
-  void WillDestroyCurrentMessageLoop();
-
-  // This should be called when the message loop becomes ready for
-  // scheduling work.
-  void StartScheduling();
-
-  // Runs |pending_task|.
-  void RunTask(PendingTask* pending_task);
-
-  ReadAndRemoveOnlyQueue& triage_tasks() { return triage_tasks_; }
-
-  Queue& delayed_tasks() { return delayed_tasks_; }
-
-  Queue& deferred_tasks() { return deferred_tasks_; }
-
-  bool HasPendingHighResolutionTasks() {
-    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-    return pending_high_res_tasks_ > 0;
-  }
-
- private:
-  friend class base::PostTaskTest;
-  friend class RefCountedThreadSafe<IncomingTaskQueue>;
-
-  // These queues below support the previous MessageLoop behavior of
-  // maintaining three queue queues to process tasks:
-  //
-  // TriageQueue
-  // The first queue to receive all tasks for the processing sequence (when
-  // reloading from the thread-safe |incoming_queue_|). Tasks are generally
-  // either dispatched immediately or sent to the queues below.
-  //
-  // DelayedQueue
-  // The queue for holding tasks that should be run later and sorted by expected
-  // run time.
-  //
-  // DeferredQueue
-  // The queue for holding tasks that couldn't be run while the MessageLoop was
-  // nested. These are generally processed during the idle stage.
-  //
-  // Many of these do not share implementations even though they look like they
-  // could because of small quirks (reloading semantics) or differing underlying
-  // data strucutre (TaskQueue vs DelayedTaskQueue).
-
-  // The starting point for all tasks on the sequence processing the tasks.
-  class TriageQueue : public ReadAndRemoveOnlyQueue {
-   public:
-    TriageQueue(IncomingTaskQueue* outer);
-    ~TriageQueue() override;
-
-    // ReadAndRemoveOnlyQueue:
-    // In general, the methods below will attempt to reload from the incoming
-    // queue if the queue itself is empty except for Clear(). See Clear() for
-    // why it doesn't reload.
-    const PendingTask& Peek() override;
-    PendingTask Pop() override;
-    // Whether this queue has tasks after reloading from the incoming queue.
-    bool HasTasks() override;
-    void Clear() override;
-
-   private:
-    void ReloadFromIncomingQueueIfEmpty();
-
-    IncomingTaskQueue* const outer_;
-    TaskQueue queue_;
-
-    DISALLOW_COPY_AND_ASSIGN(TriageQueue);
-  };
-
-  class DelayedQueue : public Queue {
-   public:
-    DelayedQueue(IncomingTaskQueue* outer);
-    ~DelayedQueue() override;
-
-    // Queue:
-    const PendingTask& Peek() override;
-    PendingTask Pop() override;
-    // Whether this queue has tasks after sweeping the cancelled ones in front.
-    bool HasTasks() override;
-    void Clear() override;
-    void Push(PendingTask pending_task) override;
-
-   private:
-    IncomingTaskQueue* const outer_;
-    DelayedTaskQueue queue_;
-
-    DISALLOW_COPY_AND_ASSIGN(DelayedQueue);
-  };
-
-  class DeferredQueue : public Queue {
-   public:
-    DeferredQueue(IncomingTaskQueue* outer);
-    ~DeferredQueue() override;
-
-    // Queue:
-    const PendingTask& Peek() override;
-    PendingTask Pop() override;
-    bool HasTasks() override;
-    void Clear() override;
-    void Push(PendingTask pending_task) override;
-
-   private:
-    IncomingTaskQueue* const outer_;
-    TaskQueue queue_;
-
-    DISALLOW_COPY_AND_ASSIGN(DeferredQueue);
-  };
-
-  virtual ~IncomingTaskQueue();
-
-  // Adds a task to |incoming_queue_|. The caller retains ownership of
-  // |pending_task|, but this function will reset the value of
-  // |pending_task->task|. This is needed to ensure that the posting call stack
-  // does not retain |pending_task->task| beyond this function call.
-  bool PostPendingTask(PendingTask* pending_task);
-
-  // Does the real work of posting a pending task. Returns true if the caller
-  // should call ScheduleWork() on the message loop.
-  bool PostPendingTaskLockRequired(PendingTask* pending_task);
-
-  // Loads tasks from the |incoming_queue_| into |*work_queue|. Must be called
-  // from the sequence processing the tasks. Returns the number of tasks that
-  // require high resolution timers in |work_queue|.
-  int ReloadWorkQueue(TaskQueue* work_queue);
-
-  // Checks calls made only on the MessageLoop thread.
-  SEQUENCE_CHECKER(sequence_checker_);
-
-  // True if we always need to call ScheduleWork when receiving a new task, even
-  // if the incoming queue was not empty.
-  const bool always_schedule_work_;
-
-  // Queue for initial triaging of tasks on the |sequence_checker_| sequence.
-  TriageQueue triage_tasks_;
-
-  // Queue for delayed tasks on the |sequence_checker_| sequence.
-  DelayedQueue delayed_tasks_;
-
-  // Queue for non-nestable deferred tasks on the |sequence_checker_| sequence.
-  DeferredQueue deferred_tasks_;
-
-  // Number of high resolution tasks in the sequence affine queues above.
-  int pending_high_res_tasks_ = 0;
-
-  // Lock that serializes |message_loop_->ScheduleWork()| calls as well as
-  // prevents |message_loop_| from being made nullptr during such a call.
-  base::Lock message_loop_lock_;
-
-  // Points to the message loop that owns |this|.
-  MessageLoop* message_loop_;
-
-  // Synchronizes access to all members below this line.
-  base::Lock incoming_queue_lock_;
-
-  // Number of tasks that require high resolution timing. This value is kept
-  // so that ReloadWorkQueue() completes in constant time.
-  int high_res_task_count_ = 0;
-
-  // An incoming queue of tasks that are acquired under a mutex for processing
-  // on this instance's thread. These tasks have not yet been been pushed to
-  // |triage_tasks_|.
-  TaskQueue incoming_queue_;
-
-  // True if new tasks should be accepted.
-  bool accept_new_tasks_ = true;
-
-  // The next sequence number to use for delayed tasks.
-  int next_sequence_num_ = 0;
-
-  // True if our message loop has already been scheduled and does not need to be
-  // scheduled again until an empty reload occurs.
-  bool message_loop_scheduled_ = false;
-
-  // False until StartScheduling() is called.
-  bool is_ready_for_scheduling_ = false;
-
-  DISALLOW_COPY_AND_ASSIGN(IncomingTaskQueue);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_INCOMING_TASK_QUEUE_H_
diff --git a/base/message_loop/message_loop.cc b/base/message_loop/message_loop.cc
deleted file mode 100644
index f81f1a8..0000000
--- a/base/message_loop/message_loop.cc
+++ /dev/null
@@ -1,484 +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 "base/message_loop/message_loop.h"
-
-#include <algorithm>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/memory/ptr_util.h"
-#include "base/message_loop/message_pump_default.h"
-#include "base/message_loop/message_pump_for_io.h"
-#include "base/message_loop/message_pump_for_ui.h"
-#include "base/run_loop.h"
-#include "base/threading/thread_id_name_manager.h"
-#include "base/threading/thread_task_runner_handle.h"
-
-#if defined(OS_MACOSX)
-#include "base/message_loop/message_pump_mac.h"
-#endif
-
-namespace base {
-
-namespace {
-
-MessageLoop::MessagePumpFactory* message_pump_for_ui_factory_ = nullptr;
-
-std::unique_ptr<MessagePump> ReturnPump(std::unique_ptr<MessagePump> pump) {
-  return pump;
-}
-
-}  // namespace
-
-//------------------------------------------------------------------------------
-
-MessageLoop::MessageLoop(Type type)
-    : MessageLoop(type, MessagePumpFactoryCallback()) {
-  BindToCurrentThread();
-}
-
-MessageLoop::MessageLoop(std::unique_ptr<MessagePump> pump)
-    : MessageLoop(TYPE_CUSTOM, BindOnce(&ReturnPump, std::move(pump))) {
-  BindToCurrentThread();
-}
-
-MessageLoop::~MessageLoop() {
-  // If |pump_| is non-null, this message loop has been bound and should be the
-  // current one on this thread. Otherwise, this loop is being destructed before
-  // it was bound to a thread, so a different message loop (or no loop at all)
-  // may be current.
-  DCHECK((pump_ && MessageLoopCurrent::IsBoundToCurrentThreadInternal(this)) ||
-         (!pump_ && !MessageLoopCurrent::IsBoundToCurrentThreadInternal(this)));
-
-  // iOS just attaches to the loop, it doesn't Run it.
-  // TODO(stuartmorgan): Consider wiring up a Detach().
-#if !defined(OS_IOS)
-  // There should be no active RunLoops on this thread, unless this MessageLoop
-  // isn't bound to the current thread (see other condition at the top of this
-  // method).
-  DCHECK(
-      (!pump_ && !MessageLoopCurrent::IsBoundToCurrentThreadInternal(this)) ||
-      !RunLoop::IsRunningOnCurrentThread());
-#endif  // !defined(OS_IOS)
-
-#if defined(OS_WIN)
-  if (in_high_res_mode_)
-    Time::ActivateHighResolutionTimer(false);
-#endif
-  // Clean up any unprocessed tasks, but take care: deleting a task could
-  // result in the addition of more tasks (e.g., via DeleteSoon).  We set a
-  // limit on the number of times we will allow a deleted task to generate more
-  // tasks.  Normally, we should only pass through this loop once or twice.  If
-  // we end up hitting the loop limit, then it is probably due to one task that
-  // is being stubborn.  Inspect the queues to see who is left.
-  bool tasks_remain;
-  for (int i = 0; i < 100; ++i) {
-    DeletePendingTasks();
-    // If we end up with empty queues, then break out of the loop.
-    tasks_remain = incoming_task_queue_->triage_tasks().HasTasks();
-    if (!tasks_remain)
-      break;
-  }
-  DCHECK(!tasks_remain);
-
-  // Let interested parties have one last shot at accessing this.
-  for (auto& observer : destruction_observers_)
-    observer.WillDestroyCurrentMessageLoop();
-
-  thread_task_runner_handle_.reset();
-
-  // Tell the incoming queue that we are dying.
-  incoming_task_queue_->WillDestroyCurrentMessageLoop();
-  incoming_task_queue_ = nullptr;
-  unbound_task_runner_ = nullptr;
-  task_runner_ = nullptr;
-
-  // OK, now make it so that no one can find us.
-  if (MessageLoopCurrent::IsBoundToCurrentThreadInternal(this))
-    MessageLoopCurrent::UnbindFromCurrentThreadInternal(this);
-}
-
-// static
-MessageLoopCurrent MessageLoop::current() {
-  return MessageLoopCurrent::Get();
-}
-
-// static
-bool MessageLoop::InitMessagePumpForUIFactory(MessagePumpFactory* factory) {
-  if (message_pump_for_ui_factory_)
-    return false;
-
-  message_pump_for_ui_factory_ = factory;
-  return true;
-}
-
-// static
-std::unique_ptr<MessagePump> MessageLoop::CreateMessagePumpForType(Type type) {
-  if (type == MessageLoop::TYPE_UI) {
-    if (message_pump_for_ui_factory_)
-      return message_pump_for_ui_factory_();
-#if defined(OS_IOS) || defined(OS_MACOSX)
-    return MessagePumpMac::Create();
-#elif defined(OS_NACL) || defined(OS_AIX)
-    // Currently NaCl and AIX don't have a UI MessageLoop.
-    // TODO(abarth): Figure out if we need this.
-    NOTREACHED();
-    return nullptr;
-#else
-    return std::make_unique<MessagePumpForUI>();
-#endif
-  }
-
-  if (type == MessageLoop::TYPE_IO)
-    return std::unique_ptr<MessagePump>(new MessagePumpForIO());
-
-#if defined(OS_ANDROID)
-  if (type == MessageLoop::TYPE_JAVA)
-    return std::unique_ptr<MessagePump>(new MessagePumpForUI());
-#endif
-
-  DCHECK_EQ(MessageLoop::TYPE_DEFAULT, type);
-#if defined(OS_IOS)
-  // On iOS, a native runloop is always required to pump system work.
-  return std::make_unique<MessagePumpCFRunLoop>();
-#else
-  return std::make_unique<MessagePumpDefault>();
-#endif
-}
-
-bool MessageLoop::IsType(Type type) const {
-  return type_ == type;
-}
-
-// TODO(gab): Migrate TaskObservers to RunLoop as part of separating concerns
-// between MessageLoop and RunLoop and making MessageLoop a swappable
-// implementation detail. http://crbug.com/703346
-void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
-  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
-  task_observers_.AddObserver(task_observer);
-}
-
-void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
-  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
-  task_observers_.RemoveObserver(task_observer);
-}
-
-bool MessageLoop::IsIdleForTesting() {
-  // Have unprocessed tasks? (this reloads the work queue if necessary)
-  if (incoming_task_queue_->triage_tasks().HasTasks())
-    return false;
-
-  // Have unprocessed deferred tasks which can be processed at this run-level?
-  if (incoming_task_queue_->deferred_tasks().HasTasks() &&
-      !RunLoop::IsNestedOnCurrentThread()) {
-    return false;
-  }
-
-  return true;
-}
-
-//------------------------------------------------------------------------------
-
-// static
-std::unique_ptr<MessageLoop> MessageLoop::CreateUnbound(
-    Type type,
-    MessagePumpFactoryCallback pump_factory) {
-  return WrapUnique(new MessageLoop(type, std::move(pump_factory)));
-}
-
-MessageLoop::MessageLoop(Type type, MessagePumpFactoryCallback pump_factory)
-    : MessageLoopCurrent(this),
-      type_(type),
-      pump_factory_(std::move(pump_factory)),
-      incoming_task_queue_(new internal::IncomingTaskQueue(this)),
-      unbound_task_runner_(
-          new internal::MessageLoopTaskRunner(incoming_task_queue_)),
-      task_runner_(unbound_task_runner_) {
-  // If type is TYPE_CUSTOM non-null pump_factory must be given.
-  DCHECK(type_ != TYPE_CUSTOM || !pump_factory_.is_null());
-
-  // Bound in BindToCurrentThread();
-  DETACH_FROM_THREAD(bound_thread_checker_);
-}
-
-void MessageLoop::BindToCurrentThread() {
-  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
-
-  DCHECK(!pump_);
-  if (!pump_factory_.is_null())
-    pump_ = std::move(pump_factory_).Run();
-  else
-    pump_ = CreateMessagePumpForType(type_);
-
-  DCHECK(!MessageLoopCurrent::IsSet())
-      << "should only have one message loop per thread";
-  MessageLoopCurrent::BindToCurrentThreadInternal(this);
-
-  incoming_task_queue_->StartScheduling();
-  unbound_task_runner_->BindToCurrentThread();
-  unbound_task_runner_ = nullptr;
-  SetThreadTaskRunnerHandle();
-  thread_id_ = PlatformThread::CurrentId();
-
-  scoped_set_sequence_local_storage_map_for_current_thread_ = std::make_unique<
-      internal::ScopedSetSequenceLocalStorageMapForCurrentThread>(
-      &sequence_local_storage_map_);
-
-  RunLoop::RegisterDelegateForCurrentThread(this);
-}
-
-std::string MessageLoop::GetThreadName() const {
-  DCHECK_NE(kInvalidThreadId, thread_id_)
-      << "GetThreadName() must only be called after BindToCurrentThread()'s "
-      << "side-effects have been synchronized with this thread.";
-  return ThreadIdNameManager::GetInstance()->GetName(thread_id_);
-}
-
-void MessageLoop::SetTaskRunner(
-    scoped_refptr<SingleThreadTaskRunner> task_runner) {
-  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
-
-  DCHECK(task_runner);
-  DCHECK(task_runner->BelongsToCurrentThread());
-  DCHECK(!unbound_task_runner_);
-  task_runner_ = std::move(task_runner);
-  SetThreadTaskRunnerHandle();
-}
-
-void MessageLoop::ClearTaskRunnerForTesting() {
-  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
-
-  DCHECK(!unbound_task_runner_);
-  task_runner_ = nullptr;
-  thread_task_runner_handle_.reset();
-}
-
-void MessageLoop::Run(bool application_tasks_allowed) {
-  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
-  if (application_tasks_allowed && !task_execution_allowed_) {
-    // Allow nested task execution as explicitly requested.
-    DCHECK(RunLoop::IsNestedOnCurrentThread());
-    task_execution_allowed_ = true;
-    pump_->Run(this);
-    task_execution_allowed_ = false;
-  } else {
-    pump_->Run(this);
-  }
-}
-
-void MessageLoop::Quit() {
-  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
-  pump_->Quit();
-}
-
-void MessageLoop::EnsureWorkScheduled() {
-  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
-  if (incoming_task_queue_->triage_tasks().HasTasks())
-    pump_->ScheduleWork();
-}
-
-void MessageLoop::SetThreadTaskRunnerHandle() {
-  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
-  // Clear the previous thread task runner first, because only one can exist at
-  // a time.
-  thread_task_runner_handle_.reset();
-  thread_task_runner_handle_.reset(new ThreadTaskRunnerHandle(task_runner_));
-}
-
-bool MessageLoop::ProcessNextDelayedNonNestableTask() {
-  if (RunLoop::IsNestedOnCurrentThread())
-    return false;
-
-  while (incoming_task_queue_->deferred_tasks().HasTasks()) {
-    PendingTask pending_task = incoming_task_queue_->deferred_tasks().Pop();
-    if (!pending_task.task.IsCancelled()) {
-      RunTask(&pending_task);
-      return true;
-    }
-  }
-
-  return false;
-}
-
-void MessageLoop::RunTask(PendingTask* pending_task) {
-  DCHECK(task_execution_allowed_);
-
-  // Execute the task and assume the worst: It is probably not reentrant.
-  task_execution_allowed_ = false;
-
-  for (auto& observer : task_observers_)
-    observer.WillProcessTask(*pending_task);
-  incoming_task_queue_->RunTask(pending_task);
-  for (auto& observer : task_observers_)
-    observer.DidProcessTask(*pending_task);
-
-  task_execution_allowed_ = true;
-}
-
-bool MessageLoop::DeferOrRunPendingTask(PendingTask pending_task) {
-  if (pending_task.nestable == Nestable::kNestable ||
-      !RunLoop::IsNestedOnCurrentThread()) {
-    RunTask(&pending_task);
-    // Show that we ran a task (Note: a new one might arrive as a
-    // consequence!).
-    return true;
-  }
-
-  // We couldn't run the task now because we're in a nested run loop
-  // and the task isn't nestable.
-  incoming_task_queue_->deferred_tasks().Push(std::move(pending_task));
-  return false;
-}
-
-void MessageLoop::DeletePendingTasks() {
-  incoming_task_queue_->triage_tasks().Clear();
-  incoming_task_queue_->deferred_tasks().Clear();
-  // TODO(robliao): Determine if we can move delayed task destruction before
-  // deferred tasks to maintain the MessagePump DoWork, DoDelayedWork, and
-  // DoIdleWork processing order.
-  incoming_task_queue_->delayed_tasks().Clear();
-}
-
-void MessageLoop::ScheduleWork() {
-  pump_->ScheduleWork();
-}
-
-bool MessageLoop::DoWork() {
-  if (!task_execution_allowed_)
-    return false;
-
-  // Execute oldest task.
-  while (incoming_task_queue_->triage_tasks().HasTasks()) {
-    PendingTask pending_task = incoming_task_queue_->triage_tasks().Pop();
-    if (pending_task.task.IsCancelled())
-      continue;
-
-    if (!pending_task.delayed_run_time.is_null()) {
-      int sequence_num = pending_task.sequence_num;
-      TimeTicks delayed_run_time = pending_task.delayed_run_time;
-      incoming_task_queue_->delayed_tasks().Push(std::move(pending_task));
-      // If we changed the topmost task, then it is time to reschedule.
-      if (incoming_task_queue_->delayed_tasks().Peek().sequence_num ==
-          sequence_num) {
-        pump_->ScheduleDelayedWork(delayed_run_time);
-      }
-    } else if (DeferOrRunPendingTask(std::move(pending_task))) {
-      return true;
-    }
-  }
-
-  // Nothing happened.
-  return false;
-}
-
-bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) {
-  if (!task_execution_allowed_ ||
-      !incoming_task_queue_->delayed_tasks().HasTasks()) {
-    recent_time_ = *next_delayed_work_time = TimeTicks();
-    return false;
-  }
-
-  // When we "fall behind", there will be a lot of tasks in the delayed work
-  // queue that are ready to run.  To increase efficiency when we fall behind,
-  // we will only call Time::Now() intermittently, and then process all tasks
-  // that are ready to run before calling it again.  As a result, the more we
-  // fall behind (and have a lot of ready-to-run delayed tasks), the more
-  // efficient we'll be at handling the tasks.
-
-  TimeTicks next_run_time =
-      incoming_task_queue_->delayed_tasks().Peek().delayed_run_time;
-  if (next_run_time > recent_time_) {
-    recent_time_ = TimeTicks::Now();  // Get a better view of Now();
-    if (next_run_time > recent_time_) {
-      *next_delayed_work_time = next_run_time;
-      return false;
-    }
-  }
-
-  PendingTask pending_task = incoming_task_queue_->delayed_tasks().Pop();
-
-  if (incoming_task_queue_->delayed_tasks().HasTasks()) {
-    *next_delayed_work_time =
-        incoming_task_queue_->delayed_tasks().Peek().delayed_run_time;
-  }
-
-  return DeferOrRunPendingTask(std::move(pending_task));
-}
-
-bool MessageLoop::DoIdleWork() {
-  if (ProcessNextDelayedNonNestableTask())
-    return true;
-
-  if (ShouldQuitWhenIdle())
-    pump_->Quit();
-
-  // When we return we will do a kernel wait for more tasks.
-#if defined(OS_WIN)
-  // On Windows we activate the high resolution timer so that the wait
-  // _if_ triggered by the timer happens with good resolution. If we don't
-  // do this the default resolution is 15ms which might not be acceptable
-  // for some tasks.
-  bool high_res = incoming_task_queue_->HasPendingHighResolutionTasks();
-  if (high_res != in_high_res_mode_) {
-    in_high_res_mode_ = high_res;
-    Time::ActivateHighResolutionTimer(in_high_res_mode_);
-  }
-#endif
-  return false;
-}
-
-#if !defined(OS_NACL)
-
-//------------------------------------------------------------------------------
-// MessageLoopForUI
-
-MessageLoopForUI::MessageLoopForUI(std::unique_ptr<MessagePump> pump)
-    : MessageLoop(TYPE_UI, BindOnce(&ReturnPump, std::move(pump))) {}
-
-// static
-MessageLoopCurrentForUI MessageLoopForUI::current() {
-  return MessageLoopCurrentForUI::Get();
-}
-
-// static
-bool MessageLoopForUI::IsCurrent() {
-  return MessageLoopCurrentForUI::IsSet();
-}
-
-#if defined(OS_IOS)
-void MessageLoopForUI::Attach() {
-  static_cast<MessagePumpUIApplication*>(pump_.get())->Attach(this);
-}
-#endif  // defined(OS_IOS)
-
-#if defined(OS_ANDROID)
-void MessageLoopForUI::Start() {
-  // No Histogram support for UI message loop as it is managed by Java side
-  static_cast<MessagePumpForUI*>(pump_.get())->Start(this);
-}
-
-void MessageLoopForUI::Abort() {
-  static_cast<MessagePumpForUI*>(pump_.get())->Abort();
-}
-#endif  // defined(OS_ANDROID)
-
-#endif  // !defined(OS_NACL)
-
-//------------------------------------------------------------------------------
-// MessageLoopForIO
-
-// static
-MessageLoopCurrentForIO MessageLoopForIO::current() {
-  return MessageLoopCurrentForIO::Get();
-}
-
-// static
-bool MessageLoopForIO::IsCurrent() {
-  return MessageLoopCurrentForIO::IsSet();
-}
-
-}  // namespace base
diff --git a/base/message_loop/message_loop.h b/base/message_loop/message_loop.h
deleted file mode 100644
index 6bcccb8..0000000
--- a/base/message_loop/message_loop.h
+++ /dev/null
@@ -1,403 +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_MESSAGE_LOOP_MESSAGE_LOOP_H_
-#define BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_
-
-#include <memory>
-#include <queue>
-#include <string>
-
-#include "base/base_export.h"
-#include "base/callback_forward.h"
-#include "base/gtest_prod_util.h"
-#include "base/macros.h"
-#include "base/memory/scoped_refptr.h"
-#include "base/message_loop/incoming_task_queue.h"
-#include "base/message_loop/message_loop_current.h"
-#include "base/message_loop/message_loop_task_runner.h"
-#include "base/message_loop/message_pump.h"
-#include "base/message_loop/timer_slack.h"
-#include "base/observer_list.h"
-#include "base/pending_task.h"
-#include "base/run_loop.h"
-#include "base/synchronization/lock.h"
-#include "base/threading/sequence_local_storage_map.h"
-#include "base/threading/thread_checker.h"
-#include "base/time/time.h"
-#include "build_config.h"
-
-namespace base {
-
-class ThreadTaskRunnerHandle;
-
-// A MessageLoop is used to process events for a particular thread.  There is
-// at most one MessageLoop instance per thread.
-//
-// Events include at a minimum Task instances submitted to the MessageLoop's
-// TaskRunner. Depending on the type of message pump used by the MessageLoop
-// other events such as UI messages may be processed.  On Windows APC calls (as
-// time permits) and signals sent to a registered set of HANDLEs may also be
-// processed.
-//
-// The MessageLoop's API should only be used directly by its owner (and users
-// which the owner opts to share a MessageLoop* with). Other ways to access
-// subsets of the MessageLoop API:
-//   - base::RunLoop : Drive the MessageLoop from the thread it's bound to.
-//   - base::Thread/SequencedTaskRunnerHandle : Post back to the MessageLoop
-//     from a task running on it.
-//   - SequenceLocalStorageSlot : Bind external state to this MessageLoop.
-//   - base::MessageLoopCurrent : Access statically exposed APIs of this
-//     MessageLoop.
-//   - Embedders may provide their own static accessors to post tasks on
-//     specific loops (e.g. content::BrowserThreads).
-//
-// NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
-// on the thread where the MessageLoop's Run method executes.
-//
-// NOTE: MessageLoop has task reentrancy protection.  This means that if a
-// task is being processed, a second task cannot start until the first task is
-// finished.  Reentrancy can happen when processing a task, and an inner
-// message pump is created.  That inner pump then processes native messages
-// which could implicitly start an inner task.  Inner message pumps are created
-// with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
-// (DoDragDrop), printer functions (StartDoc) and *many* others.
-//
-// Sample workaround when inner task processing is needed:
-//   HRESULT hr;
-//   {
-//     MessageLoopCurrent::ScopedNestableTaskAllower allow;
-//     hr = DoDragDrop(...); // Implicitly runs a modal message loop.
-//   }
-//   // Process |hr| (the result returned by DoDragDrop()).
-//
-// Please be SURE your task is reentrant (nestable) and all global variables
-// are stable and accessible before calling SetNestableTasksAllowed(true).
-//
-// TODO(gab): MessageLoop doesn't need to be a MessageLoopCurrent once callers
-// that store MessageLoop::current() in a MessageLoop* variable have been
-// updated to use a MessageLoopCurrent variable.
-class BASE_EXPORT MessageLoop : public MessagePump::Delegate,
-                                public RunLoop::Delegate,
-                                public MessageLoopCurrent {
- public:
-  // TODO(gab): Migrate usage of this class to MessageLoopCurrent and remove
-  // this forwarded declaration.
-  using DestructionObserver = MessageLoopCurrent::DestructionObserver;
-
-  // A MessageLoop has a particular type, which indicates the set of
-  // asynchronous events it may process in addition to tasks and timers.
-  //
-  // TYPE_DEFAULT
-  //   This type of ML only supports tasks and timers.
-  //
-  // TYPE_UI
-  //   This type of ML also supports native UI events (e.g., Windows messages).
-  //   See also MessageLoopForUI.
-  //
-  // TYPE_IO
-  //   This type of ML also supports asynchronous IO.  See also
-  //   MessageLoopForIO.
-  //
-  // TYPE_JAVA
-  //   This type of ML is backed by a Java message handler which is responsible
-  //   for running the tasks added to the ML. This is only for use on Android.
-  //   TYPE_JAVA behaves in essence like TYPE_UI, except during construction
-  //   where it does not use the main thread specific pump factory.
-  //
-  // TYPE_CUSTOM
-  //   MessagePump was supplied to constructor.
-  //
-  enum Type {
-    TYPE_DEFAULT,
-    TYPE_UI,
-    TYPE_CUSTOM,
-    TYPE_IO,
-#if defined(OS_ANDROID)
-    TYPE_JAVA,
-#endif  // defined(OS_ANDROID)
-  };
-
-  // Normally, it is not necessary to instantiate a MessageLoop.  Instead, it
-  // is typical to make use of the current thread's MessageLoop instance.
-  explicit MessageLoop(Type type = TYPE_DEFAULT);
-  // Creates a TYPE_CUSTOM MessageLoop with the supplied MessagePump, which must
-  // be non-NULL.
-  explicit MessageLoop(std::unique_ptr<MessagePump> pump);
-
-  ~MessageLoop() override;
-
-  // TODO(gab): Mass migrate callers to MessageLoopCurrent::Get().
-  static MessageLoopCurrent current();
-
-  using MessagePumpFactory = std::unique_ptr<MessagePump>();
-  // Uses the given base::MessagePumpForUIFactory to override the default
-  // MessagePump implementation for 'TYPE_UI'. Returns true if the factory
-  // was successfully registered.
-  static bool InitMessagePumpForUIFactory(MessagePumpFactory* factory);
-
-  // Creates the default MessagePump based on |type|. Caller owns return
-  // value.
-  static std::unique_ptr<MessagePump> CreateMessagePumpForType(Type type);
-
-  // Set the timer slack for this message loop.
-  void SetTimerSlack(TimerSlack timer_slack) {
-    pump_->SetTimerSlack(timer_slack);
-  }
-
-  // Returns true if this loop is |type|. This allows subclasses (especially
-  // those in tests) to specialize how they are identified.
-  virtual bool IsType(Type type) const;
-
-  // Returns the type passed to the constructor.
-  Type type() const { return type_; }
-
-  // Returns the name of the thread this message loop is bound to. This function
-  // is only valid when this message loop is running, BindToCurrentThread has
-  // already been called and has an "happens-before" relationship with this call
-  // (this relationship is obtained implicitly by the MessageLoop's task posting
-  // system unless calling this very early).
-  std::string GetThreadName() const;
-
-  // Gets the TaskRunner associated with this message loop.
-  const scoped_refptr<SingleThreadTaskRunner>& task_runner() const {
-    return task_runner_;
-  }
-
-  // Sets a new TaskRunner for this message loop. The message loop must already
-  // have been bound to a thread prior to this call, and the task runner must
-  // belong to that thread. Note that changing the task runner will also affect
-  // the ThreadTaskRunnerHandle for the target thread. Must be called on the
-  // thread to which the message loop is bound.
-  void SetTaskRunner(scoped_refptr<SingleThreadTaskRunner> task_runner);
-
-  // Clears task_runner() and the ThreadTaskRunnerHandle for the target thread.
-  // Must be called on the thread to which the message loop is bound.
-  void ClearTaskRunnerForTesting();
-
-  // TODO(https://crbug.com/825327): Remove users of TaskObservers through
-  // MessageLoop::current() and migrate the type back here.
-  using TaskObserver = MessageLoopCurrent::TaskObserver;
-
-  // These functions can only be called on the same thread that |this| is
-  // running on.
-  void AddTaskObserver(TaskObserver* task_observer);
-  void RemoveTaskObserver(TaskObserver* task_observer);
-
-  // Returns true if the message loop is idle (ignoring delayed tasks). This is
-  // the same condition which triggers DoWork() to return false: i.e.
-  // out of tasks which can be processed at the current run-level -- there might
-  // be deferred non-nestable tasks remaining if currently in a nested run
-  // level.
-  bool IsIdleForTesting();
-
-  // Runs the specified PendingTask.
-  void RunTask(PendingTask* pending_task);
-
-  //----------------------------------------------------------------------------
- protected:
-  std::unique_ptr<MessagePump> pump_;
-
-  using MessagePumpFactoryCallback =
-      OnceCallback<std::unique_ptr<MessagePump>()>;
-
-  // Common protected constructor. Other constructors delegate the
-  // initialization to this constructor.
-  // A subclass can invoke this constructor to create a message_loop of a
-  // specific type with a custom loop. The implementation does not call
-  // BindToCurrentThread. If this constructor is invoked directly by a subclass,
-  // then the subclass must subsequently bind the message loop.
-  MessageLoop(Type type, MessagePumpFactoryCallback pump_factory);
-
-  // Configure various members and bind this message loop to the current thread.
-  void BindToCurrentThread();
-
- private:
-  friend class internal::IncomingTaskQueue;
-  friend class MessageLoopCurrent;
-  friend class MessageLoopCurrentForIO;
-  friend class MessageLoopCurrentForUI;
-  friend class ScheduleWorkTest;
-  friend class Thread;
-  FRIEND_TEST_ALL_PREFIXES(MessageLoopTest, DeleteUnboundLoop);
-
-  // Creates a MessageLoop without binding to a thread.
-  // If |type| is TYPE_CUSTOM non-null |pump_factory| must be also given
-  // to create a message pump for this message loop.  Otherwise a default
-  // message pump for the |type| is created.
-  //
-  // It is valid to call this to create a new message loop on one thread,
-  // and then pass it to the thread where the message loop actually runs.
-  // The message loop's BindToCurrentThread() method must be called on the
-  // thread the message loop runs on, before calling Run().
-  // Before BindToCurrentThread() is called, only Post*Task() functions can
-  // be called on the message loop.
-  static std::unique_ptr<MessageLoop> CreateUnbound(
-      Type type,
-      MessagePumpFactoryCallback pump_factory);
-
-  // Sets the ThreadTaskRunnerHandle for the current thread to point to the
-  // task runner for this message loop.
-  void SetThreadTaskRunnerHandle();
-
-  // RunLoop::Delegate:
-  void Run(bool application_tasks_allowed) override;
-  void Quit() override;
-  void EnsureWorkScheduled() override;
-
-  // Called to process any delayed non-nestable tasks.
-  bool ProcessNextDelayedNonNestableTask();
-
-  // Calls RunTask or queues the pending_task on the deferred task list if it
-  // cannot be run right now.  Returns true if the task was run.
-  bool DeferOrRunPendingTask(PendingTask pending_task);
-
-  // Delete tasks that haven't run yet without running them.  Used in the
-  // destructor to make sure all the task's destructors get called.
-  void DeletePendingTasks();
-
-  // Wakes up the message pump. Can be called on any thread. The caller is
-  // responsible for synchronizing ScheduleWork() calls.
-  void ScheduleWork();
-
-  // MessagePump::Delegate methods:
-  bool DoWork() override;
-  bool DoDelayedWork(TimeTicks* next_delayed_work_time) override;
-  bool DoIdleWork() override;
-
-  const Type type_;
-
-#if defined(OS_WIN)
-  // Tracks if we have requested high resolution timers. Its only use is to
-  // turn off the high resolution timer upon loop destruction.
-  bool in_high_res_mode_ = false;
-#endif
-
-  // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
-  TimeTicks recent_time_;
-
-  ObserverList<DestructionObserver> destruction_observers_;
-
-  // A boolean which prevents unintentional reentrant task execution (e.g. from
-  // induced nested message loops). As such, nested message loops will only
-  // process system messages (not application tasks) by default. A nested loop
-  // layer must have been explicitly granted permission to be able to execute
-  // application tasks. This is granted either by
-  // RunLoop::Type::kNestableTasksAllowed when the loop is driven by the
-  // application or by a ScopedNestableTaskAllower preceding a system call that
-  // is known to generate a system-driven nested loop.
-  bool task_execution_allowed_ = true;
-
-  // pump_factory_.Run() is called to create a message pump for this loop
-  // if type_ is TYPE_CUSTOM and pump_ is null.
-  MessagePumpFactoryCallback pump_factory_;
-
-  ObserverList<TaskObserver> task_observers_;
-
-  scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
-
-  // A task runner which we haven't bound to a thread yet.
-  scoped_refptr<internal::MessageLoopTaskRunner> unbound_task_runner_;
-
-  // The task runner associated with this message loop.
-  scoped_refptr<SingleThreadTaskRunner> task_runner_;
-  std::unique_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
-
-  // Id of the thread this message loop is bound to. Initialized once when the
-  // MessageLoop is bound to its thread and constant forever after.
-  PlatformThreadId thread_id_ = kInvalidThreadId;
-
-  // Holds data stored through the SequenceLocalStorageSlot API.
-  internal::SequenceLocalStorageMap sequence_local_storage_map_;
-
-  // Enables the SequenceLocalStorageSlot API within its scope.
-  // Instantiated in BindToCurrentThread().
-  std::unique_ptr<internal::ScopedSetSequenceLocalStorageMapForCurrentThread>
-      scoped_set_sequence_local_storage_map_for_current_thread_;
-
-  // Verifies that calls are made on the thread on which BindToCurrentThread()
-  // was invoked.
-  THREAD_CHECKER(bound_thread_checker_);
-
-  DISALLOW_COPY_AND_ASSIGN(MessageLoop);
-};
-
-#if !defined(OS_NACL)
-
-//-----------------------------------------------------------------------------
-// MessageLoopForUI extends MessageLoop with methods that are particular to a
-// MessageLoop instantiated with TYPE_UI.
-//
-// By instantiating a MessageLoopForUI on the current thread, the owner enables
-// native UI message pumping.
-//
-// MessageLoopCurrentForUI is exposed statically on its thread via
-// MessageLoopCurrentForUI::Get() to provide additional functionality.
-//
-class BASE_EXPORT MessageLoopForUI : public MessageLoop {
- public:
-  MessageLoopForUI() : MessageLoop(TYPE_UI) {
-  }
-
-  explicit MessageLoopForUI(std::unique_ptr<MessagePump> pump);
-
-  // TODO(gab): Mass migrate callers to MessageLoopCurrentForUI::Get()/IsSet().
-  static MessageLoopCurrentForUI current();
-  static bool IsCurrent();
-
-#if defined(OS_IOS)
-  // On iOS, the main message loop cannot be Run().  Instead call Attach(),
-  // which connects this MessageLoop to the UI thread's CFRunLoop and allows
-  // PostTask() to work.
-  void Attach();
-#endif
-
-#if defined(OS_ANDROID)
-  // On Android, the UI message loop is handled by Java side. So Run() should
-  // never be called. Instead use Start(), which will forward all the native UI
-  // events to the Java message loop.
-  void Start();
-
-  // In Android there are cases where we want to abort immediately without
-  // calling Quit(), in these cases we call Abort().
-  void Abort();
-#endif
-};
-
-// Do not add any member variables to MessageLoopForUI!  This is important b/c
-// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI).  Any extra
-// data that you need should be stored on the MessageLoop's pump_ instance.
-static_assert(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
-              "MessageLoopForUI should not have extra member variables");
-
-#endif  // !defined(OS_NACL)
-
-//-----------------------------------------------------------------------------
-// MessageLoopForIO extends MessageLoop with methods that are particular to a
-// MessageLoop instantiated with TYPE_IO.
-//
-// By instantiating a MessageLoopForIO on the current thread, the owner enables
-// native async IO message pumping.
-//
-// MessageLoopCurrentForIO is exposed statically on its thread via
-// MessageLoopCurrentForIO::Get() to provide additional functionality.
-//
-class BASE_EXPORT MessageLoopForIO : public MessageLoop {
- public:
-  MessageLoopForIO() : MessageLoop(TYPE_IO) {}
-
-  // TODO(gab): Mass migrate callers to MessageLoopCurrentForIO::Get()/IsSet().
-  static MessageLoopCurrentForIO current();
-  static bool IsCurrent();
-};
-
-// Do not add any member variables to MessageLoopForIO!  This is important b/c
-// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO).  Any extra
-// data that you need should be stored on the MessageLoop's pump_ instance.
-static_assert(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
-              "MessageLoopForIO should not have extra member variables");
-
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_
diff --git a/base/message_loop/message_loop_current.cc b/base/message_loop/message_loop_current.cc
deleted file mode 100644
index 0beef5a..0000000
--- a/base/message_loop/message_loop_current.cc
+++ /dev/null
@@ -1,252 +0,0 @@
-// Copyright 2018 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/message_loop/message_loop_current.h"
-
-#include "base/bind.h"
-#include "base/message_loop/message_loop.h"
-#include "base/message_loop/message_pump_for_io.h"
-#include "base/message_loop/message_pump_for_ui.h"
-#include "base/no_destructor.h"
-#include "base/threading/thread_local.h"
-
-namespace base {
-
-namespace {
-
-base::ThreadLocalPointer<MessageLoop>* GetTLSMessageLoop() {
-  static NoDestructor<ThreadLocalPointer<MessageLoop>> lazy_tls_ptr;
-  return lazy_tls_ptr.get();
-}
-
-}  // namespace
-
-//------------------------------------------------------------------------------
-// MessageLoopCurrent
-
-// static
-MessageLoopCurrent MessageLoopCurrent::Get() {
-  return MessageLoopCurrent(GetTLSMessageLoop()->Get());
-}
-
-// static
-bool MessageLoopCurrent::IsSet() {
-  return !!GetTLSMessageLoop()->Get();
-}
-
-void MessageLoopCurrent::AddDestructionObserver(
-    DestructionObserver* destruction_observer) {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  current_->destruction_observers_.AddObserver(destruction_observer);
-}
-
-void MessageLoopCurrent::RemoveDestructionObserver(
-    DestructionObserver* destruction_observer) {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  current_->destruction_observers_.RemoveObserver(destruction_observer);
-}
-
-const scoped_refptr<SingleThreadTaskRunner>& MessageLoopCurrent::task_runner()
-    const {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  return current_->task_runner();
-}
-
-void MessageLoopCurrent::SetTaskRunner(
-    scoped_refptr<SingleThreadTaskRunner> task_runner) {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  current_->SetTaskRunner(std::move(task_runner));
-}
-
-bool MessageLoopCurrent::IsIdleForTesting() {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  return current_->IsIdleForTesting();
-}
-
-void MessageLoopCurrent::AddTaskObserver(TaskObserver* task_observer) {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  current_->AddTaskObserver(task_observer);
-}
-
-void MessageLoopCurrent::RemoveTaskObserver(TaskObserver* task_observer) {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  current_->RemoveTaskObserver(task_observer);
-}
-
-void MessageLoopCurrent::SetNestableTasksAllowed(bool allowed) {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  if (allowed) {
-    // Kick the native pump just in case we enter a OS-driven nested message
-    // loop that does not go through RunLoop::Run().
-    current_->pump_->ScheduleWork();
-  }
-  current_->task_execution_allowed_ = allowed;
-}
-
-bool MessageLoopCurrent::NestableTasksAllowed() const {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  return current_->task_execution_allowed_;
-}
-
-MessageLoopCurrent::ScopedNestableTaskAllower::ScopedNestableTaskAllower()
-    : loop_(GetTLSMessageLoop()->Get()),
-      old_state_(loop_->NestableTasksAllowed()) {
-  loop_->SetNestableTasksAllowed(true);
-}
-
-MessageLoopCurrent::ScopedNestableTaskAllower::~ScopedNestableTaskAllower() {
-  loop_->SetNestableTasksAllowed(old_state_);
-}
-
-// static
-void MessageLoopCurrent::BindToCurrentThreadInternal(MessageLoop* current) {
-  DCHECK(!GetTLSMessageLoop()->Get())
-      << "Can't register a second MessageLoop on the same thread.";
-  GetTLSMessageLoop()->Set(current);
-}
-
-// static
-void MessageLoopCurrent::UnbindFromCurrentThreadInternal(MessageLoop* current) {
-  DCHECK_EQ(current, GetTLSMessageLoop()->Get());
-  GetTLSMessageLoop()->Set(nullptr);
-}
-
-bool MessageLoopCurrent::IsBoundToCurrentThreadInternal(
-    MessageLoop* message_loop) {
-  return GetTLSMessageLoop()->Get() == message_loop;
-}
-
-#if !defined(OS_NACL)
-
-//------------------------------------------------------------------------------
-// MessageLoopCurrentForUI
-
-// static
-MessageLoopCurrentForUI MessageLoopCurrentForUI::Get() {
-  MessageLoop* loop = GetTLSMessageLoop()->Get();
-  DCHECK(loop);
-#if defined(OS_ANDROID)
-  DCHECK(loop->IsType(MessageLoop::TYPE_UI) ||
-         loop->IsType(MessageLoop::TYPE_JAVA));
-#else   // defined(OS_ANDROID)
-  DCHECK(loop->IsType(MessageLoop::TYPE_UI));
-#endif  // defined(OS_ANDROID)
-  auto* loop_for_ui = static_cast<MessageLoopForUI*>(loop);
-  return MessageLoopCurrentForUI(
-      loop_for_ui, static_cast<MessagePumpForUI*>(loop_for_ui->pump_.get()));
-}
-
-// static
-bool MessageLoopCurrentForUI::IsSet() {
-  MessageLoop* loop = GetTLSMessageLoop()->Get();
-  return loop &&
-#if defined(OS_ANDROID)
-         (loop->IsType(MessageLoop::TYPE_UI) ||
-          loop->IsType(MessageLoop::TYPE_JAVA));
-#else   // defined(OS_ANDROID)
-         loop->IsType(MessageLoop::TYPE_UI);
-#endif  // defined(OS_ANDROID)
-}
-
-#if defined(USE_OZONE) && !defined(OS_FUCHSIA) && !defined(OS_WIN)
-bool MessageLoopCurrentForUI::WatchFileDescriptor(
-    int fd,
-    bool persistent,
-    MessagePumpForUI::Mode mode,
-    MessagePumpForUI::FdWatchController* controller,
-    MessagePumpForUI::FdWatcher* delegate) {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  return pump_->WatchFileDescriptor(fd, persistent, mode, controller, delegate);
-}
-#endif
-
-#if defined(OS_IOS)
-void MessageLoopCurrentForUI::Attach() {
-  static_cast<MessageLoopForUI*>(current_)->Attach();
-}
-#endif  // defined(OS_IOS)
-
-#if defined(OS_ANDROID)
-void MessageLoopCurrentForUI::Start() {
-  static_cast<MessageLoopForUI*>(current_)->Start();
-}
-
-void MessageLoopCurrentForUI::Abort() {
-  static_cast<MessageLoopForUI*>(current_)->Abort();
-}
-#endif  // defined(OS_ANDROID)
-
-#endif  // !defined(OS_NACL)
-
-//------------------------------------------------------------------------------
-// MessageLoopCurrentForIO
-
-// static
-MessageLoopCurrentForIO MessageLoopCurrentForIO::Get() {
-  MessageLoop* loop = GetTLSMessageLoop()->Get();
-  DCHECK(loop);
-  DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
-  auto* loop_for_io = static_cast<MessageLoopForIO*>(loop);
-  return MessageLoopCurrentForIO(
-      loop_for_io, static_cast<MessagePumpForIO*>(loop_for_io->pump_.get()));
-}
-
-// static
-bool MessageLoopCurrentForIO::IsSet() {
-  MessageLoop* loop = GetTLSMessageLoop()->Get();
-  return loop && loop->IsType(MessageLoop::TYPE_IO);
-}
-
-#if !defined(OS_NACL_SFI)
-
-#if defined(OS_WIN)
-void MessageLoopCurrentForIO::RegisterIOHandler(
-    HANDLE file,
-    MessagePumpForIO::IOHandler* handler) {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  pump_->RegisterIOHandler(file, handler);
-}
-
-bool MessageLoopCurrentForIO::RegisterJobObject(
-    HANDLE job,
-    MessagePumpForIO::IOHandler* handler) {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  return pump_->RegisterJobObject(job, handler);
-}
-
-bool MessageLoopCurrentForIO::WaitForIOCompletion(
-    DWORD timeout,
-    MessagePumpForIO::IOHandler* filter) {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  return pump_->WaitForIOCompletion(timeout, filter);
-}
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
-bool MessageLoopCurrentForIO::WatchFileDescriptor(
-    int fd,
-    bool persistent,
-    MessagePumpForIO::Mode mode,
-    MessagePumpForIO::FdWatchController* controller,
-    MessagePumpForIO::FdWatcher* delegate) {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  return pump_->WatchFileDescriptor(fd, persistent, mode, controller, delegate);
-}
-#endif  // defined(OS_WIN)
-
-#endif  // !defined(OS_NACL_SFI)
-
-#if defined(OS_FUCHSIA)
-// Additional watch API for native platform resources.
-bool MessageLoopCurrentForIO::WatchZxHandle(
-    zx_handle_t handle,
-    bool persistent,
-    zx_signals_t signals,
-    MessagePumpForIO::ZxHandleWatchController* controller,
-    MessagePumpForIO::ZxHandleWatcher* delegate) {
-  DCHECK_CALLED_ON_VALID_THREAD(current_->bound_thread_checker_);
-  return pump_->WatchZxHandle(handle, persistent, signals, controller,
-                              delegate);
-}
-#endif
-
-}  // namespace base
diff --git a/base/message_loop/message_loop_current.h b/base/message_loop/message_loop_current.h
deleted file mode 100644
index 593942b..0000000
--- a/base/message_loop/message_loop_current.h
+++ /dev/null
@@ -1,303 +0,0 @@
-// Copyright 2018 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_MESSAGE_LOOP_MESSAGE_LOOP_CURRENT_H_
-#define BASE_MESSAGE_LOOP_MESSAGE_LOOP_CURRENT_H_
-
-#include "base/base_export.h"
-#include "base/logging.h"
-#include "base/memory/scoped_refptr.h"
-#include "base/message_loop/message_pump_for_io.h"
-#include "base/message_loop/message_pump_for_ui.h"
-#include "base/pending_task.h"
-#include "base/single_thread_task_runner.h"
-#include "build_config.h"
-
-namespace base {
-
-class MessageLoop;
-
-// MessageLoopCurrent is a proxy to the public interface of the MessageLoop
-// bound to the thread it's obtained on.
-//
-// MessageLoopCurrent(ForUI|ForIO) is available statically through
-// MessageLoopCurrent(ForUI|ForIO)::Get() on threads that have a matching
-// MessageLoop instance. APIs intended for all consumers on the thread should be
-// on MessageLoopCurrent(ForUI|ForIO), while APIs intended for the owner of the
-// instance should be on MessageLoop(ForUI|ForIO).
-//
-// Why: Historically MessageLoop::current() gave access to the full MessageLoop
-// API, preventing both addition of powerful owner-only APIs as well as making
-// it harder to remove callers of deprecated APIs (that need to stick around for
-// a few owner-only use cases and re-accrue callers after cleanup per remaining
-// publicly available).
-//
-// As such, many methods below are flagged as deprecated and should be removed
-// (or moved back to MessageLoop) once all static callers have been migrated.
-class BASE_EXPORT MessageLoopCurrent {
- public:
-  // MessageLoopCurrent is effectively just a disguised pointer and is fine to
-  // copy around.
-  MessageLoopCurrent(const MessageLoopCurrent& other) = default;
-  MessageLoopCurrent& operator=(const MessageLoopCurrent& other) = default;
-
-  // Returns a proxy object to interact with the MessageLoop running the
-  // current thread. It must only be used on the thread it was obtained.
-  static MessageLoopCurrent Get();
-
-  // Returns true if the current thread is running a MessageLoop. Prefer this to
-  // verifying the boolean value of Get() (so that Get() can ultimately DCHECK
-  // it's only invoked when IsSet()).
-  static bool IsSet();
-
-  // Allow MessageLoopCurrent to be used like a pointer to support the many
-  // callsites that used MessageLoop::current() that way when it was a
-  // MessageLoop*.
-  MessageLoopCurrent* operator->() { return this; }
-  explicit operator bool() const { return !!current_; }
-
-  // TODO(gab): Migrate the types of variables that store MessageLoop::current()
-  // and remove this implicit cast back to MessageLoop*.
-  operator MessageLoop*() const { return current_; }
-
-  // A DestructionObserver is notified when the current MessageLoop is being
-  // destroyed.  These observers are notified prior to MessageLoop::current()
-  // being changed to return NULL.  This gives interested parties the chance to
-  // do final cleanup that depends on the MessageLoop.
-  //
-  // NOTE: Any tasks posted to the MessageLoop during this notification will
-  // not be run.  Instead, they will be deleted.
-  //
-  // Deprecation note: Prefer SequenceLocalStorageSlot<std::unique_ptr<Foo>> to
-  // DestructionObserver to bind an object's lifetime to the current
-  // thread/sequence.
-  class BASE_EXPORT DestructionObserver {
-   public:
-    virtual void WillDestroyCurrentMessageLoop() = 0;
-
-   protected:
-    virtual ~DestructionObserver() = default;
-  };
-
-  // Add a DestructionObserver, which will start receiving notifications
-  // immediately.
-  void AddDestructionObserver(DestructionObserver* destruction_observer);
-
-  // Remove a DestructionObserver.  It is safe to call this method while a
-  // DestructionObserver is receiving a notification callback.
-  void RemoveDestructionObserver(DestructionObserver* destruction_observer);
-
-  // Forwards to MessageLoop::task_runner().
-  // DEPRECATED(https://crbug.com/616447): Use ThreadTaskRunnerHandle::Get()
-  // instead of MessageLoopCurrent::Get()->task_runner().
-  const scoped_refptr<SingleThreadTaskRunner>& task_runner() const;
-
-  // Forwards to MessageLoop::SetTaskRunner().
-  // DEPRECATED(https://crbug.com/825327): only owners of the MessageLoop
-  // instance should replace its TaskRunner.
-  void SetTaskRunner(scoped_refptr<SingleThreadTaskRunner> task_runner);
-
-  // A TaskObserver is an object that receives task notifications from the
-  // MessageLoop.
-  //
-  // NOTE: A TaskObserver implementation should be extremely fast!
-  class BASE_EXPORT TaskObserver {
-   public:
-    // This method is called before processing a task.
-    virtual void WillProcessTask(const PendingTask& pending_task) = 0;
-
-    // This method is called after processing a task.
-    virtual void DidProcessTask(const PendingTask& pending_task) = 0;
-
-   protected:
-    virtual ~TaskObserver() = default;
-  };
-
-  // Forwards to MessageLoop::(Add|Remove)TaskObserver.
-  // DEPRECATED(https://crbug.com/825327): only owners of the MessageLoop
-  // instance should add task observers on it.
-  void AddTaskObserver(TaskObserver* task_observer);
-  void RemoveTaskObserver(TaskObserver* task_observer);
-
-  // Enables or disables the recursive task processing. This happens in the case
-  // of recursive message loops. Some unwanted message loops may occur when
-  // using common controls or printer functions. By default, recursive task
-  // processing is disabled.
-  //
-  // Please use |ScopedNestableTaskAllower| instead of calling these methods
-  // directly.  In general, nestable message loops are to be avoided.  They are
-  // dangerous and difficult to get right, so please use with extreme caution.
-  //
-  // The specific case where tasks get queued is:
-  // - The thread is running a message loop.
-  // - It receives a task #1 and executes it.
-  // - The task #1 implicitly starts a message loop, like a MessageBox in the
-  //   unit test. This can also be StartDoc or GetSaveFileName.
-  // - The thread receives a task #2 before or while in this second message
-  //   loop.
-  // - With NestableTasksAllowed set to true, the task #2 will run right away.
-  //   Otherwise, it will get executed right after task #1 completes at "thread
-  //   message loop level".
-  //
-  // DEPRECATED(https://crbug.com/750779): Use RunLoop::Type on the relevant
-  // RunLoop instead of these methods.
-  // TODO(gab): Migrate usage and delete these methods.
-  void SetNestableTasksAllowed(bool allowed);
-  bool NestableTasksAllowed() const;
-
-  // Enables nestable tasks on the current MessageLoop while in scope.
-  // DEPRECATED(https://crbug.com/750779): This should not be used when the
-  // nested loop is driven by RunLoop (use RunLoop::Type::kNestableTasksAllowed
-  // instead). It can however still be useful in a few scenarios where re-
-  // entrancy is caused by a native message loop.
-  // TODO(gab): Remove usage of this class alongside RunLoop and rename it to
-  // ScopedApplicationTasksAllowedInNativeNestedLoop(?) for remaining use cases.
-  class BASE_EXPORT ScopedNestableTaskAllower {
-   public:
-    ScopedNestableTaskAllower();
-    ~ScopedNestableTaskAllower();
-
-   private:
-    MessageLoop* const loop_;
-    const bool old_state_;
-  };
-
-  // Returns true if the message loop is idle (ignoring delayed tasks). This is
-  // the same condition which triggers DoWork() to return false: i.e.
-  // out of tasks which can be processed at the current run-level -- there might
-  // be deferred non-nestable tasks remaining if currently in a nested run
-  // level.
-  bool IsIdleForTesting();
-
-  // Binds |current| to the current thread. It will from then on be the
-  // MessageLoop driven by MessageLoopCurrent on this thread. This is only meant
-  // to be invoked by the MessageLoop itself.
-  static void BindToCurrentThreadInternal(MessageLoop* current);
-
-  // Unbinds |current| from the current thread. Must be invoked on the same
-  // thread that invoked |BindToCurrentThreadInternal(current)|. This is only
-  // meant to be invoked by the MessageLoop itself.
-  static void UnbindFromCurrentThreadInternal(MessageLoop* current);
-
-  // Returns true if |message_loop| is bound to MessageLoopCurrent on the
-  // current thread. This is only meant to be invoked by the MessageLoop itself.
-  static bool IsBoundToCurrentThreadInternal(MessageLoop* message_loop);
-
- protected:
-  explicit MessageLoopCurrent(MessageLoop* current) : current_(current) {}
-
-  MessageLoop* const current_;
-};
-
-#if !defined(OS_NACL)
-
-// ForUI extension of MessageLoopCurrent.
-class BASE_EXPORT MessageLoopCurrentForUI : public MessageLoopCurrent {
- public:
-  // Returns an interface for the MessageLoopForUI of the current thread.
-  // Asserts that IsSet().
-  static MessageLoopCurrentForUI Get();
-
-  // Returns true if the current thread is running a MessageLoopForUI.
-  static bool IsSet();
-
-  MessageLoopCurrentForUI* operator->() { return this; }
-
-#if defined(USE_OZONE) && !defined(OS_FUCHSIA) && !defined(OS_WIN)
-  // Please see MessagePumpLibevent for definition.
-  static_assert(std::is_same<MessagePumpForUI, MessagePumpLibevent>::value,
-                "MessageLoopCurrentForUI::WatchFileDescriptor is not supported "
-                "when MessagePumpForUI is not a MessagePumpLibevent.");
-  bool WatchFileDescriptor(int fd,
-                           bool persistent,
-                           MessagePumpForUI::Mode mode,
-                           MessagePumpForUI::FdWatchController* controller,
-                           MessagePumpForUI::FdWatcher* delegate);
-#endif
-
-#if defined(OS_IOS)
-  // Forwards to MessageLoopForUI::Attach().
-  // TODO(https://crbug.com/825327): Plumb the actual MessageLoopForUI* to
-  // callers and remove ability to access this method from
-  // MessageLoopCurrentForUI.
-  void Attach();
-#endif
-
-#if defined(OS_ANDROID)
-  // Forwards to MessageLoopForUI::Start().
-  // TODO(https://crbug.com/825327): Plumb the actual MessageLoopForUI* to
-  // callers and remove ability to access this method from
-  // MessageLoopCurrentForUI.
-  void Start();
-
-  // Forwards to MessageLoopForUI::Abort().
-  // TODO(https://crbug.com/825327): Plumb the actual MessageLoopForUI* to
-  // callers and remove ability to access this method from
-  // MessageLoopCurrentForUI.
-  void Abort();
-#endif
-
- private:
-  MessageLoopCurrentForUI(MessageLoop* current, MessagePumpForUI* pump)
-      : MessageLoopCurrent(current), pump_(pump) {
-    DCHECK(pump_);
-  }
-
-  MessagePumpForUI* const pump_;
-};
-
-#endif  // !defined(OS_NACL)
-
-// ForIO extension of MessageLoopCurrent.
-class BASE_EXPORT MessageLoopCurrentForIO : public MessageLoopCurrent {
- public:
-  // Returns an interface for the MessageLoopForIO of the current thread.
-  // Asserts that IsSet().
-  static MessageLoopCurrentForIO Get();
-
-  // Returns true if the current thread is running a MessageLoopForIO.
-  static bool IsSet();
-
-  MessageLoopCurrentForIO* operator->() { return this; }
-
-#if !defined(OS_NACL_SFI)
-
-#if defined(OS_WIN)
-  // Please see MessagePumpWin for definitions of these methods.
-  void RegisterIOHandler(HANDLE file, MessagePumpForIO::IOHandler* handler);
-  bool RegisterJobObject(HANDLE job, MessagePumpForIO::IOHandler* handler);
-  bool WaitForIOCompletion(DWORD timeout, MessagePumpForIO::IOHandler* filter);
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
-  // Please see WatchableIOMessagePumpPosix for definition.
-  // Prefer base::FileDescriptorWatcher for non-critical IO.
-  bool WatchFileDescriptor(int fd,
-                           bool persistent,
-                           MessagePumpForIO::Mode mode,
-                           MessagePumpForIO::FdWatchController* controller,
-                           MessagePumpForIO::FdWatcher* delegate);
-#endif  // defined(OS_WIN)
-
-#if defined(OS_FUCHSIA)
-  // Additional watch API for native platform resources.
-  bool WatchZxHandle(zx_handle_t handle,
-                     bool persistent,
-                     zx_signals_t signals,
-                     MessagePumpForIO::ZxHandleWatchController* controller,
-                     MessagePumpForIO::ZxHandleWatcher* delegate);
-#endif  // defined(OS_FUCHSIA)
-
-#endif  // !defined(OS_NACL_SFI)
-
- private:
-  MessageLoopCurrentForIO(MessageLoop* current, MessagePumpForIO* pump)
-      : MessageLoopCurrent(current), pump_(pump) {
-    DCHECK(pump_);
-  }
-
-  MessagePumpForIO* const pump_;
-};
-
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_MESSAGE_LOOP_CURRENT_H_
diff --git a/base/message_loop/message_loop_perftest.cc b/base/message_loop/message_loop_perftest.cc
deleted file mode 100644
index 867e8fe..0000000
--- a/base/message_loop/message_loop_perftest.cc
+++ /dev/null
@@ -1,254 +0,0 @@
-// Copyright 2017 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 <memory>
-#include <vector>
-
-#include "base/atomicops.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/message_loop/message_loop.h"
-#include "base/run_loop.h"
-#include "base/strings/stringprintf.h"
-#include "base/synchronization/atomic_flag.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/threading/platform_thread.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-#include "base/time/time.h"
-#include "testing/gtest/include/gtest/gtest.h"
-#include "testing/perf/perf_test.h"
-
-namespace base {
-
-namespace {
-
-// A thread that waits for the caller to signal an event before proceeding to
-// call Action::Run().
-class PostingThread {
- public:
-  class Action {
-   public:
-    virtual ~Action() = default;
-
-    // Called after the thread is started and |start_event_| is signalled.
-    virtual void Run() = 0;
-
-   protected:
-    Action() = default;
-
-   private:
-    DISALLOW_COPY_AND_ASSIGN(Action);
-  };
-
-  // Creates a PostingThread where the thread waits on |start_event| before
-  // calling action->Run(). If a thread is returned, the thread is guaranteed to
-  // be allocated and running and the caller must call Join() before destroying
-  // the PostingThread.
-  static std::unique_ptr<PostingThread> Create(WaitableEvent* start_event,
-                                               std::unique_ptr<Action> action) {
-    auto posting_thread =
-        WrapUnique(new PostingThread(start_event, std::move(action)));
-
-    if (!posting_thread->Start())
-      return nullptr;
-
-    return posting_thread;
-  }
-
-  ~PostingThread() { DCHECK_EQ(!thread_handle_.is_null(), join_called_); }
-
-  void Join() {
-    PlatformThread::Join(thread_handle_);
-    join_called_ = true;
-  }
-
- private:
-  class Delegate final : public PlatformThread::Delegate {
-   public:
-    Delegate(PostingThread* outer, std::unique_ptr<Action> action)
-        : outer_(outer), action_(std::move(action)) {
-      DCHECK(outer_);
-      DCHECK(action_);
-    }
-
-    ~Delegate() override = default;
-
-   private:
-    void ThreadMain() override {
-      outer_->thread_started_.Signal();
-      outer_->start_event_->Wait();
-      action_->Run();
-    }
-
-    PostingThread* const outer_;
-    const std::unique_ptr<Action> action_;
-
-    DISALLOW_COPY_AND_ASSIGN(Delegate);
-  };
-
-  PostingThread(WaitableEvent* start_event, std::unique_ptr<Action> delegate)
-      : start_event_(start_event),
-        thread_started_(WaitableEvent::ResetPolicy::MANUAL,
-                        WaitableEvent::InitialState::NOT_SIGNALED),
-        delegate_(this, std::move(delegate)) {
-    DCHECK(start_event_);
-  }
-
-  bool Start() {
-    bool thread_created =
-        PlatformThread::Create(0, &delegate_, &thread_handle_);
-    if (thread_created)
-      thread_started_.Wait();
-
-    return thread_created;
-  }
-
-  bool join_called_ = false;
-  WaitableEvent* const start_event_;
-  WaitableEvent thread_started_;
-  Delegate delegate_;
-
-  PlatformThreadHandle thread_handle_;
-
-  DISALLOW_COPY_AND_ASSIGN(PostingThread);
-};
-
-class MessageLoopPerfTest : public ::testing::TestWithParam<int> {
- public:
-  MessageLoopPerfTest()
-      : message_loop_task_runner_(SequencedTaskRunnerHandle::Get()),
-        run_posting_threads_(WaitableEvent::ResetPolicy::MANUAL,
-                             WaitableEvent::InitialState::NOT_SIGNALED) {}
-
-  static std::string ParamInfoToString(
-      ::testing::TestParamInfo<int> param_info) {
-    return PostingThreadCountToString(param_info.param);
-  }
-
-  static std::string PostingThreadCountToString(int posting_threads) {
-    // Special case 1 thread for thread vs threads.
-    if (posting_threads == 1)
-      return "1_Posting_Thread";
-
-    return StringPrintf("%d_Posting_Threads", posting_threads);
-  }
-
- protected:
-  class ContinuouslyPostTasks final : public PostingThread::Action {
-   public:
-    ContinuouslyPostTasks(MessageLoopPerfTest* outer) : outer_(outer) {
-      DCHECK(outer_);
-    }
-    ~ContinuouslyPostTasks() override = default;
-
-   private:
-    void Run() override {
-      RepeatingClosure task_to_run =
-          BindRepeating([](size_t* num_tasks_run) { ++*num_tasks_run; },
-                        &outer_->num_tasks_run_);
-      while (!outer_->stop_posting_threads_.IsSet()) {
-        outer_->message_loop_task_runner_->PostTask(FROM_HERE, task_to_run);
-        subtle::NoBarrier_AtomicIncrement(&outer_->num_tasks_posted_, 1);
-      }
-    }
-
-    MessageLoopPerfTest* const outer_;
-
-    DISALLOW_COPY_AND_ASSIGN(ContinuouslyPostTasks);
-  };
-
-  void SetUp() override {
-    // This check is here because we can't ASSERT_TRUE in the constructor.
-    ASSERT_TRUE(message_loop_task_runner_);
-  }
-
-  // Runs ActionType::Run() on |num_posting_threads| and requests test
-  // termination around |duration|.
-  template <typename ActionType>
-  void RunTest(const int num_posting_threads, TimeDelta duration) {
-    std::vector<std::unique_ptr<PostingThread>> threads;
-    for (int i = 0; i < num_posting_threads; ++i) {
-      threads.emplace_back(PostingThread::Create(
-          &run_posting_threads_, std::make_unique<ActionType>(this)));
-      // Don't assert here to simplify the code that requires a Join() call for
-      // every created PostingThread.
-      EXPECT_TRUE(threads[i]);
-    }
-
-    RunLoop run_loop;
-    message_loop_task_runner_->PostDelayedTask(
-        FROM_HERE,
-        BindOnce(
-            [](RunLoop* run_loop, AtomicFlag* stop_posting_threads) {
-              stop_posting_threads->Set();
-              run_loop->Quit();
-            },
-            &run_loop, &stop_posting_threads_),
-        duration);
-
-    TimeTicks post_task_start = TimeTicks::Now();
-    run_posting_threads_.Signal();
-
-    TimeTicks run_loop_start = TimeTicks::Now();
-    run_loop.Run();
-    tasks_run_duration_ = TimeTicks::Now() - run_loop_start;
-
-    for (auto& thread : threads)
-      thread->Join();
-
-    tasks_posted_duration_ = TimeTicks::Now() - post_task_start;
-  }
-
-  size_t num_tasks_posted() const {
-    return subtle::NoBarrier_Load(&num_tasks_posted_);
-  }
-
-  TimeDelta tasks_posted_duration() const { return tasks_posted_duration_; }
-
-  size_t num_tasks_run() const { return num_tasks_run_; }
-
-  TimeDelta tasks_run_duration() const { return tasks_run_duration_; }
-
- private:
-  MessageLoop message_loop_;
-
-  // Accessed on multiple threads, thread-safe or constant:
-  const scoped_refptr<SequencedTaskRunner> message_loop_task_runner_;
-  WaitableEvent run_posting_threads_;
-  AtomicFlag stop_posting_threads_;
-  subtle::AtomicWord num_tasks_posted_ = 0;
-
-  // Accessed only on the test case thread:
-  TimeDelta tasks_posted_duration_;
-  TimeDelta tasks_run_duration_;
-  size_t num_tasks_run_ = 0;
-
-  DISALLOW_COPY_AND_ASSIGN(MessageLoopPerfTest);
-};
-
-}  // namespace
-
-TEST_P(MessageLoopPerfTest, PostTaskRate) {
-  // Measures the average rate of posting tasks from different threads and the
-  // average rate that the message loop is running those tasks.
-  RunTest<ContinuouslyPostTasks>(GetParam(), TimeDelta::FromSeconds(3));
-  perf_test::PrintResult("task_posting", "",
-                         PostingThreadCountToString(GetParam()),
-                         tasks_posted_duration().InMicroseconds() /
-                             static_cast<double>(num_tasks_posted()),
-                         "us/task", true);
-  perf_test::PrintResult("task_running", "",
-                         PostingThreadCountToString(GetParam()),
-                         tasks_run_duration().InMicroseconds() /
-                             static_cast<double>(num_tasks_run()),
-                         "us/task", true);
-}
-
-INSTANTIATE_TEST_CASE_P(,
-                        MessageLoopPerfTest,
-                        ::testing::Values(1, 5, 10),
-                        MessageLoopPerfTest::ParamInfoToString);
-}  // namespace base
diff --git a/base/message_loop/message_loop_task_runner.cc b/base/message_loop/message_loop_task_runner.cc
deleted file mode 100644
index f251e3b..0000000
--- a/base/message_loop/message_loop_task_runner.cc
+++ /dev/null
@@ -1,53 +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 "base/message_loop/message_loop_task_runner.h"
-
-#include <utility>
-
-#include "base/location.h"
-#include "base/logging.h"
-#include "base/message_loop/incoming_task_queue.h"
-
-namespace base {
-namespace internal {
-
-MessageLoopTaskRunner::MessageLoopTaskRunner(
-    scoped_refptr<IncomingTaskQueue> incoming_queue)
-    : incoming_queue_(incoming_queue), valid_thread_id_(kInvalidThreadId) {
-}
-
-void MessageLoopTaskRunner::BindToCurrentThread() {
-  AutoLock lock(valid_thread_id_lock_);
-  DCHECK_EQ(kInvalidThreadId, valid_thread_id_);
-  valid_thread_id_ = PlatformThread::CurrentId();
-}
-
-bool MessageLoopTaskRunner::PostDelayedTask(const Location& from_here,
-                                            OnceClosure task,
-                                            base::TimeDelta delay) {
-  DCHECK(!task.is_null()) << from_here.ToString();
-  return incoming_queue_->AddToIncomingQueue(from_here, std::move(task), delay,
-                                             Nestable::kNestable);
-}
-
-bool MessageLoopTaskRunner::PostNonNestableDelayedTask(
-    const Location& from_here,
-    OnceClosure task,
-    base::TimeDelta delay) {
-  DCHECK(!task.is_null()) << from_here.ToString();
-  return incoming_queue_->AddToIncomingQueue(from_here, std::move(task), delay,
-                                             Nestable::kNonNestable);
-}
-
-bool MessageLoopTaskRunner::RunsTasksInCurrentSequence() const {
-  AutoLock lock(valid_thread_id_lock_);
-  return valid_thread_id_ == PlatformThread::CurrentId();
-}
-
-MessageLoopTaskRunner::~MessageLoopTaskRunner() = default;
-
-}  // namespace internal
-
-}  // namespace base
diff --git a/base/message_loop/message_loop_task_runner.h b/base/message_loop/message_loop_task_runner.h
deleted file mode 100644
index c7d48c2..0000000
--- a/base/message_loop/message_loop_task_runner.h
+++ /dev/null
@@ -1,60 +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_MESSAGE_LOOP_MESSAGE_LOOP_TASK_RUNNER_H_
-#define BASE_MESSAGE_LOOP_MESSAGE_LOOP_TASK_RUNNER_H_
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/pending_task.h"
-#include "base/single_thread_task_runner.h"
-#include "base/synchronization/lock.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-namespace internal {
-
-class IncomingTaskQueue;
-
-// A stock implementation of SingleThreadTaskRunner that is created and managed
-// by a MessageLoop. For now a MessageLoopTaskRunner can only be created as
-// part of a MessageLoop.
-class BASE_EXPORT MessageLoopTaskRunner : public SingleThreadTaskRunner {
- public:
-  explicit MessageLoopTaskRunner(
-      scoped_refptr<IncomingTaskQueue> incoming_queue);
-
-  // Initialize this message loop task runner on the current thread.
-  void BindToCurrentThread();
-
-  // SingleThreadTaskRunner implementation
-  bool PostDelayedTask(const Location& from_here,
-                       OnceClosure task,
-                       TimeDelta delay) override;
-  bool PostNonNestableDelayedTask(const Location& from_here,
-                                  OnceClosure task,
-                                  TimeDelta delay) override;
-  bool RunsTasksInCurrentSequence() const override;
-
- private:
-  friend class RefCountedThreadSafe<MessageLoopTaskRunner>;
-  ~MessageLoopTaskRunner() override;
-
-  // The incoming queue receiving all posted tasks.
-  scoped_refptr<IncomingTaskQueue> incoming_queue_;
-
-  // ID of the thread |this| was created on.  Could be accessed on multiple
-  // threads, protected by |valid_thread_id_lock_|.
-  PlatformThreadId valid_thread_id_;
-  mutable Lock valid_thread_id_lock_;
-
-  DISALLOW_COPY_AND_ASSIGN(MessageLoopTaskRunner);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_MESSAGE_LOOP_TASK_RUNNER_H_
diff --git a/base/message_loop/message_pump.cc b/base/message_loop/message_pump.cc
deleted file mode 100644
index 9076176..0000000
--- a/base/message_loop/message_pump.cc
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright (c) 2010 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/message_loop/message_pump.h"
-
-namespace base {
-
-MessagePump::MessagePump() = default;
-
-MessagePump::~MessagePump() = default;
-
-void MessagePump::SetTimerSlack(TimerSlack) {
-}
-
-}  // namespace base
diff --git a/base/message_loop/message_pump.h b/base/message_loop/message_pump.h
deleted file mode 100644
index dec0c94..0000000
--- a/base/message_loop/message_pump.h
+++ /dev/null
@@ -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_MESSAGE_LOOP_MESSAGE_PUMP_H_
-#define BASE_MESSAGE_LOOP_MESSAGE_PUMP_H_
-
-#include "base/base_export.h"
-#include "base/message_loop/timer_slack.h"
-#include "base/sequence_checker.h"
-
-namespace base {
-
-class TimeTicks;
-
-class BASE_EXPORT MessagePump {
- public:
-  // Please see the comments above the Run method for an illustration of how
-  // these delegate methods are used.
-  class BASE_EXPORT Delegate {
-   public:
-    virtual ~Delegate() = default;
-
-    // Called from within Run in response to ScheduleWork or when the message
-    // pump would otherwise call DoDelayedWork.  Returns true to indicate that
-    // work was done.  DoDelayedWork will still be called if DoWork returns
-    // true, but DoIdleWork will not.
-    virtual bool DoWork() = 0;
-
-    // Called from within Run in response to ScheduleDelayedWork or when the
-    // message pump would otherwise sleep waiting for more work.  Returns true
-    // to indicate that delayed work was done.  DoIdleWork will not be called
-    // if DoDelayedWork returns true.  Upon return |next_delayed_work_time|
-    // indicates the time when DoDelayedWork should be called again.  If
-    // |next_delayed_work_time| is null (per Time::is_null), then the queue of
-    // future delayed work (timer events) is currently empty, and no additional
-    // calls to this function need to be scheduled.
-    virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) = 0;
-
-    // Called from within Run just before the message pump goes to sleep.
-    // Returns true to indicate that idle work was done. Returning false means
-    // the pump will now wait.
-    virtual bool DoIdleWork() = 0;
-  };
-
-  MessagePump();
-  virtual ~MessagePump();
-
-  // The Run method is called to enter the message pump's run loop.
-  //
-  // Within the method, the message pump is responsible for processing native
-  // messages as well as for giving cycles to the delegate periodically.  The
-  // message pump should take care to mix delegate callbacks with native
-  // message processing so neither type of event starves the other of cycles.
-  //
-  // The anatomy of a typical run loop:
-  //
-  //   for (;;) {
-  //     bool did_work = DoInternalWork();
-  //     if (should_quit_)
-  //       break;
-  //
-  //     did_work |= delegate_->DoWork();
-  //     if (should_quit_)
-  //       break;
-  //
-  //     TimeTicks next_time;
-  //     did_work |= delegate_->DoDelayedWork(&next_time);
-  //     if (should_quit_)
-  //       break;
-  //
-  //     if (did_work)
-  //       continue;
-  //
-  //     did_work = delegate_->DoIdleWork();
-  //     if (should_quit_)
-  //       break;
-  //
-  //     if (did_work)
-  //       continue;
-  //
-  //     WaitForWork();
-  //   }
-  //
-  // Here, DoInternalWork is some private method of the message pump that is
-  // responsible for dispatching the next UI message or notifying the next IO
-  // completion (for example).  WaitForWork is a private method that simply
-  // blocks until there is more work of any type to do.
-  //
-  // Notice that the run loop cycles between calling DoInternalWork, DoWork,
-  // and DoDelayedWork methods.  This helps ensure that none of these work
-  // queues starve the others.  This is important for message pumps that are
-  // used to drive animations, for example.
-  //
-  // Notice also that after each callout to foreign code, the run loop checks
-  // to see if it should quit.  The Quit method is responsible for setting this
-  // flag.  No further work is done once the quit flag is set.
-  //
-  // NOTE: Care must be taken to handle Run being called again from within any
-  // of the callouts to foreign code.  Native message pumps may also need to
-  // deal with other native message pumps being run outside their control
-  // (e.g., the MessageBox API on Windows pumps UI messages!).  To be specific,
-  // the callouts (DoWork and DoDelayedWork) MUST still be provided even in
-  // nested sub-loops that are "seemingly" outside the control of this message
-  // pump.  DoWork in particular must never be starved for time slices unless
-  // it returns false (meaning it has run out of things to do).
-  //
-  virtual void Run(Delegate* delegate) = 0;
-
-  // Quit immediately from the most recently entered run loop.  This method may
-  // only be used on the thread that called Run.
-  virtual void Quit() = 0;
-
-  // Schedule a DoWork callback to happen reasonably soon.  Does nothing if a
-  // DoWork callback is already scheduled.  This method may be called from any
-  // thread.  Once this call is made, DoWork should not be "starved" at least
-  // until it returns a value of false.
-  virtual void ScheduleWork() = 0;
-
-  // Schedule a DoDelayedWork callback to happen at the specified time,
-  // cancelling any pending DoDelayedWork callback.  This method may only be
-  // used on the thread that called Run.
-  virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time) = 0;
-
-  // Sets the timer slack to the specified value.
-  virtual void SetTimerSlack(TimerSlack timer_slack);
-};
-
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_MESSAGE_PUMP_H_
diff --git a/base/message_loop/message_pump_default.cc b/base/message_loop/message_pump_default.cc
deleted file mode 100644
index bca1e60..0000000
--- a/base/message_loop/message_pump_default.cc
+++ /dev/null
@@ -1,101 +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.
-
-#include "base/message_loop/message_pump_default.h"
-
-#include "base/auto_reset.h"
-#include "base/logging.h"
-#include "base/threading/thread_restrictions.h"
-#include "build_config.h"
-
-#if defined(OS_MACOSX)
-#include <mach/thread_policy.h>
-
-#include "base/mac/mach_logging.h"
-#include "base/mac/scoped_mach_port.h"
-#include "base/mac/scoped_nsautorelease_pool.h"
-#endif
-
-namespace base {
-
-MessagePumpDefault::MessagePumpDefault()
-    : keep_running_(true),
-      event_(WaitableEvent::ResetPolicy::AUTOMATIC,
-             WaitableEvent::InitialState::NOT_SIGNALED) {}
-
-MessagePumpDefault::~MessagePumpDefault() = default;
-
-void MessagePumpDefault::Run(Delegate* delegate) {
-  AutoReset<bool> auto_reset_keep_running(&keep_running_, true);
-
-  for (;;) {
-#if defined(OS_MACOSX)
-    mac::ScopedNSAutoreleasePool autorelease_pool;
-#endif
-
-    bool did_work = delegate->DoWork();
-    if (!keep_running_)
-      break;
-
-    did_work |= delegate->DoDelayedWork(&delayed_work_time_);
-    if (!keep_running_)
-      break;
-
-    if (did_work)
-      continue;
-
-    did_work = delegate->DoIdleWork();
-    if (!keep_running_)
-      break;
-
-    if (did_work)
-      continue;
-
-    ThreadRestrictions::ScopedAllowWait allow_wait;
-    if (delayed_work_time_.is_null()) {
-      event_.Wait();
-    } else {
-      // No need to handle already expired |delayed_work_time_| in any special
-      // way. When |delayed_work_time_| is in the past TimeWaitUntil returns
-      // promptly and |delayed_work_time_| will re-initialized on a next
-      // DoDelayedWork call which has to be called in order to get here again.
-      event_.TimedWaitUntil(delayed_work_time_);
-    }
-    // Since event_ is auto-reset, we don't need to do anything special here
-    // other than service each delegate method.
-  }
-}
-
-void MessagePumpDefault::Quit() {
-  keep_running_ = false;
-}
-
-void MessagePumpDefault::ScheduleWork() {
-  // Since this can be called on any thread, we need to ensure that our Run
-  // loop wakes up.
-  event_.Signal();
-}
-
-void MessagePumpDefault::ScheduleDelayedWork(
-    const TimeTicks& delayed_work_time) {
-  // We know that we can't be blocked on Wait right now since this method can
-  // only be called on the same thread as Run, so we only need to update our
-  // record of how long to sleep when we do sleep.
-  delayed_work_time_ = delayed_work_time;
-}
-
-#if defined(OS_MACOSX)
-void MessagePumpDefault::SetTimerSlack(TimerSlack timer_slack) {
-  thread_latency_qos_policy_data_t policy{};
-  policy.thread_latency_qos_tier = timer_slack == TIMER_SLACK_MAXIMUM
-                                       ? LATENCY_QOS_TIER_3
-                                       : LATENCY_QOS_TIER_UNSPECIFIED;
-  mac::ScopedMachSendRight thread_port(mach_thread_self());
-  thread_policy_set(thread_port.get(), THREAD_LATENCY_QOS_POLICY,
-                    reinterpret_cast<thread_policy_t>(&policy),
-                    THREAD_LATENCY_QOS_POLICY_COUNT);
-}
-#endif
-
-}  // namespace base
diff --git a/base/message_loop/message_pump_default.h b/base/message_loop/message_pump_default.h
deleted file mode 100644
index f92d2e4..0000000
--- a/base/message_loop/message_pump_default.h
+++ /dev/null
@@ -1,46 +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_MESSAGE_LOOP_MESSAGE_PUMP_DEFAULT_H_
-#define BASE_MESSAGE_LOOP_MESSAGE_PUMP_DEFAULT_H_
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/message_loop/message_pump.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/time/time.h"
-#include "build_config.h"
-
-namespace base {
-
-class BASE_EXPORT MessagePumpDefault : public MessagePump {
- public:
-  MessagePumpDefault();
-  ~MessagePumpDefault() override;
-
-  // MessagePump methods:
-  void Run(Delegate* delegate) override;
-  void Quit() override;
-  void ScheduleWork() override;
-  void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
-#if defined(OS_MACOSX)
-  void SetTimerSlack(TimerSlack timer_slack) override;
-#endif
-
- private:
-  // This flag is set to false when Run should return.
-  bool keep_running_;
-
-  // Used to sleep until there is more work to do.
-  WaitableEvent event_;
-
-  // The time at which we should call DoDelayedWork.
-  TimeTicks delayed_work_time_;
-
-  DISALLOW_COPY_AND_ASSIGN(MessagePumpDefault);
-};
-
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_MESSAGE_PUMP_DEFAULT_H_
diff --git a/base/message_loop/message_pump_for_io.h b/base/message_loop/message_pump_for_io.h
deleted file mode 100644
index 39a972e..0000000
--- a/base/message_loop/message_pump_for_io.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2018 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_MESSAGE_LOOP_MESSAGE_PUMP_FOR_IO_H_
-#define BASE_MESSAGE_LOOP_MESSAGE_PUMP_FOR_IO_H_
-
-// This header is a forwarding header to coalesce the various platform specific
-// types representing MessagePumpForIO.
-
-#include "build_config.h"
-
-#if defined(OS_WIN)
-#include "base/message_loop/message_pump_win.h"
-#elif defined(OS_IOS)
-#include "base/message_loop/message_pump_io_ios.h"
-#elif defined(OS_NACL_SFI)
-#include "base/message_loop/message_pump_default.h"
-#elif defined(OS_FUCHSIA)
-#include "base/message_loop/message_pump_fuchsia.h"
-#elif defined(OS_POSIX)
-#include "base/message_loop/message_pump_libevent.h"
-#endif
-
-namespace base {
-
-#if defined(OS_WIN)
-// Windows defines it as-is.
-using MessagePumpForIO = MessagePumpForIO;
-#elif defined(OS_IOS)
-using MessagePumpForIO = MessagePumpIOSForIO;
-#elif defined(OS_NACL_SFI)
-using MessagePumpForIO = MessagePumpDefault;
-#elif defined(OS_FUCHSIA)
-using MessagePumpForIO = MessagePumpFuchsia;
-#elif defined(OS_POSIX)
-using MessagePumpForIO = MessagePumpLibevent;
-#else
-#error Platform does not define MessagePumpForIO
-#endif
-
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_MESSAGE_PUMP_FOR_IO_H_
diff --git a/base/message_loop/message_pump_for_ui.h b/base/message_loop/message_pump_for_ui.h
deleted file mode 100644
index 620c2ae..0000000
--- a/base/message_loop/message_pump_for_ui.h
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright 2018 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_MESSAGE_LOOP_MESSAGE_PUMP_FOR_UI_H_
-#define BASE_MESSAGE_LOOP_MESSAGE_PUMP_FOR_UI_H_
-
-// This header is a forwarding header to coalesce the various platform specific
-// implementations of MessagePumpForUI.
-
-#include "build_config.h"
-
-#if defined(OS_WIN)
-#include "base/message_loop/message_pump_win.h"
-#elif defined(OS_ANDROID)
-#include "base/message_loop/message_pump_android.h"
-#elif defined(OS_MACOSX)
-#include "base/message_loop/message_pump.h"
-#elif defined(OS_NACL) || defined(OS_AIX)
-// No MessagePumpForUI, see below.
-#elif defined(USE_GLIB)
-#include "base/message_loop/message_pump_glib.h"
-#elif defined(OS_LINUX) || defined(OS_BSD)
-#include "base/message_loop/message_pump_libevent.h"
-#elif defined(OS_FUCHSIA)
-#include "base/message_loop/message_pump_fuchsia.h"
-#endif
-
-namespace base {
-
-#if defined(OS_WIN)
-// Windows defines it as-is.
-using MessagePumpForUI = MessagePumpForUI;
-#elif defined(OS_ANDROID)
-// Android defines it as-is.
-using MessagePumpForUI = MessagePumpForUI;
-#elif defined(OS_MACOSX)
-// MessagePumpForUI isn't bound to a specific impl on Mac. While each impl can
-// be represented by a plain MessagePump: MessagePumpMac::Create() must be used
-// to instantiate the right impl.
-using MessagePumpForUI = MessagePump;
-#elif defined(OS_NACL) || defined(OS_AIX)
-// Currently NaCl and AIX don't have a MessagePumpForUI.
-// TODO(abarth): Figure out if we need this.
-#elif defined(USE_GLIB)
-using MessagePumpForUI = MessagePumpGlib;
-#elif defined(OS_LINUX) || defined(OS_BSD)
-using MessagePumpForUI = MessagePumpLibevent;
-#elif defined(OS_FUCHSIA)
-using MessagePumpForUI = MessagePumpFuchsia;
-#else
-#error Platform does not define MessagePumpForUI
-#endif
-
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_MESSAGE_PUMP_FOR_UI_H_
diff --git a/base/message_loop/message_pump_glib.cc b/base/message_loop/message_pump_glib.cc
deleted file mode 100644
index 2f1909b..0000000
--- a/base/message_loop/message_pump_glib.cc
+++ /dev/null
@@ -1,359 +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 "base/message_loop/message_pump_glib.h"
-
-#include <fcntl.h>
-#include <math.h>
-
-#include <glib.h>
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/posix/eintr_wrapper.h"
-#include "base/synchronization/lock.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-
-namespace {
-
-// Return a timeout suitable for the glib loop, -1 to block forever,
-// 0 to return right away, or a timeout in milliseconds from now.
-int GetTimeIntervalMilliseconds(const TimeTicks& from) {
-  if (from.is_null())
-    return -1;
-
-  // Be careful here.  TimeDelta has a precision of microseconds, but we want a
-  // value in milliseconds.  If there are 5.5ms left, should the delay be 5 or
-  // 6?  It should be 6 to avoid executing delayed work too early.
-  int delay = static_cast<int>(
-      ceil((from - TimeTicks::Now()).InMillisecondsF()));
-
-  // If this value is negative, then we need to run delayed work soon.
-  return delay < 0 ? 0 : delay;
-}
-
-// A brief refresher on GLib:
-//     GLib sources have four callbacks: Prepare, Check, Dispatch and Finalize.
-// On each iteration of the GLib pump, it calls each source's Prepare function.
-// This function should return TRUE if it wants GLib to call its Dispatch, and
-// FALSE otherwise.  It can also set a timeout in this case for the next time
-// Prepare should be called again (it may be called sooner).
-//     After the Prepare calls, GLib does a poll to check for events from the
-// system.  File descriptors can be attached to the sources.  The poll may block
-// if none of the Prepare calls returned TRUE.  It will block indefinitely, or
-// by the minimum time returned by a source in Prepare.
-//     After the poll, GLib calls Check for each source that returned FALSE
-// from Prepare.  The return value of Check has the same meaning as for Prepare,
-// making Check a second chance to tell GLib we are ready for Dispatch.
-//     Finally, GLib calls Dispatch for each source that is ready.  If Dispatch
-// returns FALSE, GLib will destroy the source.  Dispatch calls may be recursive
-// (i.e., you can call Run from them), but Prepare and Check cannot.
-//     Finalize is called when the source is destroyed.
-// NOTE: It is common for subsystems to want to process pending events while
-// doing intensive work, for example the flash plugin. They usually use the
-// following pattern (recommended by the GTK docs):
-// while (gtk_events_pending()) {
-//   gtk_main_iteration();
-// }
-//
-// gtk_events_pending just calls g_main_context_pending, which does the
-// following:
-// - Call prepare on all the sources.
-// - Do the poll with a timeout of 0 (not blocking).
-// - Call check on all the sources.
-// - *Does not* call dispatch on the sources.
-// - Return true if any of prepare() or check() returned true.
-//
-// gtk_main_iteration just calls g_main_context_iteration, which does the whole
-// thing, respecting the timeout for the poll (and block, although it is
-// expected not to if gtk_events_pending returned true), and call dispatch.
-//
-// Thus it is important to only return true from prepare or check if we
-// actually have events or work to do. We also need to make sure we keep
-// internal state consistent so that if prepare/check return true when called
-// from gtk_events_pending, they will still return true when called right
-// after, from gtk_main_iteration.
-//
-// For the GLib pump we try to follow the Windows UI pump model:
-// - Whenever we receive a wakeup event or the timer for delayed work expires,
-// we run DoWork and/or DoDelayedWork. That part will also run in the other
-// event pumps.
-// - We also run DoWork, DoDelayedWork, and possibly DoIdleWork in the main
-// loop, around event handling.
-
-struct WorkSource : public GSource {
-  MessagePumpGlib* pump;
-};
-
-gboolean WorkSourcePrepare(GSource* source,
-                           gint* timeout_ms) {
-  *timeout_ms = static_cast<WorkSource*>(source)->pump->HandlePrepare();
-  // We always return FALSE, so that our timeout is honored.  If we were
-  // to return TRUE, the timeout would be considered to be 0 and the poll
-  // would never block.  Once the poll is finished, Check will be called.
-  return FALSE;
-}
-
-gboolean WorkSourceCheck(GSource* source) {
-  // Only return TRUE if Dispatch should be called.
-  return static_cast<WorkSource*>(source)->pump->HandleCheck();
-}
-
-gboolean WorkSourceDispatch(GSource* source,
-                            GSourceFunc unused_func,
-                            gpointer unused_data) {
-
-  static_cast<WorkSource*>(source)->pump->HandleDispatch();
-  // Always return TRUE so our source stays registered.
-  return TRUE;
-}
-
-// I wish these could be const, but g_source_new wants non-const.
-GSourceFuncs WorkSourceFuncs = {WorkSourcePrepare, WorkSourceCheck,
-                                WorkSourceDispatch, nullptr};
-
-// The following is used to make sure we only run the MessagePumpGlib on one
-// thread. X only has one message pump so we can only have one UI loop per
-// process.
-#ifndef NDEBUG
-
-// Tracks the pump the most recent pump that has been run.
-struct ThreadInfo {
-  // The pump.
-  MessagePumpGlib* pump;
-
-  // ID of the thread the pump was run on.
-  PlatformThreadId thread_id;
-};
-
-// Used for accesing |thread_info|.
-static LazyInstance<Lock>::Leaky thread_info_lock = LAZY_INSTANCE_INITIALIZER;
-
-// If non-NULL it means a MessagePumpGlib exists and has been Run. This is
-// destroyed when the MessagePump is destroyed.
-ThreadInfo* thread_info = NULL;
-
-void CheckThread(MessagePumpGlib* pump) {
-  AutoLock auto_lock(thread_info_lock.Get());
-  if (!thread_info) {
-    thread_info = new ThreadInfo;
-    thread_info->pump = pump;
-    thread_info->thread_id = PlatformThread::CurrentId();
-  }
-  DCHECK(thread_info->thread_id == PlatformThread::CurrentId()) <<
-      "Running MessagePumpGlib on two different threads; "
-      "this is unsupported by GLib!";
-}
-
-void PumpDestroyed(MessagePumpGlib* pump) {
-  AutoLock auto_lock(thread_info_lock.Get());
-  if (thread_info && thread_info->pump == pump) {
-    delete thread_info;
-    thread_info = NULL;
-  }
-}
-
-#endif
-
-}  // namespace
-
-struct MessagePumpGlib::RunState {
-  Delegate* delegate;
-
-  // Used to flag that the current Run() invocation should return ASAP.
-  bool should_quit;
-
-  // Used to count how many Run() invocations are on the stack.
-  int run_depth;
-
-  // This keeps the state of whether the pump got signaled that there was new
-  // work to be done. Since we eat the message on the wake up pipe as soon as
-  // we get it, we keep that state here to stay consistent.
-  bool has_work;
-};
-
-MessagePumpGlib::MessagePumpGlib()
-    : state_(nullptr),
-      context_(g_main_context_default()),
-      wakeup_gpollfd_(new GPollFD) {
-  // Create our wakeup pipe, which is used to flag when work was scheduled.
-  int fds[2];
-  int ret = pipe(fds);
-  DCHECK_EQ(ret, 0);
-  (void)ret;  // Prevent warning in release mode.
-
-  wakeup_pipe_read_  = fds[0];
-  wakeup_pipe_write_ = fds[1];
-  wakeup_gpollfd_->fd = wakeup_pipe_read_;
-  wakeup_gpollfd_->events = G_IO_IN;
-
-  work_source_ = g_source_new(&WorkSourceFuncs, sizeof(WorkSource));
-  static_cast<WorkSource*>(work_source_)->pump = this;
-  g_source_add_poll(work_source_, wakeup_gpollfd_.get());
-  // Use a low priority so that we let other events in the queue go first.
-  g_source_set_priority(work_source_, G_PRIORITY_DEFAULT_IDLE);
-  // This is needed to allow Run calls inside Dispatch.
-  g_source_set_can_recurse(work_source_, TRUE);
-  g_source_attach(work_source_, context_);
-}
-
-MessagePumpGlib::~MessagePumpGlib() {
-#ifndef NDEBUG
-  PumpDestroyed(this);
-#endif
-  g_source_destroy(work_source_);
-  g_source_unref(work_source_);
-  close(wakeup_pipe_read_);
-  close(wakeup_pipe_write_);
-}
-
-// Return the timeout we want passed to poll.
-int MessagePumpGlib::HandlePrepare() {
-  // We know we have work, but we haven't called HandleDispatch yet. Don't let
-  // the pump block so that we can do some processing.
-  if (state_ &&  // state_ may be null during tests.
-      state_->has_work)
-    return 0;
-
-  // We don't think we have work to do, but make sure not to block
-  // longer than the next time we need to run delayed work.
-  return GetTimeIntervalMilliseconds(delayed_work_time_);
-}
-
-bool MessagePumpGlib::HandleCheck() {
-  if (!state_)  // state_ may be null during tests.
-    return false;
-
-  // We usually have a single message on the wakeup pipe, since we are only
-  // signaled when the queue went from empty to non-empty, but there can be
-  // two messages if a task posted a task, hence we read at most two bytes.
-  // The glib poll will tell us whether there was data, so this read
-  // shouldn't block.
-  if (wakeup_gpollfd_->revents & G_IO_IN) {
-    char msg[2];
-    const int num_bytes = HANDLE_EINTR(read(wakeup_pipe_read_, msg, 2));
-    if (num_bytes < 1) {
-      NOTREACHED() << "Error reading from the wakeup pipe.";
-    }
-    DCHECK((num_bytes == 1 && msg[0] == '!') ||
-           (num_bytes == 2 && msg[0] == '!' && msg[1] == '!'));
-    // Since we ate the message, we need to record that we have more work,
-    // because HandleCheck() may be called without HandleDispatch being called
-    // afterwards.
-    state_->has_work = true;
-  }
-
-  if (state_->has_work)
-    return true;
-
-  if (GetTimeIntervalMilliseconds(delayed_work_time_) == 0) {
-    // The timer has expired. That condition will stay true until we process
-    // that delayed work, so we don't need to record this differently.
-    return true;
-  }
-
-  return false;
-}
-
-void MessagePumpGlib::HandleDispatch() {
-  state_->has_work = false;
-  if (state_->delegate->DoWork()) {
-    // NOTE: on Windows at this point we would call ScheduleWork (see
-    // MessagePumpGlib::HandleWorkMessage in message_pump_win.cc). But here,
-    // instead of posting a message on the wakeup pipe, we can avoid the
-    // syscalls and just signal that we have more work.
-    state_->has_work = true;
-  }
-
-  if (state_->should_quit)
-    return;
-
-  state_->delegate->DoDelayedWork(&delayed_work_time_);
-}
-
-void MessagePumpGlib::Run(Delegate* delegate) {
-#ifndef NDEBUG
-  CheckThread(this);
-#endif
-
-  RunState state;
-  state.delegate = delegate;
-  state.should_quit = false;
-  state.run_depth = state_ ? state_->run_depth + 1 : 1;
-  state.has_work = false;
-
-  RunState* previous_state = state_;
-  state_ = &state;
-
-  // We really only do a single task for each iteration of the loop.  If we
-  // have done something, assume there is likely something more to do.  This
-  // will mean that we don't block on the message pump until there was nothing
-  // more to do.  We also set this to true to make sure not to block on the
-  // first iteration of the loop, so RunUntilIdle() works correctly.
-  bool more_work_is_plausible = true;
-
-  // We run our own loop instead of using g_main_loop_quit in one of the
-  // callbacks.  This is so we only quit our own loops, and we don't quit
-  // nested loops run by others.  TODO(deanm): Is this what we want?
-  for (;;) {
-    // Don't block if we think we have more work to do.
-    bool block = !more_work_is_plausible;
-
-    more_work_is_plausible = g_main_context_iteration(context_, block);
-    if (state_->should_quit)
-      break;
-
-    more_work_is_plausible |= state_->delegate->DoWork();
-    if (state_->should_quit)
-      break;
-
-    more_work_is_plausible |=
-        state_->delegate->DoDelayedWork(&delayed_work_time_);
-    if (state_->should_quit)
-      break;
-
-    if (more_work_is_plausible)
-      continue;
-
-    more_work_is_plausible = state_->delegate->DoIdleWork();
-    if (state_->should_quit)
-      break;
-  }
-
-  state_ = previous_state;
-}
-
-void MessagePumpGlib::Quit() {
-  if (state_) {
-    state_->should_quit = true;
-  } else {
-    NOTREACHED() << "Quit called outside Run!";
-  }
-}
-
-void MessagePumpGlib::ScheduleWork() {
-  // This can be called on any thread, so we don't want to touch any state
-  // variables as we would then need locks all over.  This ensures that if
-  // we are sleeping in a poll that we will wake up.
-  char msg = '!';
-  if (HANDLE_EINTR(write(wakeup_pipe_write_, &msg, 1)) != 1) {
-    NOTREACHED() << "Could not write to the UI message loop wakeup pipe!";
-  }
-}
-
-void MessagePumpGlib::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
-  // We need to wake up the loop in case the poll timeout needs to be
-  // adjusted.  This will cause us to try to do work, but that's OK.
-  delayed_work_time_ = delayed_work_time;
-  ScheduleWork();
-}
-
-bool MessagePumpGlib::ShouldQuit() const {
-  CHECK(state_);
-  return state_->should_quit;
-}
-
-}  // namespace base
diff --git a/base/message_loop/message_pump_glib.h b/base/message_loop/message_pump_glib.h
deleted file mode 100644
index d79dba5..0000000
--- a/base/message_loop/message_pump_glib.h
+++ /dev/null
@@ -1,80 +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_MESSAGE_LOOP_MESSAGE_PUMP_GLIB_H_
-#define BASE_MESSAGE_LOOP_MESSAGE_PUMP_GLIB_H_
-
-#include <memory>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/message_loop/message_pump.h"
-#include "base/observer_list.h"
-#include "base/time/time.h"
-
-typedef struct _GMainContext GMainContext;
-typedef struct _GPollFD GPollFD;
-typedef struct _GSource GSource;
-
-namespace base {
-
-// This class implements a base MessagePump needed for TYPE_UI MessageLoops on
-// platforms using GLib.
-class BASE_EXPORT MessagePumpGlib : public MessagePump {
- public:
-  MessagePumpGlib();
-  ~MessagePumpGlib() override;
-
-  // Internal methods used for processing the pump callbacks.  They are
-  // public for simplicity but should not be used directly.  HandlePrepare
-  // is called during the prepare step of glib, and returns a timeout that
-  // will be passed to the poll. HandleCheck is called after the poll
-  // has completed, and returns whether or not HandleDispatch should be called.
-  // HandleDispatch is called if HandleCheck returned true.
-  int HandlePrepare();
-  bool HandleCheck();
-  void HandleDispatch();
-
-  // Overridden from MessagePump:
-  void Run(Delegate* delegate) override;
-  void Quit() override;
-  void ScheduleWork() override;
-  void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
-
- private:
-  bool ShouldQuit() const;
-
-  // We may make recursive calls to Run, so we save state that needs to be
-  // separate between them in this structure type.
-  struct RunState;
-
-  RunState* state_;
-
-  // This is a GLib structure that we can add event sources to.  We use the
-  // default GLib context, which is the one to which all GTK events are
-  // dispatched.
-  GMainContext* context_;
-
-  // This is the time when we need to do delayed work.
-  TimeTicks delayed_work_time_;
-
-  // The work source.  It is shared by all calls to Run and destroyed when
-  // the message pump is destroyed.
-  GSource* work_source_;
-
-  // We use a wakeup pipe to make sure we'll get out of the glib polling phase
-  // when another thread has scheduled us to do some work.  There is a glib
-  // mechanism g_main_context_wakeup, but this won't guarantee that our event's
-  // Dispatch() will be called.
-  int wakeup_pipe_read_;
-  int wakeup_pipe_write_;
-  // Use a unique_ptr to avoid needing the definition of GPollFD in the header.
-  std::unique_ptr<GPollFD> wakeup_gpollfd_;
-
-  DISALLOW_COPY_AND_ASSIGN(MessagePumpGlib);
-};
-
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_MESSAGE_PUMP_GLIB_H_
diff --git a/base/message_loop/message_pump_libevent.cc b/base/message_loop/message_pump_libevent.cc
deleted file mode 100644
index 2b47681..0000000
--- a/base/message_loop/message_pump_libevent.cc
+++ /dev/null
@@ -1,344 +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 "base/message_loop/message_pump_libevent.h"
-
-#include <errno.h>
-#include <unistd.h>
-
-#include <utility>
-
-#include "base/auto_reset.h"
-#include "base/compiler_specific.h"
-#include "base/files/file_util.h"
-#include "base/logging.h"
-#include "base/posix/eintr_wrapper.h"
-#include "base/third_party/libevent/event.h"
-#include "base/time/time.h"
-#include "build_config.h"
-
-#if defined(OS_MACOSX)
-#include "base/mac/scoped_nsautorelease_pool.h"
-#endif
-
-// Lifecycle of struct event
-// Libevent uses two main data structures:
-// struct event_base (of which there is one per message pump), and
-// struct event (of which there is roughly one per socket).
-// The socket's struct event is created in
-// MessagePumpLibevent::WatchFileDescriptor(),
-// is owned by the FdWatchController, and is destroyed in
-// StopWatchingFileDescriptor().
-// It is moved into and out of lists in struct event_base by
-// the libevent functions event_add() and event_del().
-//
-// TODO(dkegel):
-// At the moment bad things happen if a FdWatchController
-// is active after its MessagePumpLibevent has been destroyed.
-// See MessageLoopTest.FdWatchControllerOutlivesMessageLoop
-// Not clear yet whether that situation occurs in practice,
-// but if it does, we need to fix it.
-
-namespace base {
-
-MessagePumpLibevent::FdWatchController::FdWatchController(
-    const Location& from_here)
-    : FdWatchControllerInterface(from_here) {}
-
-MessagePumpLibevent::FdWatchController::~FdWatchController() {
-  if (event_) {
-    StopWatchingFileDescriptor();
-  }
-  if (was_destroyed_) {
-    DCHECK(!*was_destroyed_);
-    *was_destroyed_ = true;
-  }
-}
-
-bool MessagePumpLibevent::FdWatchController::StopWatchingFileDescriptor() {
-  std::unique_ptr<event> e = ReleaseEvent();
-  if (!e)
-    return true;
-
-  // event_del() is a no-op if the event isn't active.
-  int rv = event_del(e.get());
-  pump_ = nullptr;
-  watcher_ = nullptr;
-  return (rv == 0);
-}
-
-void MessagePumpLibevent::FdWatchController::Init(std::unique_ptr<event> e) {
-  DCHECK(e);
-  DCHECK(!event_);
-
-  event_ = std::move(e);
-}
-
-std::unique_ptr<event> MessagePumpLibevent::FdWatchController::ReleaseEvent() {
-  return std::move(event_);
-}
-
-void MessagePumpLibevent::FdWatchController::OnFileCanReadWithoutBlocking(
-    int fd,
-    MessagePumpLibevent* pump) {
-  // Since OnFileCanWriteWithoutBlocking() gets called first, it can stop
-  // watching the file descriptor.
-  if (!watcher_)
-    return;
-  watcher_->OnFileCanReadWithoutBlocking(fd);
-}
-
-void MessagePumpLibevent::FdWatchController::OnFileCanWriteWithoutBlocking(
-    int fd,
-    MessagePumpLibevent* pump) {
-  DCHECK(watcher_);
-  watcher_->OnFileCanWriteWithoutBlocking(fd);
-}
-
-MessagePumpLibevent::MessagePumpLibevent()
-    : keep_running_(true),
-      in_run_(false),
-      processed_io_events_(false),
-      event_base_(event_base_new()),
-      wakeup_pipe_in_(-1),
-      wakeup_pipe_out_(-1) {
-  if (!Init())
-    NOTREACHED();
-}
-
-MessagePumpLibevent::~MessagePumpLibevent() {
-  DCHECK(wakeup_event_);
-  DCHECK(event_base_);
-  event_del(wakeup_event_);
-  delete wakeup_event_;
-  if (wakeup_pipe_in_ >= 0) {
-    if (IGNORE_EINTR(close(wakeup_pipe_in_)) < 0)
-      DPLOG(ERROR) << "close";
-  }
-  if (wakeup_pipe_out_ >= 0) {
-    if (IGNORE_EINTR(close(wakeup_pipe_out_)) < 0)
-      DPLOG(ERROR) << "close";
-  }
-  event_base_free(event_base_);
-}
-
-bool MessagePumpLibevent::WatchFileDescriptor(int fd,
-                                              bool persistent,
-                                              int mode,
-                                              FdWatchController* controller,
-                                              FdWatcher* delegate) {
-  DCHECK_GE(fd, 0);
-  DCHECK(controller);
-  DCHECK(delegate);
-  DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
-  // WatchFileDescriptor should be called on the pump thread. It is not
-  // threadsafe, and your watcher may never be registered.
-  DCHECK(watch_file_descriptor_caller_checker_.CalledOnValidThread());
-
-  int event_mask = persistent ? EV_PERSIST : 0;
-  if (mode & WATCH_READ) {
-    event_mask |= EV_READ;
-  }
-  if (mode & WATCH_WRITE) {
-    event_mask |= EV_WRITE;
-  }
-
-  std::unique_ptr<event> evt(controller->ReleaseEvent());
-  if (!evt) {
-    // Ownership is transferred to the controller.
-    evt.reset(new event);
-  } else {
-    // Make sure we don't pick up any funky internal libevent masks.
-    int old_interest_mask = evt->ev_events & (EV_READ | EV_WRITE | EV_PERSIST);
-
-    // Combine old/new event masks.
-    event_mask |= old_interest_mask;
-
-    // Must disarm the event before we can reuse it.
-    event_del(evt.get());
-
-    // It's illegal to use this function to listen on 2 separate fds with the
-    // same |controller|.
-    if (EVENT_FD(evt.get()) != fd) {
-      NOTREACHED() << "FDs don't match" << EVENT_FD(evt.get()) << "!=" << fd;
-      return false;
-    }
-  }
-
-  // Set current interest mask and message pump for this event.
-  event_set(evt.get(), fd, event_mask, OnLibeventNotification, controller);
-
-  // Tell libevent which message pump this socket will belong to when we add it.
-  if (event_base_set(event_base_, evt.get())) {
-    DPLOG(ERROR) << "event_base_set(fd=" << EVENT_FD(evt.get()) << ")";
-    return false;
-  }
-
-  // Add this socket to the list of monitored sockets.
-  if (event_add(evt.get(), nullptr)) {
-    DPLOG(ERROR) << "event_add failed(fd=" << EVENT_FD(evt.get()) << ")";
-    return false;
-  }
-
-  controller->Init(std::move(evt));
-  controller->set_watcher(delegate);
-  controller->set_pump(this);
-  return true;
-}
-
-// Tell libevent to break out of inner loop.
-static void timer_callback(int fd, short events, void* context) {
-  event_base_loopbreak((struct event_base*)context);
-}
-
-// Reentrant!
-void MessagePumpLibevent::Run(Delegate* delegate) {
-  AutoReset<bool> auto_reset_keep_running(&keep_running_, true);
-  AutoReset<bool> auto_reset_in_run(&in_run_, true);
-
-  // event_base_loopexit() + EVLOOP_ONCE is leaky, see http://crbug.com/25641.
-  // Instead, make our own timer and reuse it on each call to event_base_loop().
-  std::unique_ptr<event> timer_event(new event);
-
-  for (;;) {
-#if defined(OS_MACOSX)
-    mac::ScopedNSAutoreleasePool autorelease_pool;
-#endif
-
-    bool did_work = delegate->DoWork();
-    if (!keep_running_)
-      break;
-
-    event_base_loop(event_base_, EVLOOP_NONBLOCK);
-    did_work |= processed_io_events_;
-    processed_io_events_ = false;
-    if (!keep_running_)
-      break;
-
-    did_work |= delegate->DoDelayedWork(&delayed_work_time_);
-    if (!keep_running_)
-      break;
-
-    if (did_work)
-      continue;
-
-    did_work = delegate->DoIdleWork();
-    if (!keep_running_)
-      break;
-
-    if (did_work)
-      continue;
-
-    // EVLOOP_ONCE tells libevent to only block once,
-    // but to service all pending events when it wakes up.
-    if (delayed_work_time_.is_null()) {
-      event_base_loop(event_base_, EVLOOP_ONCE);
-    } else {
-      TimeDelta delay = delayed_work_time_ - TimeTicks::Now();
-      if (delay > TimeDelta()) {
-        struct timeval poll_tv;
-        poll_tv.tv_sec = delay.InSeconds();
-        poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;
-        event_set(timer_event.get(), -1, 0, timer_callback, event_base_);
-        event_base_set(event_base_, timer_event.get());
-        event_add(timer_event.get(), &poll_tv);
-        event_base_loop(event_base_, EVLOOP_ONCE);
-        event_del(timer_event.get());
-      } else {
-        // It looks like delayed_work_time_ indicates a time in the past, so we
-        // need to call DoDelayedWork now.
-        delayed_work_time_ = TimeTicks();
-      }
-    }
-
-    if (!keep_running_)
-      break;
-  }
-}
-
-void MessagePumpLibevent::Quit() {
-  DCHECK(in_run_) << "Quit was called outside of Run!";
-  // Tell both libevent and Run that they should break out of their loops.
-  keep_running_ = false;
-  ScheduleWork();
-}
-
-void MessagePumpLibevent::ScheduleWork() {
-  // Tell libevent (in a threadsafe way) that it should break out of its loop.
-  char buf = 0;
-  int nwrite = HANDLE_EINTR(write(wakeup_pipe_in_, &buf, 1));
-  DCHECK(nwrite == 1 || errno == EAGAIN)
-      << "[nwrite:" << nwrite << "] [errno:" << errno << "]";
-}
-
-void MessagePumpLibevent::ScheduleDelayedWork(
-    const TimeTicks& delayed_work_time) {
-  // We know that we can't be blocked on Wait right now since this method can
-  // only be called on the same thread as Run, so we only need to update our
-  // record of how long to sleep when we do sleep.
-  delayed_work_time_ = delayed_work_time;
-}
-
-bool MessagePumpLibevent::Init() {
-  int fds[2];
-  if (!CreateLocalNonBlockingPipe(fds)) {
-    DPLOG(ERROR) << "pipe creation failed";
-    return false;
-  }
-  wakeup_pipe_out_ = fds[0];
-  wakeup_pipe_in_ = fds[1];
-
-  wakeup_event_ = new event;
-  event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
-            OnWakeup, this);
-  event_base_set(event_base_, wakeup_event_);
-
-  if (event_add(wakeup_event_, nullptr))
-    return false;
-  return true;
-}
-
-// static
-void MessagePumpLibevent::OnLibeventNotification(int fd,
-                                                 short flags,
-                                                 void* context) {
-  FdWatchController* controller = static_cast<FdWatchController*>(context);
-  DCHECK(controller);
-
-  MessagePumpLibevent* pump = controller->pump();
-  pump->processed_io_events_ = true;
-
-  if ((flags & (EV_READ | EV_WRITE)) == (EV_READ | EV_WRITE)) {
-    // Both callbacks will be called. It is necessary to check that |controller|
-    // is not destroyed.
-    bool controller_was_destroyed = false;
-    controller->was_destroyed_ = &controller_was_destroyed;
-    controller->OnFileCanWriteWithoutBlocking(fd, pump);
-    if (!controller_was_destroyed)
-      controller->OnFileCanReadWithoutBlocking(fd, pump);
-    if (!controller_was_destroyed)
-      controller->was_destroyed_ = nullptr;
-  } else if (flags & EV_WRITE) {
-    controller->OnFileCanWriteWithoutBlocking(fd, pump);
-  } else if (flags & EV_READ) {
-    controller->OnFileCanReadWithoutBlocking(fd, pump);
-  }
-}
-
-// Called if a byte is received on the wakeup pipe.
-// static
-void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
-  MessagePumpLibevent* that = static_cast<MessagePumpLibevent*>(context);
-  DCHECK(that->wakeup_pipe_out_ == socket);
-
-  // Remove and discard the wakeup byte.
-  char buf;
-  int nread = HANDLE_EINTR(read(socket, &buf, 1));
-  DCHECK_EQ(nread, 1);
-  that->processed_io_events_ = true;
-  // Tell libevent to break out of inner loop.
-  event_base_loopbreak(that->event_base_);
-}
-
-}  // namespace base
diff --git a/base/message_loop/message_pump_libevent.h b/base/message_loop/message_pump_libevent.h
deleted file mode 100644
index 002c36c..0000000
--- a/base/message_loop/message_pump_libevent.h
+++ /dev/null
@@ -1,123 +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_MESSAGE_LOOP_MESSAGE_PUMP_LIBEVENT_H_
-#define BASE_MESSAGE_LOOP_MESSAGE_PUMP_LIBEVENT_H_
-
-#include <memory>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/message_loop/message_pump.h"
-#include "base/message_loop/watchable_io_message_pump_posix.h"
-#include "base/threading/thread_checker.h"
-#include "base/time/time.h"
-
-// Declare structs we need from libevent.h rather than including it
-struct event_base;
-struct event;
-
-namespace base {
-
-// Class to monitor sockets and issue callbacks when sockets are ready for I/O
-// TODO(dkegel): add support for background file IO somehow
-class BASE_EXPORT MessagePumpLibevent : public MessagePump,
-                                        public WatchableIOMessagePumpPosix {
- public:
-  class FdWatchController : public FdWatchControllerInterface {
-   public:
-    explicit FdWatchController(const Location& from_here);
-
-    // Implicitly calls StopWatchingFileDescriptor.
-    ~FdWatchController() override;
-
-    // FdWatchControllerInterface:
-    bool StopWatchingFileDescriptor() override;
-
-   private:
-    friend class MessagePumpLibevent;
-    friend class MessagePumpLibeventTest;
-
-    // Called by MessagePumpLibevent.
-    void Init(std::unique_ptr<event> e);
-
-    // Used by MessagePumpLibevent to take ownership of |event_|.
-    std::unique_ptr<event> ReleaseEvent();
-
-    void set_pump(MessagePumpLibevent* pump) { pump_ = pump; }
-    MessagePumpLibevent* pump() const { return pump_; }
-
-    void set_watcher(FdWatcher* watcher) { watcher_ = watcher; }
-
-    void OnFileCanReadWithoutBlocking(int fd, MessagePumpLibevent* pump);
-    void OnFileCanWriteWithoutBlocking(int fd, MessagePumpLibevent* pump);
-
-    std::unique_ptr<event> event_;
-    MessagePumpLibevent* pump_ = nullptr;
-    FdWatcher* watcher_ = nullptr;
-    // If this pointer is non-NULL, the pointee is set to true in the
-    // destructor.
-    bool* was_destroyed_ = nullptr;
-
-    DISALLOW_COPY_AND_ASSIGN(FdWatchController);
-  };
-
-  MessagePumpLibevent();
-  ~MessagePumpLibevent() override;
-
-  bool WatchFileDescriptor(int fd,
-                           bool persistent,
-                           int mode,
-                           FdWatchController* controller,
-                           FdWatcher* delegate);
-
-  // MessagePump methods:
-  void Run(Delegate* delegate) override;
-  void Quit() override;
-  void ScheduleWork() override;
-  void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
-
- private:
-  friend class MessagePumpLibeventTest;
-
-  // Risky part of constructor.  Returns true on success.
-  bool Init();
-
-  // Called by libevent to tell us a registered FD can be read/written to.
-  static void OnLibeventNotification(int fd, short flags, void* context);
-
-  // Unix pipe used to implement ScheduleWork()
-  // ... callback; called by libevent inside Run() when pipe is ready to read
-  static void OnWakeup(int socket, short flags, void* context);
-
-  // This flag is set to false when Run should return.
-  bool keep_running_;
-
-  // This flag is set when inside Run.
-  bool in_run_;
-
-  // This flag is set if libevent has processed I/O events.
-  bool processed_io_events_;
-
-  // The time at which we should call DoDelayedWork.
-  TimeTicks delayed_work_time_;
-
-  // Libevent dispatcher.  Watches all sockets registered with it, and sends
-  // readiness callbacks when a socket is ready for I/O.
-  event_base* event_base_;
-
-  // ... write end; ScheduleWork() writes a single byte to it
-  int wakeup_pipe_in_;
-  // ... read end; OnWakeup reads it and then breaks Run() out of its sleep
-  int wakeup_pipe_out_;
-  // ... libevent wrapper for read end
-  event* wakeup_event_;
-
-  ThreadChecker watch_file_descriptor_caller_checker_;
-  DISALLOW_COPY_AND_ASSIGN(MessagePumpLibevent);
-};
-
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_MESSAGE_PUMP_LIBEVENT_H_
diff --git a/base/message_loop/message_pump_mac.h b/base/message_loop/message_pump_mac.h
deleted file mode 100644
index 686fcd2..0000000
--- a/base/message_loop/message_pump_mac.h
+++ /dev/null
@@ -1,404 +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.
-
-// The basis for all native run loops on the Mac is the CFRunLoop.  It can be
-// used directly, it can be used as the driving force behind the similar
-// Foundation NSRunLoop, and it can be used to implement higher-level event
-// loops such as the NSApplication event loop.
-//
-// This file introduces a basic CFRunLoop-based implementation of the
-// MessagePump interface called CFRunLoopBase.  CFRunLoopBase contains all
-// of the machinery necessary to dispatch events to a delegate, but does not
-// implement the specific run loop.  Concrete subclasses must provide their
-// own DoRun and Quit implementations.
-//
-// A concrete subclass that just runs a CFRunLoop loop is provided in
-// MessagePumpCFRunLoop.  For an NSRunLoop, the similar MessagePumpNSRunLoop
-// is provided.
-//
-// For the application's event loop, an implementation based on AppKit's
-// NSApplication event system is provided in MessagePumpNSApplication.
-//
-// Typically, MessagePumpNSApplication only makes sense on a Cocoa
-// application's main thread.  If a CFRunLoop-based message pump is needed on
-// any other thread, one of the other concrete subclasses is preferable.
-// MessagePumpMac::Create is defined, which returns a new NSApplication-based
-// or NSRunLoop-based MessagePump subclass depending on which thread it is
-// called on.
-
-#ifndef BASE_MESSAGE_LOOP_MESSAGE_PUMP_MAC_H_
-#define BASE_MESSAGE_LOOP_MESSAGE_PUMP_MAC_H_
-
-#include "base/message_loop/message_pump.h"
-
-
-#include <CoreFoundation/CoreFoundation.h>
-
-#include "base/macros.h"
-#include "base/memory/weak_ptr.h"
-#include "base/message_loop/timer_slack.h"
-#include "build_config.h"
-
-#if defined(__OBJC__)
-#if defined(OS_IOS)
-#import <Foundation/Foundation.h>
-#else
-#import <AppKit/AppKit.h>
-
-// Clients must subclass NSApplication and implement this protocol if they use
-// MessagePumpMac.
-@protocol CrAppProtocol
-// Must return true if -[NSApplication sendEvent:] is currently on the stack.
-// See the comment for |CreateAutoreleasePool()| in the cc file for why this is
-// necessary.
-- (BOOL)isHandlingSendEvent;
-@end
-#endif  // !defined(OS_IOS)
-#endif  // defined(__OBJC__)
-
-namespace base {
-
-class RunLoop;
-class TimeTicks;
-
-// AutoreleasePoolType is a proxy type for autorelease pools. Its definition
-// depends on the translation unit (TU) in which this header appears. In pure
-// C++ TUs, it is defined as a forward C++ class declaration (that is never
-// defined), because autorelease pools are an Objective-C concept. In Automatic
-// Reference Counting (ARC) Objective-C TUs, it is similarly defined as a
-// forward C++ class declaration, because clang will not allow the type
-// "NSAutoreleasePool" in such TUs. Finally, in Manual Retain Release (MRR)
-// Objective-C TUs, it is a type alias for NSAutoreleasePool. In all cases, a
-// method that takes or returns an NSAutoreleasePool* can use
-// AutoreleasePoolType* instead.
-#if !defined(__OBJC__) || __has_feature(objc_arc)
-class AutoreleasePoolType;
-#else   // !defined(__OBJC__) || __has_feature(objc_arc)
-typedef NSAutoreleasePool AutoreleasePoolType;
-#endif  // !defined(__OBJC__) || __has_feature(objc_arc)
-
-class BASE_EXPORT MessagePumpCFRunLoopBase : public MessagePump {
- public:
-  // MessagePump:
-  void Run(Delegate* delegate) override;
-  void ScheduleWork() override;
-  void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
-  void SetTimerSlack(TimerSlack timer_slack) override;
-
- protected:
-  // Needs access to CreateAutoreleasePool.
-  friend class MessagePumpScopedAutoreleasePool;
-  friend class TestMessagePumpCFRunLoopBase;
-
-  // Tasks will be pumped in the run loop modes described by
-  // |initial_mode_mask|, which maps bits to the index of an internal array of
-  // run loop mode identifiers.
-  explicit MessagePumpCFRunLoopBase(int initial_mode_mask);
-  ~MessagePumpCFRunLoopBase() override;
-
-  // Subclasses should implement the work they need to do in MessagePump::Run
-  // in the DoRun method.  MessagePumpCFRunLoopBase::Run calls DoRun directly.
-  // This arrangement is used because MessagePumpCFRunLoopBase needs to set
-  // up and tear down things before and after the "meat" of DoRun.
-  virtual void DoRun(Delegate* delegate) = 0;
-
-  // Accessors for private data members to be used by subclasses.
-  CFRunLoopRef run_loop() const { return run_loop_; }
-  int nesting_level() const { return nesting_level_; }
-  int run_nesting_level() const { return run_nesting_level_; }
-
-  // Sets this pump's delegate.  Signals the appropriate sources if
-  // |delegateless_work_| is true.  |delegate| can be NULL.
-  void SetDelegate(Delegate* delegate);
-
-  // Return an autorelease pool to wrap around any work being performed.
-  // In some cases, CreateAutoreleasePool may return nil intentionally to
-  // preventing an autorelease pool from being created, allowing any
-  // objects autoreleased by work to fall into the current autorelease pool.
-  virtual AutoreleasePoolType* CreateAutoreleasePool();
-
-  // Enable and disable entries in |enabled_modes_| to match |mode_mask|.
-  void SetModeMask(int mode_mask);
-
-  // Get the current mode mask from |enabled_modes_|.
-  int GetModeMask() const;
-
- private:
-  class ScopedModeEnabler;
-
-  // The maximum number of run loop modes that can be monitored.
-  static constexpr int kNumModes = 4;
-
-  // Marking timers as invalid at the right time helps significantly reduce
-  // power use (see the comment in RunDelayedWorkTimer()), however there is no
-  // public API for doing so. CFRuntime.h states that CFRuntimeBase, upon which
-  // the above timer invalidation functions are based, can change from release
-  // to release and should not be accessed directly (this struct last changed at
-  // least in 2008 in CF-476).
-  //
-  // This function uses private API to modify a test timer's valid state and
-  // uses public API to confirm that the private API changed the right bit.
-  static bool CanInvalidateCFRunLoopTimers();
-
-  // Sets a Core Foundation object's "invalid" bit to |valid|. Based on code
-  // from CFRunLoop.c.
-  static void ChromeCFRunLoopTimerSetValid(CFRunLoopTimerRef timer, bool valid);
-
-  // Timer callback scheduled by ScheduleDelayedWork.  This does not do any
-  // work, but it signals work_source_ so that delayed work can be performed
-  // within the appropriate priority constraints.
-  static void RunDelayedWorkTimer(CFRunLoopTimerRef timer, void* info);
-
-  // Perform highest-priority work.  This is associated with work_source_
-  // signalled by ScheduleWork or RunDelayedWorkTimer.  The static method calls
-  // the instance method; the instance method returns true if it resignalled
-  // work_source_ to be called again from the loop.
-  static void RunWorkSource(void* info);
-  bool RunWork();
-
-  // Perform idle-priority work.  This is normally called by PreWaitObserver,
-  // but is also associated with idle_work_source_.  When this function
-  // actually does perform idle work, it will resignal that source.  The
-  // static method calls the instance method; the instance method returns
-  // true if idle work was done.
-  static void RunIdleWorkSource(void* info);
-  bool RunIdleWork();
-
-  // Perform work that may have been deferred because it was not runnable
-  // within a nested run loop.  This is associated with
-  // nesting_deferred_work_source_ and is signalled by
-  // MaybeScheduleNestingDeferredWork when returning from a nested loop,
-  // so that an outer loop will be able to perform the necessary tasks if it
-  // permits nestable tasks.
-  static void RunNestingDeferredWorkSource(void* info);
-  bool RunNestingDeferredWork();
-
-  // Schedules possible nesting-deferred work to be processed before the run
-  // loop goes to sleep, exits, or begins processing sources at the top of its
-  // loop.  If this function detects that a nested loop had run since the
-  // previous attempt to schedule nesting-deferred work, it will schedule a
-  // call to RunNestingDeferredWorkSource.
-  void MaybeScheduleNestingDeferredWork();
-
-  // Observer callback responsible for performing idle-priority work, before
-  // the run loop goes to sleep.  Associated with idle_work_observer_.
-  static void PreWaitObserver(CFRunLoopObserverRef observer,
-                              CFRunLoopActivity activity, void* info);
-
-  // Observer callback called before the run loop processes any sources.
-  // Associated with pre_source_observer_.
-  static void PreSourceObserver(CFRunLoopObserverRef observer,
-                                CFRunLoopActivity activity, void* info);
-
-  // Observer callback called when the run loop starts and stops, at the
-  // beginning and end of calls to CFRunLoopRun.  This is used to maintain
-  // nesting_level_.  Associated with enter_exit_observer_.
-  static void EnterExitObserver(CFRunLoopObserverRef observer,
-                                CFRunLoopActivity activity, void* info);
-
-  // Called by EnterExitObserver after performing maintenance on nesting_level_.
-  // This allows subclasses an opportunity to perform additional processing on
-  // the basis of run loops starting and stopping.
-  virtual void EnterExitRunLoop(CFRunLoopActivity activity);
-
-  // The thread's run loop.
-  CFRunLoopRef run_loop_;
-
-  // The enabled modes. Posted tasks may run in any non-null entry.
-  std::unique_ptr<ScopedModeEnabler> enabled_modes_[kNumModes];
-
-  // The timer, sources, and observers are described above alongside their
-  // callbacks.
-  CFRunLoopTimerRef delayed_work_timer_;
-  CFRunLoopSourceRef work_source_;
-  CFRunLoopSourceRef idle_work_source_;
-  CFRunLoopSourceRef nesting_deferred_work_source_;
-  CFRunLoopObserverRef pre_wait_observer_;
-  CFRunLoopObserverRef pre_source_observer_;
-  CFRunLoopObserverRef enter_exit_observer_;
-
-  // (weak) Delegate passed as an argument to the innermost Run call.
-  Delegate* delegate_;
-
-  // The time that delayed_work_timer_ is scheduled to fire.  This is tracked
-  // independently of CFRunLoopTimerGetNextFireDate(delayed_work_timer_)
-  // to be able to reset the timer properly after waking from system sleep.
-  // See PowerStateNotification.
-  CFAbsoluteTime delayed_work_fire_time_;
-
-  base::TimerSlack timer_slack_;
-
-  // The recursion depth of the currently-executing CFRunLoopRun loop on the
-  // run loop's thread.  0 if no run loops are running inside of whatever scope
-  // the object was created in.
-  int nesting_level_;
-
-  // The recursion depth (calculated in the same way as nesting_level_) of the
-  // innermost executing CFRunLoopRun loop started by a call to Run.
-  int run_nesting_level_;
-
-  // The deepest (numerically highest) recursion depth encountered since the
-  // most recent attempt to run nesting-deferred work.
-  int deepest_nesting_level_;
-
-  // "Delegateless" work flags are set when work is ready to be performed but
-  // must wait until a delegate is available to process it.  This can happen
-  // when a MessagePumpCFRunLoopBase is instantiated and work arrives without
-  // any call to Run on the stack.  The Run method will check for delegateless
-  // work on entry and redispatch it as needed once a delegate is available.
-  bool delegateless_work_;
-  bool delegateless_idle_work_;
-
-  DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoopBase);
-};
-
-class BASE_EXPORT MessagePumpCFRunLoop : public MessagePumpCFRunLoopBase {
- public:
-  MessagePumpCFRunLoop();
-  ~MessagePumpCFRunLoop() override;
-
-  void DoRun(Delegate* delegate) override;
-  void Quit() override;
-
- private:
-  void EnterExitRunLoop(CFRunLoopActivity activity) override;
-
-  // True if Quit is called to stop the innermost MessagePump
-  // (innermost_quittable_) but some other CFRunLoopRun loop (nesting_level_)
-  // is running inside the MessagePump's innermost Run call.
-  bool quit_pending_;
-
-  DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoop);
-};
-
-class BASE_EXPORT MessagePumpNSRunLoop : public MessagePumpCFRunLoopBase {
- public:
-  MessagePumpNSRunLoop();
-  ~MessagePumpNSRunLoop() override;
-
-  void DoRun(Delegate* delegate) override;
-  void Quit() override;
-
- private:
-  // A source that doesn't do anything but provide something signalable
-  // attached to the run loop.  This source will be signalled when Quit
-  // is called, to cause the loop to wake up so that it can stop.
-  CFRunLoopSourceRef quit_source_;
-
-  // False after Quit is called.
-  bool keep_running_;
-
-  DISALLOW_COPY_AND_ASSIGN(MessagePumpNSRunLoop);
-};
-
-#if defined(OS_IOS)
-// This is a fake message pump.  It attaches sources to the main thread's
-// CFRunLoop, so PostTask() will work, but it is unable to drive the loop
-// directly, so calling Run() or Quit() are errors.
-class MessagePumpUIApplication : public MessagePumpCFRunLoopBase {
- public:
-  MessagePumpUIApplication();
-  ~MessagePumpUIApplication() override;
-  void DoRun(Delegate* delegate) override;
-  void Quit() override;
-
-  // This message pump can not spin the main message loop directly.  Instead,
-  // call |Attach()| to set up a delegate.  It is an error to call |Run()|.
-  virtual void Attach(Delegate* delegate);
-
- private:
-  RunLoop* run_loop_;
-
-  DISALLOW_COPY_AND_ASSIGN(MessagePumpUIApplication);
-};
-
-#else
-
-// While in scope, permits posted tasks to be run in private AppKit run loop
-// modes that would otherwise make the UI unresponsive. E.g., menu fade out.
-class BASE_EXPORT ScopedPumpMessagesInPrivateModes {
- public:
-  ScopedPumpMessagesInPrivateModes();
-  ~ScopedPumpMessagesInPrivateModes();
-
-  int GetModeMaskForTest();
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(ScopedPumpMessagesInPrivateModes);
-};
-
-class MessagePumpNSApplication : public MessagePumpCFRunLoopBase {
- public:
-  MessagePumpNSApplication();
-  ~MessagePumpNSApplication() override;
-
-  void DoRun(Delegate* delegate) override;
-  void Quit() override;
-
- private:
-  friend class ScopedPumpMessagesInPrivateModes;
-
-  // False after Quit is called.
-  bool keep_running_;
-
-  // True if DoRun is managing its own run loop as opposed to letting
-  // -[NSApplication run] handle it.  The outermost run loop in the application
-  // is managed by -[NSApplication run], inner run loops are handled by a loop
-  // in DoRun.
-  bool running_own_loop_;
-
-  DISALLOW_COPY_AND_ASSIGN(MessagePumpNSApplication);
-};
-
-class MessagePumpCrApplication : public MessagePumpNSApplication {
- public:
-  MessagePumpCrApplication();
-  ~MessagePumpCrApplication() override;
-
- protected:
-  // Returns nil if NSApp is currently in the middle of calling
-  // -sendEvent.  Requires NSApp implementing CrAppProtocol.
-  AutoreleasePoolType* CreateAutoreleasePool() override;
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(MessagePumpCrApplication);
-};
-#endif  // !defined(OS_IOS)
-
-class BASE_EXPORT MessagePumpMac {
- public:
-  // If not on the main thread, returns a new instance of
-  // MessagePumpNSRunLoop.
-  //
-  // On the main thread, if NSApp exists and conforms to
-  // CrAppProtocol, creates an instances of MessagePumpCrApplication.
-  //
-  // Otherwise creates an instance of MessagePumpNSApplication using a
-  // default NSApplication.
-  static std::unique_ptr<MessagePump> Create();
-
-#if !defined(OS_IOS)
-  // If a pump is created before the required CrAppProtocol is
-  // created, the wrong MessagePump subclass could be used.
-  // UsingCrApp() returns false if the message pump was created before
-  // NSApp was initialized, or if NSApp does not implement
-  // CrAppProtocol.  NSApp must be initialized before calling.
-  static bool UsingCrApp();
-
-  // Wrapper to query -[NSApp isHandlingSendEvent] from C++ code.
-  // Requires NSApp to implement CrAppProtocol.
-  static bool IsHandlingSendEvent();
-#endif  // !defined(OS_IOS)
-
- private:
-  DISALLOW_IMPLICIT_CONSTRUCTORS(MessagePumpMac);
-};
-
-// Tasks posted to the message loop are posted under this mode, as well
-// as kCFRunLoopCommonModes.
-extern const CFStringRef BASE_EXPORT kMessageLoopExclusiveRunLoopMode;
-
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_MESSAGE_PUMP_MAC_H_
diff --git a/base/message_loop/message_pump_mac.mm b/base/message_loop/message_pump_mac.mm
deleted file mode 100644
index 14b0a86..0000000
--- a/base/message_loop/message_pump_mac.mm
+++ /dev/null
@@ -1,935 +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.
-
-#import "base/message_loop/message_pump_mac.h"
-
-#import <Foundation/Foundation.h>
-
-#include <limits>
-#include <memory>
-
-#include "base/auto_reset.h"
-#include "base/logging.h"
-#include "base/mac/call_with_eh_frame.h"
-#include "base/mac/scoped_cftyperef.h"
-#include "base/macros.h"
-#include "base/message_loop/timer_slack.h"
-#include "base/run_loop.h"
-#include "base/time/time.h"
-#include "build_config.h"
-
-#if !defined(OS_IOS)
-#import <AppKit/AppKit.h>
-#endif  // !defined(OS_IOS)
-
-namespace base {
-
-const CFStringRef kMessageLoopExclusiveRunLoopMode =
-    CFSTR("kMessageLoopExclusiveRunLoopMode");
-
-namespace {
-
-// Mask that determines which modes to use.
-enum { kCommonModeMask = 0x1, kAllModesMask = 0xf };
-
-// Modes to use for MessagePumpNSApplication that are considered "safe".
-// Currently just common and exclusive modes. Ideally, messages would be pumped
-// in all modes, but that interacts badly with app modal dialogs (e.g. NSAlert).
-enum { kNSApplicationModalSafeModeMask = 0x3 };
-
-void NoOp(void* info) {
-}
-
-constexpr CFTimeInterval kCFTimeIntervalMax =
-    std::numeric_limits<CFTimeInterval>::max();
-
-#if !defined(OS_IOS)
-// Set to true if MessagePumpMac::Create() is called before NSApp is
-// initialized.  Only accessed from the main thread.
-bool g_not_using_cr_app = false;
-
-// The MessagePump controlling [NSApp run].
-MessagePumpNSApplication* g_app_pump;
-
-// Various CoreFoundation definitions.
-typedef struct __CFRuntimeBase {
-  uintptr_t _cfisa;
-  uint8_t _cfinfo[4];
-  uint32_t _rc;
-} CFRuntimeBase;
-
-#if defined(__BIG_ENDIAN__)
-#define __CF_BIG_ENDIAN__ 1
-#define __CF_LITTLE_ENDIAN__ 0
-#endif
-
-#if defined(__LITTLE_ENDIAN__)
-#define __CF_LITTLE_ENDIAN__ 1
-#define __CF_BIG_ENDIAN__ 0
-#endif
-
-#define CF_INFO_BITS (!!(__CF_BIG_ENDIAN__)*3)
-
-#define __CFBitfieldMask(N1, N2) \
-  ((((UInt32)~0UL) << (31UL - (N1) + (N2))) >> (31UL - N1))
-#define __CFBitfieldSetValue(V, N1, N2, X)   \
-  ((V) = ((V) & ~__CFBitfieldMask(N1, N2)) | \
-         (((X) << (N2)) & __CFBitfieldMask(N1, N2)))
-
-// Marking timers as invalid at the right time by flipping their valid bit helps
-// significantly reduce power use (see the explanation in
-// RunDelayedWorkTimer()), however there is no public API for doing so.
-// CFRuntime.h states that CFRuntimeBase can change from release to release
-// and should not be accessed directly. The last known change of this struct
-// occurred in 2008 in CF-476 / 10.5; unfortunately the source for 10.11 and
-// 10.12 is not available for inspection at this time.
-// CanInvalidateCFRunLoopTimers() will at least prevent us from invalidating
-// timers if this function starts flipping the wrong bit on a future OS release.
-void __ChromeCFRunLoopTimerSetValid(CFRunLoopTimerRef timer, bool valid) {
-  __CFBitfieldSetValue(((CFRuntimeBase*)timer)->_cfinfo[CF_INFO_BITS], 3, 3,
-                       valid);
-}
-#endif  // !defined(OS_IOS)
-
-}  // namespace
-
-// A scoper for autorelease pools created from message pump run loops.
-// Avoids dirtying up the ScopedNSAutoreleasePool interface for the rare
-// case where an autorelease pool needs to be passed in.
-class MessagePumpScopedAutoreleasePool {
- public:
-  explicit MessagePumpScopedAutoreleasePool(MessagePumpCFRunLoopBase* pump) :
-      pool_(pump->CreateAutoreleasePool()) {
-  }
-   ~MessagePumpScopedAutoreleasePool() {
-    [pool_ drain];
-  }
-
- private:
-  NSAutoreleasePool* pool_;
-  DISALLOW_COPY_AND_ASSIGN(MessagePumpScopedAutoreleasePool);
-};
-
-class MessagePumpCFRunLoopBase::ScopedModeEnabler {
- public:
-  ScopedModeEnabler(MessagePumpCFRunLoopBase* owner, int mode_index)
-      : owner_(owner), mode_index_(mode_index) {
-    CFRunLoopRef loop = owner_->run_loop_;
-    CFRunLoopAddTimer(loop, owner_->delayed_work_timer_, mode());
-    CFRunLoopAddSource(loop, owner_->work_source_, mode());
-    CFRunLoopAddSource(loop, owner_->idle_work_source_, mode());
-    CFRunLoopAddSource(loop, owner_->nesting_deferred_work_source_, mode());
-    CFRunLoopAddObserver(loop, owner_->pre_wait_observer_, mode());
-    CFRunLoopAddObserver(loop, owner_->pre_source_observer_, mode());
-    CFRunLoopAddObserver(loop, owner_->enter_exit_observer_, mode());
-  }
-
-  ~ScopedModeEnabler() {
-    CFRunLoopRef loop = owner_->run_loop_;
-    CFRunLoopRemoveObserver(loop, owner_->enter_exit_observer_, mode());
-    CFRunLoopRemoveObserver(loop, owner_->pre_source_observer_, mode());
-    CFRunLoopRemoveObserver(loop, owner_->pre_wait_observer_, mode());
-    CFRunLoopRemoveSource(loop, owner_->nesting_deferred_work_source_, mode());
-    CFRunLoopRemoveSource(loop, owner_->idle_work_source_, mode());
-    CFRunLoopRemoveSource(loop, owner_->work_source_, mode());
-    CFRunLoopRemoveTimer(loop, owner_->delayed_work_timer_, mode());
-  }
-
-  // This function knows about the AppKit RunLoop modes observed to potentially
-  // run tasks posted to Chrome's main thread task runner. Some are internal to
-  // AppKit but must be observed to keep Chrome's UI responsive. Others that may
-  // be interesting, but are not watched:
-  //  - com.apple.hitoolbox.windows.transitionmode
-  //  - com.apple.hitoolbox.windows.flushmode
-  const CFStringRef& mode() const {
-    static const CFStringRef modes[] = {
-        // The standard Core Foundation "common modes" constant. Must always be
-        // first in this list to match the value of kCommonModeMask.
-        kCFRunLoopCommonModes,
-
-        // Mode that only sees Chrome work sources.
-        kMessageLoopExclusiveRunLoopMode,
-
-        // Process work when NSMenus are fading out.
-        CFSTR("com.apple.hitoolbox.windows.windowfadingmode"),
-
-        // Process work when AppKit is highlighting an item on the main menubar.
-        CFSTR("NSUnhighlightMenuRunLoopMode"),
-    };
-    static_assert(arraysize(modes) == kNumModes, "mode size mismatch");
-    static_assert((1 << kNumModes) - 1 == kAllModesMask,
-                  "kAllModesMask not large enough");
-
-    return modes[mode_index_];
-  }
-
- private:
-  MessagePumpCFRunLoopBase* const owner_;  // Weak. Owns this.
-  const int mode_index_;
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedModeEnabler);
-};
-
-// Must be called on the run loop thread.
-void MessagePumpCFRunLoopBase::Run(Delegate* delegate) {
-  // nesting_level_ will be incremented in EnterExitRunLoop, so set
-  // run_nesting_level_ accordingly.
-  int last_run_nesting_level = run_nesting_level_;
-  run_nesting_level_ = nesting_level_ + 1;
-
-  Delegate* last_delegate = delegate_;
-  SetDelegate(delegate);
-
-  DoRun(delegate);
-
-  // Restore the previous state of the object.
-  SetDelegate(last_delegate);
-  run_nesting_level_ = last_run_nesting_level;
-}
-
-// May be called on any thread.
-void MessagePumpCFRunLoopBase::ScheduleWork() {
-  CFRunLoopSourceSignal(work_source_);
-  CFRunLoopWakeUp(run_loop_);
-}
-
-// Must be called on the run loop thread.
-void MessagePumpCFRunLoopBase::ScheduleDelayedWork(
-    const TimeTicks& delayed_work_time) {
-  TimeDelta delta = delayed_work_time - TimeTicks::Now();
-  delayed_work_fire_time_ = CFAbsoluteTimeGetCurrent() + delta.InSecondsF();
-
-  // Flip the timer's validation bit just before setting the new fire time. Do
-  // this now because CFRunLoopTimerSetNextFireDate() likely checks the validity
-  // of a timer before proceeding to set its fire date. Making the timer valid
-  // now won't have any side effects (such as a premature firing of the timer)
-  // because we're only flipping a bit.
-  //
-  // Please see the comment in RunDelayedWorkTimer() for more info on the whys
-  // of invalidation.
-  ChromeCFRunLoopTimerSetValid(delayed_work_timer_, true);
-
-  CFRunLoopTimerSetNextFireDate(delayed_work_timer_, delayed_work_fire_time_);
-  if (timer_slack_ == TIMER_SLACK_MAXIMUM) {
-    CFRunLoopTimerSetTolerance(delayed_work_timer_, delta.InSecondsF() * 0.5);
-  } else {
-    CFRunLoopTimerSetTolerance(delayed_work_timer_, 0);
-  }
-}
-
-void MessagePumpCFRunLoopBase::SetTimerSlack(TimerSlack timer_slack) {
-  timer_slack_ = timer_slack;
-}
-
-// Must be called on the run loop thread.
-MessagePumpCFRunLoopBase::MessagePumpCFRunLoopBase(int initial_mode_mask)
-    : delegate_(NULL),
-      delayed_work_fire_time_(kCFTimeIntervalMax),
-      timer_slack_(base::TIMER_SLACK_NONE),
-      nesting_level_(0),
-      run_nesting_level_(0),
-      deepest_nesting_level_(0),
-      delegateless_work_(false),
-      delegateless_idle_work_(false) {
-  run_loop_ = CFRunLoopGetCurrent();
-  CFRetain(run_loop_);
-
-  // Set a repeating timer with a preposterous firing time and interval.  The
-  // timer will effectively never fire as-is.  The firing time will be adjusted
-  // as needed when ScheduleDelayedWork is called.
-  CFRunLoopTimerContext timer_context = CFRunLoopTimerContext();
-  timer_context.info = this;
-  delayed_work_timer_ = CFRunLoopTimerCreate(NULL,                // allocator
-                                             kCFTimeIntervalMax,  // fire time
-                                             kCFTimeIntervalMax,  // interval
-                                             0,                   // flags
-                                             0,                   // priority
-                                             RunDelayedWorkTimer,
-                                             &timer_context);
-
-  CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
-  source_context.info = this;
-  source_context.perform = RunWorkSource;
-  work_source_ = CFRunLoopSourceCreate(NULL,  // allocator
-                                       1,     // priority
-                                       &source_context);
-  source_context.perform = RunIdleWorkSource;
-  idle_work_source_ = CFRunLoopSourceCreate(NULL,  // allocator
-                                            2,     // priority
-                                            &source_context);
-  source_context.perform = RunNestingDeferredWorkSource;
-  nesting_deferred_work_source_ = CFRunLoopSourceCreate(NULL,  // allocator
-                                                        0,     // priority
-                                                        &source_context);
-
-  CFRunLoopObserverContext observer_context = CFRunLoopObserverContext();
-  observer_context.info = this;
-  pre_wait_observer_ = CFRunLoopObserverCreate(NULL,  // allocator
-                                               kCFRunLoopBeforeWaiting,
-                                               true,  // repeat
-                                               0,     // priority
-                                               PreWaitObserver,
-                                               &observer_context);
-  pre_source_observer_ = CFRunLoopObserverCreate(NULL,  // allocator
-                                                 kCFRunLoopBeforeSources,
-                                                 true,  // repeat
-                                                 0,     // priority
-                                                 PreSourceObserver,
-                                                 &observer_context);
-  enter_exit_observer_ = CFRunLoopObserverCreate(NULL,  // allocator
-                                                 kCFRunLoopEntry |
-                                                     kCFRunLoopExit,
-                                                 true,  // repeat
-                                                 0,     // priority
-                                                 EnterExitObserver,
-                                                 &observer_context);
-  SetModeMask(initial_mode_mask);
-}
-
-// Ideally called on the run loop thread.  If other run loops were running
-// lower on the run loop thread's stack when this object was created, the
-// same number of run loops must be running when this object is destroyed.
-MessagePumpCFRunLoopBase::~MessagePumpCFRunLoopBase() {
-  SetModeMask(0);
-  CFRelease(enter_exit_observer_);
-  CFRelease(pre_source_observer_);
-  CFRelease(pre_wait_observer_);
-  CFRelease(nesting_deferred_work_source_);
-  CFRelease(idle_work_source_);
-  CFRelease(work_source_);
-  CFRelease(delayed_work_timer_);
-  CFRelease(run_loop_);
-}
-
-void MessagePumpCFRunLoopBase::SetDelegate(Delegate* delegate) {
-  delegate_ = delegate;
-
-  if (delegate) {
-    // If any work showed up but could not be dispatched for want of a
-    // delegate, set it up for dispatch again now that a delegate is
-    // available.
-    if (delegateless_work_) {
-      CFRunLoopSourceSignal(work_source_);
-      delegateless_work_ = false;
-    }
-    if (delegateless_idle_work_) {
-      CFRunLoopSourceSignal(idle_work_source_);
-      delegateless_idle_work_ = false;
-    }
-  }
-}
-
-// Base version returns a standard NSAutoreleasePool.
-AutoreleasePoolType* MessagePumpCFRunLoopBase::CreateAutoreleasePool() {
-  return [[NSAutoreleasePool alloc] init];
-}
-
-void MessagePumpCFRunLoopBase::SetModeMask(int mode_mask) {
-  for (size_t i = 0; i < kNumModes; ++i) {
-    bool enable = mode_mask & (0x1 << i);
-    if (enable == !enabled_modes_[i]) {
-      enabled_modes_[i] =
-          enable ? std::make_unique<ScopedModeEnabler>(this, i) : nullptr;
-    }
-  }
-}
-
-int MessagePumpCFRunLoopBase::GetModeMask() const {
-  int mask = 0;
-  for (size_t i = 0; i < kNumModes; ++i)
-    mask |= enabled_modes_[i] ? (0x1 << i) : 0;
-  return mask;
-}
-
-#if !defined(OS_IOS)
-// This function uses private API to modify a test timer's valid state and
-// uses public API to confirm that the private API changed the correct bit.
-// static
-bool MessagePumpCFRunLoopBase::CanInvalidateCFRunLoopTimers() {
-  CFRunLoopTimerContext timer_context = CFRunLoopTimerContext();
-  timer_context.info = nullptr;
-  ScopedCFTypeRef<CFRunLoopTimerRef> test_timer(
-      CFRunLoopTimerCreate(NULL,                // allocator
-                           kCFTimeIntervalMax,  // fire time
-                           kCFTimeIntervalMax,  // interval
-                           0,                   // flags
-                           0,                   // priority
-                           nullptr, &timer_context));
-  // Should be valid from the start.
-  if (!CFRunLoopTimerIsValid(test_timer)) {
-    return false;
-  }
-  // Confirm that the private API can mark the timer invalid.
-  __ChromeCFRunLoopTimerSetValid(test_timer, false);
-  if (CFRunLoopTimerIsValid(test_timer)) {
-    return false;
-  }
-  // Confirm that the private API can mark the timer valid.
-  __ChromeCFRunLoopTimerSetValid(test_timer, true);
-  return CFRunLoopTimerIsValid(test_timer);
-}
-#endif  // !defined(OS_IOS)
-
-// static
-void MessagePumpCFRunLoopBase::ChromeCFRunLoopTimerSetValid(
-    CFRunLoopTimerRef timer,
-    bool valid) {
-#if !defined(OS_IOS)
-  static bool can_invalidate_timers = CanInvalidateCFRunLoopTimers();
-  if (can_invalidate_timers) {
-    __ChromeCFRunLoopTimerSetValid(timer, valid);
-  }
-#endif  // !defined(OS_IOS)
-}
-
-// Called from the run loop.
-// static
-void MessagePumpCFRunLoopBase::RunDelayedWorkTimer(CFRunLoopTimerRef timer,
-                                                   void* info) {
-  MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
-
-  // The timer won't fire again until it's reset.
-  self->delayed_work_fire_time_ = kCFTimeIntervalMax;
-
-  // The message pump's timer needs to fire at changing and unpredictable
-  // intervals. Creating a new timer for each firing time is very expensive, so
-  // the message pump instead uses a repeating timer with a very large repeat
-  // rate. After each firing of the timer, the run loop sets the timer's next
-  // firing time to the distant future, essentially pausing the timer until the
-  // pump sets the next firing time. This is the solution recommended by Apple.
-  //
-  // It turns out, however, that scheduling timers is also quite expensive, and
-  // that every one of the message pump's timer firings incurs two
-  // reschedulings. The first rescheduling occurs in ScheduleDelayedWork(),
-  // which sets the desired next firing time. The second comes after exiting
-  // this method (the timer's callback method), when the run loop sets the
-  // timer's next firing time to far in the future.
-  //
-  // The code in __CFRunLoopDoTimer() inside CFRunLoop.c calls the timer's
-  // callback, confirms that the timer is valid, and then sets its future
-  // firing time based on its repeat frequency. Flipping the valid bit here
-  // causes the __CFRunLoopDoTimer() to skip setting the future firing time.
-  // Note that there's public API to invalidate a timer but it goes beyond
-  // flipping the valid bit, making the timer unusable in the future.
-  //
-  // ScheduleDelayedWork() flips the valid bit back just before setting the
-  // timer's new firing time.
-  ChromeCFRunLoopTimerSetValid(self->delayed_work_timer_, false);
-
-  // CFRunLoopTimers fire outside of the priority scheme for CFRunLoopSources.
-  // In order to establish the proper priority in which work and delayed work
-  // are processed one for one, the timer used to schedule delayed work must
-  // signal a CFRunLoopSource used to dispatch both work and delayed work.
-  CFRunLoopSourceSignal(self->work_source_);
-}
-
-// Called from the run loop.
-// static
-void MessagePumpCFRunLoopBase::RunWorkSource(void* info) {
-  MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
-  base::mac::CallWithEHFrame(^{
-    self->RunWork();
-  });
-}
-
-// Called by MessagePumpCFRunLoopBase::RunWorkSource.
-bool MessagePumpCFRunLoopBase::RunWork() {
-  if (!delegate_) {
-    // This point can be reached with a NULL delegate_ if Run is not on the
-    // stack but foreign code is spinning the CFRunLoop.  Arrange to come back
-    // here when a delegate is available.
-    delegateless_work_ = true;
-    return false;
-  }
-
-  // The NSApplication-based run loop only drains the autorelease pool at each
-  // UI event (NSEvent).  The autorelease pool is not drained for each
-  // CFRunLoopSource target that's run.  Use a local pool for any autoreleased
-  // objects if the app is not currently handling a UI event to ensure they're
-  // released promptly even in the absence of UI events.
-  MessagePumpScopedAutoreleasePool autorelease_pool(this);
-
-  // Call DoWork and DoDelayedWork once, and if something was done, arrange to
-  // come back here again as long as the loop is still running.
-  bool did_work = delegate_->DoWork();
-  bool resignal_work_source = did_work;
-
-  TimeTicks next_time;
-  delegate_->DoDelayedWork(&next_time);
-  if (!did_work) {
-    // Determine whether there's more delayed work, and if so, if it needs to
-    // be done at some point in the future or if it's already time to do it.
-    // Only do these checks if did_work is false. If did_work is true, this
-    // function, and therefore any additional delayed work, will get another
-    // chance to run before the loop goes to sleep.
-    bool more_delayed_work = !next_time.is_null();
-    if (more_delayed_work) {
-      TimeDelta delay = next_time - TimeTicks::Now();
-      if (delay > TimeDelta()) {
-        // There's more delayed work to be done in the future.
-        ScheduleDelayedWork(next_time);
-      } else {
-        // There's more delayed work to be done, and its time is in the past.
-        // Arrange to come back here directly as long as the loop is still
-        // running.
-        resignal_work_source = true;
-      }
-    }
-  }
-
-  if (resignal_work_source) {
-    CFRunLoopSourceSignal(work_source_);
-  }
-
-  return resignal_work_source;
-}
-
-// Called from the run loop.
-// static
-void MessagePumpCFRunLoopBase::RunIdleWorkSource(void* info) {
-  MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
-  base::mac::CallWithEHFrame(^{
-    self->RunIdleWork();
-  });
-}
-
-// Called by MessagePumpCFRunLoopBase::RunIdleWorkSource.
-bool MessagePumpCFRunLoopBase::RunIdleWork() {
-  if (!delegate_) {
-    // This point can be reached with a NULL delegate_ if Run is not on the
-    // stack but foreign code is spinning the CFRunLoop.  Arrange to come back
-    // here when a delegate is available.
-    delegateless_idle_work_ = true;
-    return false;
-  }
-
-  // The NSApplication-based run loop only drains the autorelease pool at each
-  // UI event (NSEvent).  The autorelease pool is not drained for each
-  // CFRunLoopSource target that's run.  Use a local pool for any autoreleased
-  // objects if the app is not currently handling a UI event to ensure they're
-  // released promptly even in the absence of UI events.
-  MessagePumpScopedAutoreleasePool autorelease_pool(this);
-
-  // Call DoIdleWork once, and if something was done, arrange to come back here
-  // again as long as the loop is still running.
-  bool did_work = delegate_->DoIdleWork();
-  if (did_work) {
-    CFRunLoopSourceSignal(idle_work_source_);
-  }
-
-  return did_work;
-}
-
-// Called from the run loop.
-// static
-void MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource(void* info) {
-  MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
-  base::mac::CallWithEHFrame(^{
-    self->RunNestingDeferredWork();
-  });
-}
-
-// Called by MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource.
-bool MessagePumpCFRunLoopBase::RunNestingDeferredWork() {
-  if (!delegate_) {
-    // This point can be reached with a NULL delegate_ if Run is not on the
-    // stack but foreign code is spinning the CFRunLoop.  There's no sense in
-    // attempting to do any work or signalling the work sources because
-    // without a delegate, work is not possible.
-    return false;
-  }
-
-  // Immediately try work in priority order.
-  if (!RunWork()) {
-    if (!RunIdleWork()) {
-      return false;
-    }
-  } else {
-    // Work was done.  Arrange for the loop to try non-nestable idle work on
-    // a subsequent pass.
-    CFRunLoopSourceSignal(idle_work_source_);
-  }
-
-  return true;
-}
-
-// Called before the run loop goes to sleep or exits, or processes sources.
-void MessagePumpCFRunLoopBase::MaybeScheduleNestingDeferredWork() {
-  // deepest_nesting_level_ is set as run loops are entered.  If the deepest
-  // level encountered is deeper than the current level, a nested loop
-  // (relative to the current level) ran since the last time nesting-deferred
-  // work was scheduled.  When that situation is encountered, schedule
-  // nesting-deferred work in case any work was deferred because nested work
-  // was disallowed.
-  if (deepest_nesting_level_ > nesting_level_) {
-    deepest_nesting_level_ = nesting_level_;
-    CFRunLoopSourceSignal(nesting_deferred_work_source_);
-  }
-}
-
-// Called from the run loop.
-// static
-void MessagePumpCFRunLoopBase::PreWaitObserver(CFRunLoopObserverRef observer,
-                                               CFRunLoopActivity activity,
-                                               void* info) {
-  MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
-  base::mac::CallWithEHFrame(^{
-    // Attempt to do some idle work before going to sleep.
-    self->RunIdleWork();
-
-    // The run loop is about to go to sleep.  If any of the work done since it
-    // started or woke up resulted in a nested run loop running,
-    // nesting-deferred work may have accumulated.  Schedule it for processing
-    // if appropriate.
-    self->MaybeScheduleNestingDeferredWork();
-  });
-}
-
-// Called from the run loop.
-// static
-void MessagePumpCFRunLoopBase::PreSourceObserver(CFRunLoopObserverRef observer,
-                                                 CFRunLoopActivity activity,
-                                                 void* info) {
-  MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
-
-  // The run loop has reached the top of the loop and is about to begin
-  // processing sources.  If the last iteration of the loop at this nesting
-  // level did not sleep or exit, nesting-deferred work may have accumulated
-  // if a nested loop ran.  Schedule nesting-deferred work for processing if
-  // appropriate.
-  base::mac::CallWithEHFrame(^{
-    self->MaybeScheduleNestingDeferredWork();
-  });
-}
-
-// Called from the run loop.
-// static
-void MessagePumpCFRunLoopBase::EnterExitObserver(CFRunLoopObserverRef observer,
-                                                 CFRunLoopActivity activity,
-                                                 void* info) {
-  MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
-
-  switch (activity) {
-    case kCFRunLoopEntry:
-      ++self->nesting_level_;
-      if (self->nesting_level_ > self->deepest_nesting_level_) {
-        self->deepest_nesting_level_ = self->nesting_level_;
-      }
-      break;
-
-    case kCFRunLoopExit:
-      // Not all run loops go to sleep.  If a run loop is stopped before it
-      // goes to sleep due to a CFRunLoopStop call, or if the timeout passed
-      // to CFRunLoopRunInMode expires, the run loop may proceed directly from
-      // handling sources to exiting without any sleep.  This most commonly
-      // occurs when CFRunLoopRunInMode is passed a timeout of 0, causing it
-      // to make a single pass through the loop and exit without sleep.  Some
-      // native loops use CFRunLoop in this way.  Because PreWaitObserver will
-      // not be called in these case, MaybeScheduleNestingDeferredWork needs
-      // to be called here, as the run loop exits.
-      //
-      // MaybeScheduleNestingDeferredWork consults self->nesting_level_
-      // to determine whether to schedule nesting-deferred work.  It expects
-      // the nesting level to be set to the depth of the loop that is going
-      // to sleep or exiting.  It must be called before decrementing the
-      // value so that the value still corresponds to the level of the exiting
-      // loop.
-      base::mac::CallWithEHFrame(^{
-        self->MaybeScheduleNestingDeferredWork();
-      });
-      --self->nesting_level_;
-      break;
-
-    default:
-      break;
-  }
-
-  base::mac::CallWithEHFrame(^{
-    self->EnterExitRunLoop(activity);
-  });
-}
-
-// Called by MessagePumpCFRunLoopBase::EnterExitRunLoop.  The default
-// implementation is a no-op.
-void MessagePumpCFRunLoopBase::EnterExitRunLoop(CFRunLoopActivity activity) {
-}
-
-MessagePumpCFRunLoop::MessagePumpCFRunLoop()
-    : MessagePumpCFRunLoopBase(kCommonModeMask), quit_pending_(false) {}
-
-MessagePumpCFRunLoop::~MessagePumpCFRunLoop() {}
-
-// Called by MessagePumpCFRunLoopBase::DoRun.  If other CFRunLoopRun loops were
-// running lower on the run loop thread's stack when this object was created,
-// the same number of CFRunLoopRun loops must be running for the outermost call
-// to Run.  Run/DoRun are reentrant after that point.
-void MessagePumpCFRunLoop::DoRun(Delegate* delegate) {
-  // This is completely identical to calling CFRunLoopRun(), except autorelease
-  // pool management is introduced.
-  int result;
-  do {
-    MessagePumpScopedAutoreleasePool autorelease_pool(this);
-    result = CFRunLoopRunInMode(kCFRunLoopDefaultMode,
-                                kCFTimeIntervalMax,
-                                false);
-  } while (result != kCFRunLoopRunStopped && result != kCFRunLoopRunFinished);
-}
-
-// Must be called on the run loop thread.
-void MessagePumpCFRunLoop::Quit() {
-  // Stop the innermost run loop managed by this MessagePumpCFRunLoop object.
-  if (nesting_level() == run_nesting_level()) {
-    // This object is running the innermost loop, just stop it.
-    CFRunLoopStop(run_loop());
-  } else {
-    // There's another loop running inside the loop managed by this object.
-    // In other words, someone else called CFRunLoopRunInMode on the same
-    // thread, deeper on the stack than the deepest Run call.  Don't preempt
-    // other run loops, just mark this object to quit the innermost Run as
-    // soon as the other inner loops not managed by Run are done.
-    quit_pending_ = true;
-  }
-}
-
-// Called by MessagePumpCFRunLoopBase::EnterExitObserver.
-void MessagePumpCFRunLoop::EnterExitRunLoop(CFRunLoopActivity activity) {
-  if (activity == kCFRunLoopExit &&
-      nesting_level() == run_nesting_level() &&
-      quit_pending_) {
-    // Quit was called while loops other than those managed by this object
-    // were running further inside a run loop managed by this object.  Now
-    // that all unmanaged inner run loops are gone, stop the loop running
-    // just inside Run.
-    CFRunLoopStop(run_loop());
-    quit_pending_ = false;
-  }
-}
-
-MessagePumpNSRunLoop::MessagePumpNSRunLoop()
-    : MessagePumpCFRunLoopBase(kCommonModeMask), keep_running_(true) {
-  CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
-  source_context.perform = NoOp;
-  quit_source_ = CFRunLoopSourceCreate(NULL,  // allocator
-                                       0,     // priority
-                                       &source_context);
-  CFRunLoopAddSource(run_loop(), quit_source_, kCFRunLoopCommonModes);
-}
-
-MessagePumpNSRunLoop::~MessagePumpNSRunLoop() {
-  CFRunLoopRemoveSource(run_loop(), quit_source_, kCFRunLoopCommonModes);
-  CFRelease(quit_source_);
-}
-
-void MessagePumpNSRunLoop::DoRun(Delegate* delegate) {
-  AutoReset<bool> auto_reset_keep_running(&keep_running_, true);
-
-  while (keep_running_) {
-    // NSRunLoop manages autorelease pools itself.
-    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
-                             beforeDate:[NSDate distantFuture]];
-  }
-}
-
-void MessagePumpNSRunLoop::Quit() {
-  keep_running_ = false;
-  CFRunLoopSourceSignal(quit_source_);
-  CFRunLoopWakeUp(run_loop());
-}
-
-#if defined(OS_IOS)
-MessagePumpUIApplication::MessagePumpUIApplication()
-    : MessagePumpCFRunLoopBase(kCommonModeMask), run_loop_(NULL) {}
-
-MessagePumpUIApplication::~MessagePumpUIApplication() {}
-
-void MessagePumpUIApplication::DoRun(Delegate* delegate) {
-  NOTREACHED();
-}
-
-void MessagePumpUIApplication::Quit() {
-  NOTREACHED();
-}
-
-void MessagePumpUIApplication::Attach(Delegate* delegate) {
-  DCHECK(!run_loop_);
-  run_loop_ = new RunLoop();
-  CHECK(run_loop_->BeforeRun());
-  SetDelegate(delegate);
-}
-
-#else
-
-ScopedPumpMessagesInPrivateModes::ScopedPumpMessagesInPrivateModes() {
-  DCHECK(g_app_pump);
-  DCHECK_EQ(kNSApplicationModalSafeModeMask, g_app_pump->GetModeMask());
-  // Pumping events in private runloop modes is known to interact badly with
-  // app modal windows like NSAlert.
-  if (![NSApp modalWindow])
-    g_app_pump->SetModeMask(kAllModesMask);
-}
-
-ScopedPumpMessagesInPrivateModes::~ScopedPumpMessagesInPrivateModes() {
-  DCHECK(g_app_pump);
-  g_app_pump->SetModeMask(kNSApplicationModalSafeModeMask);
-}
-
-int ScopedPumpMessagesInPrivateModes::GetModeMaskForTest() {
-  return g_app_pump ? g_app_pump->GetModeMask() : -1;
-}
-
-MessagePumpNSApplication::MessagePumpNSApplication()
-    : MessagePumpCFRunLoopBase(kNSApplicationModalSafeModeMask),
-      keep_running_(true),
-      running_own_loop_(false) {
-  DCHECK_EQ(nullptr, g_app_pump);
-  g_app_pump = this;
-}
-
-MessagePumpNSApplication::~MessagePumpNSApplication() {
-  DCHECK_EQ(this, g_app_pump);
-  g_app_pump = nullptr;
-}
-
-void MessagePumpNSApplication::DoRun(Delegate* delegate) {
-  AutoReset<bool> auto_reset_keep_running(&keep_running_, true);
-  bool last_running_own_loop_ = running_own_loop_;
-
-  // NSApp must be initialized by calling:
-  // [{some class which implements CrAppProtocol} sharedApplication]
-  // Most likely candidates are CrApplication or BrowserCrApplication.
-  // These can be initialized from C++ code by calling
-  // RegisterCrApp() or RegisterBrowserCrApp().
-  CHECK(NSApp);
-
-  if (![NSApp isRunning]) {
-    running_own_loop_ = false;
-    // NSApplication manages autorelease pools itself when run this way.
-    [NSApp run];
-  } else {
-    running_own_loop_ = true;
-    NSDate* distant_future = [NSDate distantFuture];
-    while (keep_running_) {
-      MessagePumpScopedAutoreleasePool autorelease_pool(this);
-      NSEvent* event = [NSApp nextEventMatchingMask:NSAnyEventMask
-                                          untilDate:distant_future
-                                             inMode:NSDefaultRunLoopMode
-                                            dequeue:YES];
-      if (event) {
-        [NSApp sendEvent:event];
-      }
-    }
-  }
-
-  running_own_loop_ = last_running_own_loop_;
-}
-
-void MessagePumpNSApplication::Quit() {
-  if (!running_own_loop_) {
-    [[NSApplication sharedApplication] stop:nil];
-  } else {
-    keep_running_ = false;
-  }
-
-  // Send a fake event to wake the loop up.
-  [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined
-                                      location:NSZeroPoint
-                                 modifierFlags:0
-                                     timestamp:0
-                                  windowNumber:0
-                                       context:NULL
-                                       subtype:0
-                                         data1:0
-                                         data2:0]
-           atStart:NO];
-}
-
-MessagePumpCrApplication::MessagePumpCrApplication() {
-}
-
-MessagePumpCrApplication::~MessagePumpCrApplication() {
-}
-
-// Prevents an autorelease pool from being created if the app is in the midst of
-// handling a UI event because various parts of AppKit depend on objects that
-// are created while handling a UI event to be autoreleased in the event loop.
-// An example of this is NSWindowController. When a window with a window
-// controller is closed it goes through a stack like this:
-// (Several stack frames elided for clarity)
-//
-// #0 [NSWindowController autorelease]
-// #1 DoAClose
-// #2 MessagePumpCFRunLoopBase::DoWork()
-// #3 [NSRunLoop run]
-// #4 [NSButton performClick:]
-// #5 [NSWindow sendEvent:]
-// #6 [NSApp sendEvent:]
-// #7 [NSApp run]
-//
-// -performClick: spins a nested run loop. If the pool created in DoWork was a
-// standard NSAutoreleasePool, it would release the objects that were
-// autoreleased into it once DoWork released it. This would cause the window
-// controller, which autoreleased itself in frame #0, to release itself, and
-// possibly free itself. Unfortunately this window controller controls the
-// window in frame #5. When the stack is unwound to frame #5, the window would
-// no longer exists and crashes may occur. Apple gets around this by never
-// releasing the pool it creates in frame #4, and letting frame #7 clean it up
-// when it cleans up the pool that wraps frame #7. When an autorelease pool is
-// released it releases all other pools that were created after it on the
-// autorelease pool stack.
-//
-// CrApplication is responsible for setting handlingSendEvent to true just
-// before it sends the event through the event handling mechanism, and
-// returning it to its previous value once the event has been sent.
-AutoreleasePoolType* MessagePumpCrApplication::CreateAutoreleasePool() {
-  if (MessagePumpMac::IsHandlingSendEvent())
-    return nil;
-  return MessagePumpNSApplication::CreateAutoreleasePool();
-}
-
-// static
-bool MessagePumpMac::UsingCrApp() {
-  DCHECK([NSThread isMainThread]);
-
-  // If NSApp is still not initialized, then the subclass used cannot
-  // be determined.
-  DCHECK(NSApp);
-
-  // The pump was created using MessagePumpNSApplication.
-  if (g_not_using_cr_app)
-    return false;
-
-  return [NSApp conformsToProtocol:@protocol(CrAppProtocol)];
-}
-
-// static
-bool MessagePumpMac::IsHandlingSendEvent() {
-  DCHECK([NSApp conformsToProtocol:@protocol(CrAppProtocol)]);
-  NSObject<CrAppProtocol>* app = static_cast<NSObject<CrAppProtocol>*>(NSApp);
-  return [app isHandlingSendEvent];
-}
-#endif  // !defined(OS_IOS)
-
-// static
-std::unique_ptr<MessagePump> MessagePumpMac::Create() {
-  if ([NSThread isMainThread]) {
-#if defined(OS_IOS)
-    return std::make_unique<MessagePumpUIApplication>();
-#else
-    if ([NSApp conformsToProtocol:@protocol(CrAppProtocol)])
-      return std::make_unique<MessagePumpCrApplication>();
-
-    // The main-thread MessagePump implementations REQUIRE an NSApp.
-    // Executables which have specific requirements for their
-    // NSApplication subclass should initialize appropriately before
-    // creating an event loop.
-    [NSApplication sharedApplication];
-    g_not_using_cr_app = true;
-    return std::make_unique<MessagePumpNSApplication>();
-#endif
-  }
-
-  return std::make_unique<MessagePumpNSRunLoop>();
-}
-
-}  // namespace base
diff --git a/base/message_loop/message_pump_mac_unittest.mm b/base/message_loop/message_pump_mac_unittest.mm
deleted file mode 100644
index 6b63aa1..0000000
--- a/base/message_loop/message_pump_mac_unittest.mm
+++ /dev/null
@@ -1,225 +0,0 @@
-// Copyright 2017 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/message_loop/message_pump_mac.h"
-
-#include "base/mac/scoped_cftyperef.h"
-#import "base/mac/scoped_nsobject.h"
-#include "base/macros.h"
-#include "base/message_loop/message_loop.h"
-#include "base/message_loop/message_loop_current.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-@interface TestModalAlertCloser : NSObject
-- (void)runTestThenCloseAlert:(NSAlert*)alert;
-@end
-
-namespace {
-
-// Internal constants from message_pump_mac.mm.
-constexpr int kAllModesMask = 0xf;
-constexpr int kNSApplicationModalSafeModeMask = 0x3;
-
-}  // namespace
-
-namespace base {
-
-class TestMessagePumpCFRunLoopBase {
- public:
-  bool TestCanInvalidateTimers() {
-    return MessagePumpCFRunLoopBase::CanInvalidateCFRunLoopTimers();
-  }
-  static void SetTimerValid(CFRunLoopTimerRef timer, bool valid) {
-    MessagePumpCFRunLoopBase::ChromeCFRunLoopTimerSetValid(timer, valid);
-  }
-
-  static void PerformTimerCallback(CFRunLoopTimerRef timer, void* info) {
-    TestMessagePumpCFRunLoopBase* self =
-        static_cast<TestMessagePumpCFRunLoopBase*>(info);
-    self->timer_callback_called_ = true;
-
-    if (self->invalidate_timer_in_callback_) {
-      SetTimerValid(timer, false);
-    }
-  }
-
-  bool invalidate_timer_in_callback_;
-
-  bool timer_callback_called_;
-};
-
-TEST(MessagePumpMacTest, TestCanInvalidateTimers) {
-  TestMessagePumpCFRunLoopBase message_pump_test;
-
-  // Catch whether or not the use of private API ever starts failing.
-  EXPECT_TRUE(message_pump_test.TestCanInvalidateTimers());
-}
-
-TEST(MessagePumpMacTest, TestInvalidatedTimerReuse) {
-  TestMessagePumpCFRunLoopBase message_pump_test;
-
-  CFRunLoopTimerContext timer_context = CFRunLoopTimerContext();
-  timer_context.info = &message_pump_test;
-  const CFTimeInterval kCFTimeIntervalMax =
-      std::numeric_limits<CFTimeInterval>::max();
-  ScopedCFTypeRef<CFRunLoopTimerRef> test_timer(CFRunLoopTimerCreate(
-      NULL,                // allocator
-      kCFTimeIntervalMax,  // fire time
-      kCFTimeIntervalMax,  // interval
-      0,                   // flags
-      0,                   // priority
-      TestMessagePumpCFRunLoopBase::PerformTimerCallback, &timer_context));
-  CFRunLoopAddTimer(CFRunLoopGetCurrent(), test_timer,
-                    kMessageLoopExclusiveRunLoopMode);
-
-  // Sanity check.
-  EXPECT_TRUE(CFRunLoopTimerIsValid(test_timer));
-
-  // Confirm that the timer fires as expected, and that it's not a one-time-use
-  // timer (those timers are invalidated after they fire).
-  CFAbsoluteTime next_fire_time = CFAbsoluteTimeGetCurrent() + 0.01;
-  CFRunLoopTimerSetNextFireDate(test_timer, next_fire_time);
-  message_pump_test.timer_callback_called_ = false;
-  message_pump_test.invalidate_timer_in_callback_ = false;
-  CFRunLoopRunInMode(kMessageLoopExclusiveRunLoopMode, 0.02, true);
-  EXPECT_TRUE(message_pump_test.timer_callback_called_);
-  EXPECT_TRUE(CFRunLoopTimerIsValid(test_timer));
-
-  // As a repeating timer, the timer should have a new fire date set in the
-  // future.
-  EXPECT_GT(CFRunLoopTimerGetNextFireDate(test_timer), next_fire_time);
-
-  // Try firing the timer, and invalidating it within its callback.
-  next_fire_time = CFAbsoluteTimeGetCurrent() + 0.01;
-  CFRunLoopTimerSetNextFireDate(test_timer, next_fire_time);
-  message_pump_test.timer_callback_called_ = false;
-  message_pump_test.invalidate_timer_in_callback_ = true;
-  CFRunLoopRunInMode(kMessageLoopExclusiveRunLoopMode, 0.02, true);
-  EXPECT_TRUE(message_pump_test.timer_callback_called_);
-  EXPECT_FALSE(CFRunLoopTimerIsValid(test_timer));
-
-  // The CFRunLoop believes the timer is invalid, so it should not have a
-  // fire date.
-  EXPECT_EQ(0, CFRunLoopTimerGetNextFireDate(test_timer));
-
-  // Now mark the timer as valid and confirm that it still fires correctly.
-  TestMessagePumpCFRunLoopBase::SetTimerValid(test_timer, true);
-  EXPECT_TRUE(CFRunLoopTimerIsValid(test_timer));
-  next_fire_time = CFAbsoluteTimeGetCurrent() + 0.01;
-  CFRunLoopTimerSetNextFireDate(test_timer, next_fire_time);
-  message_pump_test.timer_callback_called_ = false;
-  message_pump_test.invalidate_timer_in_callback_ = false;
-  CFRunLoopRunInMode(kMessageLoopExclusiveRunLoopMode, 0.02, true);
-  EXPECT_TRUE(message_pump_test.timer_callback_called_);
-  EXPECT_TRUE(CFRunLoopTimerIsValid(test_timer));
-
-  // Confirm that the run loop again gave it a new fire date in the future.
-  EXPECT_GT(CFRunLoopTimerGetNextFireDate(test_timer), next_fire_time);
-
-  CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), test_timer,
-                       kMessageLoopExclusiveRunLoopMode);
-}
-
-namespace {
-
-// PostedTasks are only executed while the message pump has a delegate. That is,
-// when a base::RunLoop is running, so in order to test whether posted tasks
-// are run by CFRunLoopRunInMode and *not* by the regular RunLoop, we need to
-// be inside a task that is also calling CFRunLoopRunInMode. This task runs the
-// given |mode| after posting a task to increment a counter, then checks whether
-// the counter incremented after emptying that run loop mode.
-void IncrementInModeAndExpect(CFRunLoopMode mode, int result) {
-  // Since this task is "ours" rather than a system task, allow nesting.
-  MessageLoopCurrent::ScopedNestableTaskAllower allow;
-  int counter = 0;
-  auto increment = BindRepeating([](int* i) { ++*i; }, &counter);
-  ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, increment);
-  while (CFRunLoopRunInMode(mode, 0, true) == kCFRunLoopRunHandledSource)
-    ;
-  ASSERT_EQ(result, counter);
-}
-
-}  // namespace
-
-// Tests the correct behavior of ScopedPumpMessagesInPrivateModes.
-TEST(MessagePumpMacTest, ScopedPumpMessagesInPrivateModes) {
-  MessageLoopForUI message_loop;
-
-  CFRunLoopMode kRegular = kCFRunLoopDefaultMode;
-  CFRunLoopMode kPrivate = CFSTR("NSUnhighlightMenuRunLoopMode");
-
-  // Work is seen when running in the default mode.
-  ThreadTaskRunnerHandle::Get()->PostTask(
-      FROM_HERE, BindOnce(&IncrementInModeAndExpect, kRegular, 1));
-  EXPECT_NO_FATAL_FAILURE(RunLoop().RunUntilIdle());
-
-  // But not seen when running in a private mode.
-  ThreadTaskRunnerHandle::Get()->PostTask(
-      FROM_HERE, BindOnce(&IncrementInModeAndExpect, kPrivate, 0));
-  EXPECT_NO_FATAL_FAILURE(RunLoop().RunUntilIdle());
-
-  {
-    ScopedPumpMessagesInPrivateModes allow_private;
-    // Now the work should be seen.
-    ThreadTaskRunnerHandle::Get()->PostTask(
-        FROM_HERE, BindOnce(&IncrementInModeAndExpect, kPrivate, 1));
-    EXPECT_NO_FATAL_FAILURE(RunLoop().RunUntilIdle());
-
-    // The regular mode should also work the same.
-    ThreadTaskRunnerHandle::Get()->PostTask(
-        FROM_HERE, BindOnce(&IncrementInModeAndExpect, kRegular, 1));
-    EXPECT_NO_FATAL_FAILURE(RunLoop().RunUntilIdle());
-  }
-
-  // And now the scoper is out of scope, private modes should no longer see it.
-  ThreadTaskRunnerHandle::Get()->PostTask(
-      FROM_HERE, BindOnce(&IncrementInModeAndExpect, kPrivate, 0));
-  EXPECT_NO_FATAL_FAILURE(RunLoop().RunUntilIdle());
-
-  // Only regular modes see it.
-  ThreadTaskRunnerHandle::Get()->PostTask(
-      FROM_HERE, BindOnce(&IncrementInModeAndExpect, kRegular, 1));
-  EXPECT_NO_FATAL_FAILURE(RunLoop().RunUntilIdle());
-}
-
-// Tests that private message loop modes are not pumped while a modal dialog is
-// present.
-TEST(MessagePumpMacTest, ScopedPumpMessagesAttemptWithModalDialog) {
-  MessageLoopForUI message_loop;
-
-  {
-    base::ScopedPumpMessagesInPrivateModes allow_private;
-    // No modal window, so all modes should be pumped.
-    EXPECT_EQ(kAllModesMask, allow_private.GetModeMaskForTest());
-  }
-
-  base::scoped_nsobject<NSAlert> alert([[NSAlert alloc] init]);
-  [alert addButtonWithTitle:@"OK"];
-  base::scoped_nsobject<TestModalAlertCloser> closer(
-      [[TestModalAlertCloser alloc] init]);
-  [closer performSelector:@selector(runTestThenCloseAlert:)
-               withObject:alert
-               afterDelay:0
-                  inModes:@[ NSModalPanelRunLoopMode ]];
-  NSInteger result = [alert runModal];
-  EXPECT_EQ(NSAlertFirstButtonReturn, result);
-}
-
-}  // namespace base
-
-@implementation TestModalAlertCloser
-
-- (void)runTestThenCloseAlert:(NSAlert*)alert {
-  EXPECT_TRUE([NSApp modalWindow]);
-  {
-    base::ScopedPumpMessagesInPrivateModes allow_private;
-    // With a modal window, only safe modes should be pumped.
-    EXPECT_EQ(kNSApplicationModalSafeModeMask,
-              allow_private.GetModeMaskForTest());
-  }
-  [[alert buttons][0] performClick:nil];
-}
-
-@end
diff --git a/base/message_loop/message_pump_perftest.cc b/base/message_loop/message_pump_perftest.cc
deleted file mode 100644
index 8391888..0000000
--- a/base/message_loop/message_pump_perftest.cc
+++ /dev/null
@@ -1,306 +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 <stddef.h>
-#include <stdint.h>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/format_macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/message_loop/message_loop.h"
-#include "base/single_thread_task_runner.h"
-#include "base/strings/stringprintf.h"
-#include "base/synchronization/condition_variable.h"
-#include "base/synchronization/lock.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/threading/thread.h"
-#include "base/time/time.h"
-#include "build_config.h"
-#include "testing/gtest/include/gtest/gtest.h"
-#include "testing/perf/perf_test.h"
-
-#if defined(OS_ANDROID)
-#include "base/android/java_handler_thread.h"
-#endif
-
-namespace base {
-
-class ScheduleWorkTest : public testing::Test {
- public:
-  ScheduleWorkTest() : counter_(0) {}
-
-  void SetUp() override {
-    if (base::ThreadTicks::IsSupported())
-      base::ThreadTicks::WaitUntilInitialized();
-  }
-
-  void Increment(uint64_t amount) { counter_ += amount; }
-
-  void Schedule(int index) {
-    base::TimeTicks start = base::TimeTicks::Now();
-    base::ThreadTicks thread_start;
-    if (ThreadTicks::IsSupported())
-      thread_start = base::ThreadTicks::Now();
-    base::TimeDelta minimum = base::TimeDelta::Max();
-    base::TimeDelta maximum = base::TimeDelta();
-    base::TimeTicks now, lastnow = start;
-    uint64_t schedule_calls = 0u;
-    do {
-      for (size_t i = 0; i < kBatchSize; ++i) {
-        target_message_loop()->ScheduleWork();
-        schedule_calls++;
-      }
-      now = base::TimeTicks::Now();
-      base::TimeDelta laptime = now - lastnow;
-      lastnow = now;
-      minimum = std::min(minimum, laptime);
-      maximum = std::max(maximum, laptime);
-    } while (now - start < base::TimeDelta::FromSeconds(kTargetTimeSec));
-
-    scheduling_times_[index] = now - start;
-    if (ThreadTicks::IsSupported())
-      scheduling_thread_times_[index] =
-          base::ThreadTicks::Now() - thread_start;
-    min_batch_times_[index] = minimum;
-    max_batch_times_[index] = maximum;
-    target_message_loop()->task_runner()->PostTask(
-        FROM_HERE, base::BindOnce(&ScheduleWorkTest::Increment,
-                                  base::Unretained(this), schedule_calls));
-  }
-
-  void ScheduleWork(MessageLoop::Type target_type, int num_scheduling_threads) {
-#if defined(OS_ANDROID)
-    if (target_type == MessageLoop::TYPE_JAVA) {
-      java_thread_.reset(new android::JavaHandlerThread("target"));
-      java_thread_->Start();
-    } else
-#endif
-    {
-      target_.reset(new Thread("target"));
-      target_->StartWithOptions(Thread::Options(target_type, 0u));
-
-      // Without this, it's possible for the scheduling threads to start and run
-      // before the target thread. In this case, the scheduling threads will
-      // call target_message_loop()->ScheduleWork(), which dereferences the
-      // loop's message pump, which is only created after the target thread has
-      // finished starting.
-      target_->WaitUntilThreadStarted();
-    }
-
-    std::vector<std::unique_ptr<Thread>> scheduling_threads;
-    scheduling_times_.reset(new base::TimeDelta[num_scheduling_threads]);
-    scheduling_thread_times_.reset(new base::TimeDelta[num_scheduling_threads]);
-    min_batch_times_.reset(new base::TimeDelta[num_scheduling_threads]);
-    max_batch_times_.reset(new base::TimeDelta[num_scheduling_threads]);
-
-    for (int i = 0; i < num_scheduling_threads; ++i) {
-      scheduling_threads.push_back(std::make_unique<Thread>("posting thread"));
-      scheduling_threads[i]->Start();
-    }
-
-    for (int i = 0; i < num_scheduling_threads; ++i) {
-      scheduling_threads[i]->task_runner()->PostTask(
-          FROM_HERE, base::BindOnce(&ScheduleWorkTest::Schedule,
-                                    base::Unretained(this), i));
-    }
-
-    for (int i = 0; i < num_scheduling_threads; ++i) {
-      scheduling_threads[i]->Stop();
-    }
-#if defined(OS_ANDROID)
-    if (target_type == MessageLoop::TYPE_JAVA) {
-      java_thread_->Stop();
-      java_thread_.reset();
-    } else
-#endif
-    {
-      target_->Stop();
-      target_.reset();
-    }
-    base::TimeDelta total_time;
-    base::TimeDelta total_thread_time;
-    base::TimeDelta min_batch_time = base::TimeDelta::Max();
-    base::TimeDelta max_batch_time = base::TimeDelta();
-    for (int i = 0; i < num_scheduling_threads; ++i) {
-      total_time += scheduling_times_[i];
-      total_thread_time += scheduling_thread_times_[i];
-      min_batch_time = std::min(min_batch_time, min_batch_times_[i]);
-      max_batch_time = std::max(max_batch_time, max_batch_times_[i]);
-    }
-    std::string trace = StringPrintf(
-        "%d_threads_scheduling_to_%s_pump",
-        num_scheduling_threads,
-        target_type == MessageLoop::TYPE_IO
-            ? "io"
-            : (target_type == MessageLoop::TYPE_UI ? "ui" : "default"));
-    perf_test::PrintResult(
-        "task",
-        "",
-        trace,
-        total_time.InMicroseconds() / static_cast<double>(counter_),
-        "us/task",
-        true);
-    perf_test::PrintResult(
-        "task",
-        "_min_batch_time",
-        trace,
-        min_batch_time.InMicroseconds() / static_cast<double>(kBatchSize),
-        "us/task",
-        false);
-    perf_test::PrintResult(
-        "task",
-        "_max_batch_time",
-        trace,
-        max_batch_time.InMicroseconds() / static_cast<double>(kBatchSize),
-        "us/task",
-        false);
-    if (ThreadTicks::IsSupported()) {
-      perf_test::PrintResult(
-          "task",
-          "_thread_time",
-          trace,
-          total_thread_time.InMicroseconds() / static_cast<double>(counter_),
-          "us/task",
-          true);
-    }
-  }
-
-  MessageLoop* target_message_loop() {
-#if defined(OS_ANDROID)
-    if (java_thread_)
-      return java_thread_->message_loop();
-#endif
-    return target_->message_loop();
-  }
-
- private:
-  std::unique_ptr<Thread> target_;
-#if defined(OS_ANDROID)
-  std::unique_ptr<android::JavaHandlerThread> java_thread_;
-#endif
-  std::unique_ptr<base::TimeDelta[]> scheduling_times_;
-  std::unique_ptr<base::TimeDelta[]> scheduling_thread_times_;
-  std::unique_ptr<base::TimeDelta[]> min_batch_times_;
-  std::unique_ptr<base::TimeDelta[]> max_batch_times_;
-  uint64_t counter_;
-
-  static const size_t kTargetTimeSec = 5;
-  static const size_t kBatchSize = 1000;
-};
-
-TEST_F(ScheduleWorkTest, ThreadTimeToIOFromOneThread) {
-  ScheduleWork(MessageLoop::TYPE_IO, 1);
-}
-
-TEST_F(ScheduleWorkTest, ThreadTimeToIOFromTwoThreads) {
-  ScheduleWork(MessageLoop::TYPE_IO, 2);
-}
-
-TEST_F(ScheduleWorkTest, ThreadTimeToIOFromFourThreads) {
-  ScheduleWork(MessageLoop::TYPE_IO, 4);
-}
-
-TEST_F(ScheduleWorkTest, ThreadTimeToUIFromOneThread) {
-  ScheduleWork(MessageLoop::TYPE_UI, 1);
-}
-
-TEST_F(ScheduleWorkTest, ThreadTimeToUIFromTwoThreads) {
-  ScheduleWork(MessageLoop::TYPE_UI, 2);
-}
-
-TEST_F(ScheduleWorkTest, ThreadTimeToUIFromFourThreads) {
-  ScheduleWork(MessageLoop::TYPE_UI, 4);
-}
-
-TEST_F(ScheduleWorkTest, ThreadTimeToDefaultFromOneThread) {
-  ScheduleWork(MessageLoop::TYPE_DEFAULT, 1);
-}
-
-TEST_F(ScheduleWorkTest, ThreadTimeToDefaultFromTwoThreads) {
-  ScheduleWork(MessageLoop::TYPE_DEFAULT, 2);
-}
-
-TEST_F(ScheduleWorkTest, ThreadTimeToDefaultFromFourThreads) {
-  ScheduleWork(MessageLoop::TYPE_DEFAULT, 4);
-}
-
-#if defined(OS_ANDROID)
-TEST_F(ScheduleWorkTest, ThreadTimeToJavaFromOneThread) {
-  ScheduleWork(MessageLoop::TYPE_JAVA, 1);
-}
-
-TEST_F(ScheduleWorkTest, ThreadTimeToJavaFromTwoThreads) {
-  ScheduleWork(MessageLoop::TYPE_JAVA, 2);
-}
-
-TEST_F(ScheduleWorkTest, ThreadTimeToJavaFromFourThreads) {
-  ScheduleWork(MessageLoop::TYPE_JAVA, 4);
-}
-#endif
-
-class FakeMessagePump : public MessagePump {
- public:
-  FakeMessagePump() = default;
-  ~FakeMessagePump() override = default;
-
-  void Run(Delegate* delegate) override {}
-
-  void Quit() override {}
-  void ScheduleWork() override {}
-  void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override {}
-};
-
-class PostTaskTest : public testing::Test {
- public:
-  void Run(int batch_size, int tasks_per_reload) {
-    base::TimeTicks start = base::TimeTicks::Now();
-    base::TimeTicks now;
-    MessageLoop loop(std::unique_ptr<MessagePump>(new FakeMessagePump));
-    scoped_refptr<internal::IncomingTaskQueue> queue(
-        new internal::IncomingTaskQueue(&loop));
-    uint32_t num_posted = 0;
-    do {
-      for (int i = 0; i < batch_size; ++i) {
-        for (int j = 0; j < tasks_per_reload; ++j) {
-          queue->AddToIncomingQueue(FROM_HERE, DoNothing(), base::TimeDelta(),
-                                    Nestable::kNonNestable);
-          num_posted++;
-        }
-        TaskQueue loop_local_queue;
-        queue->ReloadWorkQueue(&loop_local_queue);
-        while (!loop_local_queue.empty()) {
-          PendingTask t = std::move(loop_local_queue.front());
-          loop_local_queue.pop();
-          loop.RunTask(&t);
-        }
-      }
-
-      now = base::TimeTicks::Now();
-    } while (now - start < base::TimeDelta::FromSeconds(5));
-    std::string trace = StringPrintf("%d_tasks_per_reload", tasks_per_reload);
-    perf_test::PrintResult(
-        "task",
-        "",
-        trace,
-        (now - start).InMicroseconds() / static_cast<double>(num_posted),
-        "us/task",
-        true);
-    queue->WillDestroyCurrentMessageLoop();
-  }
-};
-
-TEST_F(PostTaskTest, OneTaskPerReload) {
-  Run(10000, 1);
-}
-
-TEST_F(PostTaskTest, TenTasksPerReload) {
-  Run(10000, 10);
-}
-
-TEST_F(PostTaskTest, OneHundredTasksPerReload) {
-  Run(1000, 100);
-}
-
-}  // namespace base
diff --git a/base/message_loop/message_pump_win.cc b/base/message_loop/message_pump_win.cc
deleted file mode 100644
index d278ffc..0000000
--- a/base/message_loop/message_pump_win.cc
+++ /dev/null
@@ -1,564 +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 "base/message_loop/message_pump_win.h"
-
-#include <math.h>
-#include <stdint.h>
-
-#include <limits>
-
-#include "base/bind.h"
-#include "base/memory/ptr_util.h"
-#include "base/strings/stringprintf.h"
-#include "base/win/current_module.h"
-#include "base/win/wrapped_window_proc.h"
-
-namespace base {
-
-namespace {
-
-enum MessageLoopProblems {
-  MESSAGE_POST_ERROR,
-  COMPLETION_POST_ERROR,
-  SET_TIMER_ERROR,
-  RECEIVED_WM_QUIT_ERROR,
-  MESSAGE_LOOP_PROBLEM_MAX,
-};
-
-}  // namespace
-
-// Message sent to get an additional time slice for pumping (processing) another
-// task (a series of such messages creates a continuous task pump).
-static const int kMsgHaveWork = WM_USER + 1;
-
-//-----------------------------------------------------------------------------
-// MessagePumpWin public:
-
-MessagePumpWin::MessagePumpWin() = default;
-
-void MessagePumpWin::Run(Delegate* delegate) {
-  RunState s;
-  s.delegate = delegate;
-  s.should_quit = false;
-  s.run_depth = state_ ? state_->run_depth + 1 : 1;
-
-  // TODO(stanisc): crbug.com/596190: Remove this code once the bug is fixed.
-  s.schedule_work_error_count = 0;
-  s.last_schedule_work_error_time = Time();
-
-  RunState* previous_state = state_;
-  state_ = &s;
-
-  DoRunLoop();
-
-  state_ = previous_state;
-}
-
-void MessagePumpWin::Quit() {
-  DCHECK(state_);
-  state_->should_quit = true;
-}
-
-//-----------------------------------------------------------------------------
-// MessagePumpWin protected:
-
-int MessagePumpWin::GetCurrentDelay() const {
-  if (delayed_work_time_.is_null())
-    return -1;
-
-  // Be careful here.  TimeDelta has a precision of microseconds, but we want a
-  // value in milliseconds.  If there are 5.5ms left, should the delay be 5 or
-  // 6?  It should be 6 to avoid executing delayed work too early.
-  double timeout =
-      ceil((delayed_work_time_ - TimeTicks::Now()).InMillisecondsF());
-
-  // Range check the |timeout| while converting to an integer.  If the |timeout|
-  // is negative, then we need to run delayed work soon.  If the |timeout| is
-  // "overflowingly" large, that means a delayed task was posted with a
-  // super-long delay.
-  return timeout < 0 ? 0 :
-      (timeout > std::numeric_limits<int>::max() ?
-       std::numeric_limits<int>::max() : static_cast<int>(timeout));
-}
-
-//-----------------------------------------------------------------------------
-// MessagePumpForUI public:
-
-MessagePumpForUI::MessagePumpForUI() {
-  bool succeeded = message_window_.Create(
-      BindRepeating(&MessagePumpForUI::MessageCallback, Unretained(this)));
-  DCHECK(succeeded);
-}
-
-MessagePumpForUI::~MessagePumpForUI() = default;
-
-void MessagePumpForUI::ScheduleWork() {
-  if (InterlockedExchange(&work_state_, HAVE_WORK) != READY)
-    return;  // Someone else continued the pumping.
-
-  // Make sure the MessagePump does some work for us.
-  BOOL ret = PostMessage(message_window_.hwnd(), kMsgHaveWork, 0, 0);
-  if (ret)
-    return;  // There was room in the Window Message queue.
-
-  // We have failed to insert a have-work message, so there is a chance that we
-  // will starve tasks/timers while sitting in a nested run loop.  Nested
-  // loops only look at Windows Message queues, and don't look at *our* task
-  // queues, etc., so we might not get a time slice in such. :-(
-  // We could abort here, but the fear is that this failure mode is plausibly
-  // common (queue is full, of about 2000 messages), so we'll do a near-graceful
-  // recovery.  Nested loops are pretty transient (we think), so this will
-  // probably be recoverable.
-
-  // Clarify that we didn't really insert.
-  InterlockedExchange(&work_state_, READY);
-  state_->schedule_work_error_count++;
-  state_->last_schedule_work_error_time = Time::Now();
-}
-
-void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
-  delayed_work_time_ = delayed_work_time;
-  RescheduleTimer();
-}
-
-//-----------------------------------------------------------------------------
-// MessagePumpForUI private:
-
-bool MessagePumpForUI::MessageCallback(
-    UINT message, WPARAM wparam, LPARAM lparam, LRESULT* result) {
-  switch (message) {
-    case kMsgHaveWork:
-      HandleWorkMessage();
-      break;
-    case WM_TIMER:
-      HandleTimerMessage();
-      break;
-  }
-  return false;
-}
-
-void MessagePumpForUI::DoRunLoop() {
-  // IF this was just a simple PeekMessage() loop (servicing all possible work
-  // queues), then Windows would try to achieve the following order according
-  // to MSDN documentation about PeekMessage with no filter):
-  //    * Sent messages
-  //    * Posted messages
-  //    * Sent messages (again)
-  //    * WM_PAINT messages
-  //    * WM_TIMER messages
-  //
-  // Summary: none of the above classes is starved, and sent messages has twice
-  // the chance of being processed (i.e., reduced service time).
-
-  for (;;) {
-    // If we do any work, we may create more messages etc., and more work may
-    // possibly be waiting in another task group.  When we (for example)
-    // ProcessNextWindowsMessage(), there is a good chance there are still more
-    // messages waiting.  On the other hand, when any of these methods return
-    // having done no work, then it is pretty unlikely that calling them again
-    // quickly will find any work to do.  Finally, if they all say they had no
-    // work, then it is a good time to consider sleeping (waiting) for more
-    // work.
-
-    bool more_work_is_plausible = ProcessNextWindowsMessage();
-    if (state_->should_quit)
-      break;
-
-    more_work_is_plausible |= state_->delegate->DoWork();
-    if (state_->should_quit)
-      break;
-
-    more_work_is_plausible |=
-        state_->delegate->DoDelayedWork(&delayed_work_time_);
-    // If we did not process any delayed work, then we can assume that our
-    // existing WM_TIMER if any will fire when delayed work should run.  We
-    // don't want to disturb that timer if it is already in flight.  However,
-    // if we did do all remaining delayed work, then lets kill the WM_TIMER.
-    if (more_work_is_plausible && delayed_work_time_.is_null())
-      KillTimer(message_window_.hwnd(), reinterpret_cast<UINT_PTR>(this));
-    if (state_->should_quit)
-      break;
-
-    if (more_work_is_plausible)
-      continue;
-
-    more_work_is_plausible = state_->delegate->DoIdleWork();
-    if (state_->should_quit)
-      break;
-
-    if (more_work_is_plausible)
-      continue;
-
-    WaitForWork();  // Wait (sleep) until we have work to do again.
-  }
-}
-
-void MessagePumpForUI::WaitForWork() {
-  // Wait until a message is available, up to the time needed by the timer
-  // manager to fire the next set of timers.
-  int delay;
-  DWORD wait_flags = MWMO_INPUTAVAILABLE;
-
-  while ((delay = GetCurrentDelay()) != 0) {
-    if (delay < 0)  // Negative value means no timers waiting.
-      delay = INFINITE;
-
-    // Tell the optimizer to retain these values to simplify analyzing hangs.
-    DWORD result = MsgWaitForMultipleObjectsEx(0, nullptr, delay, QS_ALLINPUT,
-                                               wait_flags);
-
-    if (WAIT_OBJECT_0 == result) {
-      // A WM_* message is available.
-      // If a parent child relationship exists between windows across threads
-      // then their thread inputs are implicitly attached.
-      // This causes the MsgWaitForMultipleObjectsEx API to return indicating
-      // that messages are ready for processing (Specifically, mouse messages
-      // intended for the child window may appear if the child window has
-      // capture).
-      // The subsequent PeekMessages call may fail to return any messages thus
-      // causing us to enter a tight loop at times.
-      // The code below is a workaround to give the child window
-      // some time to process its input messages by looping back to
-      // MsgWaitForMultipleObjectsEx above when there are no messages for the
-      // current thread.
-      MSG msg = {0};
-      bool has_pending_sent_message =
-          (HIWORD(GetQueueStatus(QS_SENDMESSAGE)) & QS_SENDMESSAGE) != 0;
-      if (has_pending_sent_message ||
-          PeekMessage(&msg, nullptr, 0, 0, PM_NOREMOVE)) {
-        return;
-      }
-
-      // We know there are no more messages for this thread because PeekMessage
-      // has returned false. Reset |wait_flags| so that we wait for a *new*
-      // message.
-      wait_flags = 0;
-    }
-
-    DCHECK_NE(WAIT_FAILED, result) << GetLastError();
-  }
-}
-
-void MessagePumpForUI::HandleWorkMessage() {
-  // If we are being called outside of the context of Run, then don't try to do
-  // any work.  This could correspond to a MessageBox call or something of that
-  // sort.
-  if (!state_) {
-    // Since we handled a kMsgHaveWork message, we must still update this flag.
-    InterlockedExchange(&work_state_, READY);
-    return;
-  }
-
-  // Let whatever would have run had we not been putting messages in the queue
-  // run now.  This is an attempt to make our dummy message not starve other
-  // messages that may be in the Windows message queue.
-  ProcessPumpReplacementMessage();
-
-  // Now give the delegate a chance to do some work.  It'll let us know if it
-  // needs to do more work.
-  if (state_->delegate->DoWork())
-    ScheduleWork();
-  state_->delegate->DoDelayedWork(&delayed_work_time_);
-  RescheduleTimer();
-}
-
-void MessagePumpForUI::HandleTimerMessage() {
-  KillTimer(message_window_.hwnd(), reinterpret_cast<UINT_PTR>(this));
-
-  // If we are being called outside of the context of Run, then don't do
-  // anything.  This could correspond to a MessageBox call or something of
-  // that sort.
-  if (!state_)
-    return;
-
-  state_->delegate->DoDelayedWork(&delayed_work_time_);
-  RescheduleTimer();
-}
-
-void MessagePumpForUI::RescheduleTimer() {
-  if (delayed_work_time_.is_null())
-    return;
-  //
-  // We would *like* to provide high resolution timers.  Windows timers using
-  // SetTimer() have a 10ms granularity.  We have to use WM_TIMER as a wakeup
-  // mechanism because the application can enter modal windows loops where it
-  // is not running our MessageLoop; the only way to have our timers fire in
-  // these cases is to post messages there.
-  //
-  // To provide sub-10ms timers, we process timers directly from our run loop.
-  // For the common case, timers will be processed there as the run loop does
-  // its normal work.  However, we *also* set the system timer so that WM_TIMER
-  // events fire.  This mops up the case of timers not being able to work in
-  // modal message loops.  It is possible for the SetTimer to pop and have no
-  // pending timers, because they could have already been processed by the
-  // run loop itself.
-  //
-  // We use a single SetTimer corresponding to the timer that will expire
-  // soonest.  As new timers are created and destroyed, we update SetTimer.
-  // Getting a spurious SetTimer event firing is benign, as we'll just be
-  // processing an empty timer queue.
-  //
-  int delay_msec = GetCurrentDelay();
-  DCHECK_GE(delay_msec, 0);
-  if (delay_msec == 0) {
-    ScheduleWork();
-  } else {
-    if (delay_msec < USER_TIMER_MINIMUM)
-      delay_msec = USER_TIMER_MINIMUM;
-
-    // Create a WM_TIMER event that will wake us up to check for any pending
-    // timers (in case we are running within a nested, external sub-pump).
-    UINT_PTR ret = SetTimer(message_window_.hwnd(), 0, delay_msec, nullptr);
-    if (ret)
-      return;
-  }
-}
-
-bool MessagePumpForUI::ProcessNextWindowsMessage() {
-  // If there are sent messages in the queue then PeekMessage internally
-  // dispatches the message and returns false. We return true in this
-  // case to ensure that the message loop peeks again instead of calling
-  // MsgWaitForMultipleObjectsEx again.
-  bool sent_messages_in_queue = false;
-  DWORD queue_status = GetQueueStatus(QS_SENDMESSAGE);
-  if (HIWORD(queue_status) & QS_SENDMESSAGE)
-    sent_messages_in_queue = true;
-
-  MSG msg;
-  if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE) != FALSE)
-    return ProcessMessageHelper(msg);
-
-  return sent_messages_in_queue;
-}
-
-bool MessagePumpForUI::ProcessMessageHelper(const MSG& msg) {
-  if (WM_QUIT == msg.message) {
-    // WM_QUIT is the standard way to exit a GetMessage() loop. Our MessageLoop
-    // has its own quit mechanism, so WM_QUIT is unexpected and should be
-    // ignored.
-    return true;
-  }
-
-  // While running our main message pump, we discard kMsgHaveWork messages.
-  if (msg.message == kMsgHaveWork && msg.hwnd == message_window_.hwnd())
-    return ProcessPumpReplacementMessage();
-
-  TranslateMessage(&msg);
-  DispatchMessage(&msg);
-
-  return true;
-}
-
-bool MessagePumpForUI::ProcessPumpReplacementMessage() {
-  // When we encounter a kMsgHaveWork message, this method is called to peek and
-  // process a replacement message. The goal is to make the kMsgHaveWork as non-
-  // intrusive as possible, even though a continuous stream of such messages are
-  // posted. This method carefully peeks a message while there is no chance for
-  // a kMsgHaveWork to be pending, then resets the |have_work_| flag (allowing a
-  // replacement kMsgHaveWork to possibly be posted), and finally dispatches
-  // that peeked replacement. Note that the re-post of kMsgHaveWork may be
-  // asynchronous to this thread!!
-
-  MSG msg;
-  const bool have_message =
-      PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE) != FALSE;
-
-  // Expect no message or a message different than kMsgHaveWork.
-  DCHECK(!have_message || kMsgHaveWork != msg.message ||
-         msg.hwnd != message_window_.hwnd());
-
-  // Since we discarded a kMsgHaveWork message, we must update the flag.
-  int old_work_state_ = InterlockedExchange(&work_state_, READY);
-  DCHECK_EQ(HAVE_WORK, old_work_state_);
-
-  // We don't need a special time slice if we didn't have_message to process.
-  if (!have_message)
-    return false;
-
-  // Guarantee we'll get another time slice in the case where we go into native
-  // windows code.   This ScheduleWork() may hurt performance a tiny bit when
-  // tasks appear very infrequently, but when the event queue is busy, the
-  // kMsgHaveWork events get (percentage wise) rarer and rarer.
-  ScheduleWork();
-  return ProcessMessageHelper(msg);
-}
-
-//-----------------------------------------------------------------------------
-// MessagePumpForIO public:
-
-MessagePumpForIO::IOContext::IOContext() {
-  memset(&overlapped, 0, sizeof(overlapped));
-}
-
-MessagePumpForIO::MessagePumpForIO() {
-  port_.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE, nullptr,
-      reinterpret_cast<ULONG_PTR>(nullptr), 1));
-  DCHECK(port_.IsValid());
-}
-
-MessagePumpForIO::~MessagePumpForIO() = default;
-
-void MessagePumpForIO::ScheduleWork() {
-  if (InterlockedExchange(&work_state_, HAVE_WORK) != READY)
-    return;  // Someone else continued the pumping.
-
-  // Make sure the MessagePump does some work for us.
-  BOOL ret = PostQueuedCompletionStatus(port_.Get(), 0,
-                                        reinterpret_cast<ULONG_PTR>(this),
-                                        reinterpret_cast<OVERLAPPED*>(this));
-  if (ret)
-    return;  // Post worked perfectly.
-
-  // See comment in MessagePumpForUI::ScheduleWork() for this error recovery.
-  InterlockedExchange(&work_state_, READY);  // Clarify that we didn't succeed.
-  state_->schedule_work_error_count++;
-  state_->last_schedule_work_error_time = Time::Now();
-}
-
-void MessagePumpForIO::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
-  // We know that we can't be blocked right now since this method can only be
-  // called on the same thread as Run, so we only need to update our record of
-  // how long to sleep when we do sleep.
-  delayed_work_time_ = delayed_work_time;
-}
-
-void MessagePumpForIO::RegisterIOHandler(HANDLE file_handle,
-                                         IOHandler* handler) {
-  HANDLE port = CreateIoCompletionPort(file_handle, port_.Get(),
-                                       reinterpret_cast<ULONG_PTR>(handler), 1);
-  DPCHECK(port);
-}
-
-bool MessagePumpForIO::RegisterJobObject(HANDLE job_handle,
-                                         IOHandler* handler) {
-  JOBOBJECT_ASSOCIATE_COMPLETION_PORT info;
-  info.CompletionKey = handler;
-  info.CompletionPort = port_.Get();
-  return SetInformationJobObject(job_handle,
-                                 JobObjectAssociateCompletionPortInformation,
-                                 &info,
-                                 sizeof(info)) != FALSE;
-}
-
-//-----------------------------------------------------------------------------
-// MessagePumpForIO private:
-
-void MessagePumpForIO::DoRunLoop() {
-  for (;;) {
-    // If we do any work, we may create more messages etc., and more work may
-    // possibly be waiting in another task group.  When we (for example)
-    // WaitForIOCompletion(), there is a good chance there are still more
-    // messages waiting.  On the other hand, when any of these methods return
-    // having done no work, then it is pretty unlikely that calling them
-    // again quickly will find any work to do.  Finally, if they all say they
-    // had no work, then it is a good time to consider sleeping (waiting) for
-    // more work.
-
-    bool more_work_is_plausible = state_->delegate->DoWork();
-    if (state_->should_quit)
-      break;
-
-    more_work_is_plausible |= WaitForIOCompletion(0, nullptr);
-    if (state_->should_quit)
-      break;
-
-    more_work_is_plausible |=
-        state_->delegate->DoDelayedWork(&delayed_work_time_);
-    if (state_->should_quit)
-      break;
-
-    if (more_work_is_plausible)
-      continue;
-
-    more_work_is_plausible = state_->delegate->DoIdleWork();
-    if (state_->should_quit)
-      break;
-
-    if (more_work_is_plausible)
-      continue;
-
-    WaitForWork();  // Wait (sleep) until we have work to do again.
-  }
-}
-
-// Wait until IO completes, up to the time needed by the timer manager to fire
-// the next set of timers.
-void MessagePumpForIO::WaitForWork() {
-  // We do not support nested IO message loops. This is to avoid messy
-  // recursion problems.
-  DCHECK_EQ(1, state_->run_depth) << "Cannot nest an IO message loop!";
-
-  int timeout = GetCurrentDelay();
-  if (timeout < 0)  // Negative value means no timers waiting.
-    timeout = INFINITE;
-
-  WaitForIOCompletion(timeout, nullptr);
-}
-
-bool MessagePumpForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
-  IOItem item;
-  if (completed_io_.empty() || !MatchCompletedIOItem(filter, &item)) {
-    // We have to ask the system for another IO completion.
-    if (!GetIOItem(timeout, &item))
-      return false;
-
-    if (ProcessInternalIOItem(item))
-      return true;
-  }
-
-  if (filter && item.handler != filter) {
-    // Save this item for later
-    completed_io_.push_back(item);
-  } else {
-    item.handler->OnIOCompleted(item.context, item.bytes_transfered,
-                                item.error);
-  }
-  return true;
-}
-
-// Asks the OS for another IO completion result.
-bool MessagePumpForIO::GetIOItem(DWORD timeout, IOItem* item) {
-  memset(item, 0, sizeof(*item));
-  ULONG_PTR key = reinterpret_cast<ULONG_PTR>(nullptr);
-  OVERLAPPED* overlapped = nullptr;
-  if (!GetQueuedCompletionStatus(port_.Get(), &item->bytes_transfered, &key,
-                                 &overlapped, timeout)) {
-    if (!overlapped)
-      return false;  // Nothing in the queue.
-    item->error = GetLastError();
-    item->bytes_transfered = 0;
-  }
-
-  item->handler = reinterpret_cast<IOHandler*>(key);
-  item->context = reinterpret_cast<IOContext*>(overlapped);
-  return true;
-}
-
-bool MessagePumpForIO::ProcessInternalIOItem(const IOItem& item) {
-  if (reinterpret_cast<void*>(this) == reinterpret_cast<void*>(item.context) &&
-      reinterpret_cast<void*>(this) == reinterpret_cast<void*>(item.handler)) {
-    // This is our internal completion.
-    DCHECK(!item.bytes_transfered);
-    InterlockedExchange(&work_state_, READY);
-    return true;
-  }
-  return false;
-}
-
-// Returns a completion item that was previously received.
-bool MessagePumpForIO::MatchCompletedIOItem(IOHandler* filter, IOItem* item) {
-  DCHECK(!completed_io_.empty());
-  for (std::list<IOItem>::iterator it = completed_io_.begin();
-       it != completed_io_.end(); ++it) {
-    if (!filter || it->handler == filter) {
-      *item = *it;
-      completed_io_.erase(it);
-      return true;
-    }
-  }
-  return false;
-}
-
-}  // namespace base
diff --git a/base/message_loop/message_pump_win.h b/base/message_loop/message_pump_win.h
deleted file mode 100644
index f8a8557..0000000
--- a/base/message_loop/message_pump_win.h
+++ /dev/null
@@ -1,254 +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_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_
-#define BASE_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_
-
-#include <windows.h>
-
-#include <list>
-#include <memory>
-
-#include "base/base_export.h"
-#include "base/message_loop/message_pump.h"
-#include "base/time/time.h"
-#include "base/win/message_window.h"
-#include "base/win/scoped_handle.h"
-
-namespace base {
-
-// MessagePumpWin serves as the base for specialized versions of the MessagePump
-// for Windows. It provides basic functionality like handling of observers and
-// controlling the lifetime of the message pump.
-class BASE_EXPORT MessagePumpWin : public MessagePump {
- public:
-  MessagePumpWin();
-
-  // MessagePump methods:
-  void Run(Delegate* delegate) override;
-  void Quit() override;
-
- protected:
-  struct RunState {
-    Delegate* delegate;
-
-    // Used to flag that the current Run() invocation should return ASAP.
-    bool should_quit;
-
-    // Used to count how many Run() invocations are on the stack.
-    int run_depth;
-
-    // Used to help diagnose hangs.
-    // TODO(stanisc): crbug.com/596190: Remove these once the bug is fixed.
-    int schedule_work_error_count;
-    Time last_schedule_work_error_time;
-  };
-
-  // State used with |work_state_| variable.
-  enum WorkState {
-    READY = 0,      // Ready to accept new work.
-    HAVE_WORK = 1,  // New work has been signalled.
-    WORKING = 2     // Handling the work.
-  };
-
-  virtual void DoRunLoop() = 0;
-  int GetCurrentDelay() const;
-
-  // The time at which delayed work should run.
-  TimeTicks delayed_work_time_;
-
-  // A value used to indicate if there is a kMsgDoWork message pending
-  // in the Windows Message queue.  There is at most one such message, and it
-  // can drive execution of tasks when a native message pump is running.
-  LONG work_state_ = READY;
-
-  // State for the current invocation of Run.
-  RunState* state_ = nullptr;
-};
-
-//-----------------------------------------------------------------------------
-// MessagePumpForUI extends MessagePumpWin with methods that are particular to a
-// MessageLoop instantiated with TYPE_UI.
-//
-// MessagePumpForUI implements a "traditional" Windows message pump. It contains
-// a nearly infinite loop that peeks out messages, and then dispatches them.
-// Intermixed with those peeks are callouts to DoWork for pending tasks, and
-// DoDelayedWork for pending timers. When there are no events to be serviced,
-// this pump goes into a wait state. In most cases, this message pump handles
-// all processing.
-//
-// However, when a task, or windows event, invokes on the stack a native dialog
-// box or such, that window typically provides a bare bones (native?) message
-// pump.  That bare-bones message pump generally supports little more than a
-// peek of the Windows message queue, followed by a dispatch of the peeked
-// message.  MessageLoop extends that bare-bones message pump to also service
-// Tasks, at the cost of some complexity.
-//
-// The basic structure of the extension (referred to as a sub-pump) is that a
-// special message, kMsgHaveWork, is repeatedly injected into the Windows
-// Message queue.  Each time the kMsgHaveWork message is peeked, checks are
-// made for an extended set of events, including the availability of Tasks to
-// run.
-//
-// After running a task, the special message kMsgHaveWork is again posted to
-// the Windows Message queue, ensuring a future time slice for processing a
-// future event.  To prevent flooding the Windows Message queue, care is taken
-// to be sure that at most one kMsgHaveWork message is EVER pending in the
-// Window's Message queue.
-//
-// There are a few additional complexities in this system where, when there are
-// no Tasks to run, this otherwise infinite stream of messages which drives the
-// sub-pump is halted.  The pump is automatically re-started when Tasks are
-// queued.
-//
-// A second complexity is that the presence of this stream of posted tasks may
-// prevent a bare-bones message pump from ever peeking a WM_PAINT or WM_TIMER.
-// Such paint and timer events always give priority to a posted message, such as
-// kMsgHaveWork messages.  As a result, care is taken to do some peeking in
-// between the posting of each kMsgHaveWork message (i.e., after kMsgHaveWork
-// is peeked, and before a replacement kMsgHaveWork is posted).
-//
-// NOTE: Although it may seem odd that messages are used to start and stop this
-// flow (as opposed to signaling objects, etc.), it should be understood that
-// the native message pump will *only* respond to messages.  As a result, it is
-// an excellent choice.  It is also helpful that the starter messages that are
-// placed in the queue when new task arrive also awakens DoRunLoop.
-//
-class BASE_EXPORT MessagePumpForUI : public MessagePumpWin {
- public:
-  MessagePumpForUI();
-  ~MessagePumpForUI() override;
-
-  // MessagePump methods:
-  void ScheduleWork() override;
-  void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
-
- private:
-  bool MessageCallback(
-      UINT message, WPARAM wparam, LPARAM lparam, LRESULT* result);
-  void DoRunLoop() override;
-  void WaitForWork();
-  void HandleWorkMessage();
-  void HandleTimerMessage();
-  void RescheduleTimer();
-  bool ProcessNextWindowsMessage();
-  bool ProcessMessageHelper(const MSG& msg);
-  bool ProcessPumpReplacementMessage();
-
-  base::win::MessageWindow message_window_;
-};
-
-//-----------------------------------------------------------------------------
-// MessagePumpForIO extends MessagePumpWin with methods that are particular to a
-// MessageLoop instantiated with TYPE_IO. This version of MessagePump does not
-// deal with Windows mesagges, and instead has a Run loop based on Completion
-// Ports so it is better suited for IO operations.
-//
-class BASE_EXPORT MessagePumpForIO : public MessagePumpWin {
- public:
-  struct BASE_EXPORT IOContext {
-    IOContext();
-    OVERLAPPED overlapped;
-  };
-
-  // Clients interested in receiving OS notifications when asynchronous IO
-  // operations complete should implement this interface and register themselves
-  // with the message pump.
-  //
-  // Typical use #1:
-  //   class MyFile : public IOHandler {
-  //     MyFile() {
-  //       ...
-  //       message_pump->RegisterIOHandler(file_, this);
-  //     }
-  //     // Plus some code to make sure that this destructor is not called
-  //     // while there are pending IO operations.
-  //     ~MyFile() {
-  //     }
-  //     virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
-  //                                DWORD error) {
-  //       ...
-  //       delete context;
-  //     }
-  //     void DoSomeIo() {
-  //       ...
-  //       IOContext* context = new IOContext;
-  //       ReadFile(file_, buffer, num_bytes, &read, &context);
-  //     }
-  //     HANDLE file_;
-  //   };
-  //
-  // Typical use #2:
-  // Same as the previous example, except that in order to deal with the
-  // requirement stated for the destructor, the class calls WaitForIOCompletion
-  // from the destructor to block until all IO finishes.
-  //     ~MyFile() {
-  //       while(pending_)
-  //         message_pump->WaitForIOCompletion(INFINITE, this);
-  //     }
-  //
-  class IOHandler {
-   public:
-    virtual ~IOHandler() {}
-    // This will be called once the pending IO operation associated with
-    // |context| completes. |error| is the Win32 error code of the IO operation
-    // (ERROR_SUCCESS if there was no error). |bytes_transfered| will be zero
-    // on error.
-    virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
-                               DWORD error) = 0;
-  };
-
-  MessagePumpForIO();
-  ~MessagePumpForIO() override;
-
-  // MessagePump methods:
-  void ScheduleWork() override;
-  void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
-
-  // Register the handler to be used when asynchronous IO for the given file
-  // completes. The registration persists as long as |file_handle| is valid, so
-  // |handler| must be valid as long as there is pending IO for the given file.
-  void RegisterIOHandler(HANDLE file_handle, IOHandler* handler);
-
-  // Register the handler to be used to process job events. The registration
-  // persists as long as the job object is live, so |handler| must be valid
-  // until the job object is destroyed. Returns true if the registration
-  // succeeded, and false otherwise.
-  bool RegisterJobObject(HANDLE job_handle, IOHandler* handler);
-
-  // Waits for the next IO completion that should be processed by |filter|, for
-  // up to |timeout| milliseconds. Return true if any IO operation completed,
-  // regardless of the involved handler, and false if the timeout expired. If
-  // the completion port received any message and the involved IO handler
-  // matches |filter|, the callback is called before returning from this code;
-  // if the handler is not the one that we are looking for, the callback will
-  // be postponed for another time, so reentrancy problems can be avoided.
-  // External use of this method should be reserved for the rare case when the
-  // caller is willing to allow pausing regular task dispatching on this thread.
-  bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
-
- private:
-  struct IOItem {
-    IOHandler* handler;
-    IOContext* context;
-    DWORD bytes_transfered;
-    DWORD error;
-  };
-
-  void DoRunLoop() override;
-  void WaitForWork();
-  bool MatchCompletedIOItem(IOHandler* filter, IOItem* item);
-  bool GetIOItem(DWORD timeout, IOItem* item);
-  bool ProcessInternalIOItem(const IOItem& item);
-
-  // The completion port associated with this thread.
-  win::ScopedHandle port_;
-  // This list will be empty almost always. It stores IO completions that have
-  // not been delivered yet because somebody was doing cleanup.
-  std::list<IOItem> completed_io_;
-};
-
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_MESSAGE_PUMP_WIN_H_
diff --git a/base/message_loop/timer_slack.h b/base/message_loop/timer_slack.h
deleted file mode 100644
index 1ad6ca9..0000000
--- a/base/message_loop/timer_slack.h
+++ /dev/null
@@ -1,22 +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.
-
-#ifndef BASE_MESSAGE_LOOP_TIMER_SLACK_H_
-#define BASE_MESSAGE_LOOP_TIMER_SLACK_H_
-
-namespace base {
-
-// Amount of timer slack to use for delayed timers.  Increasing timer slack
-// allows the OS to coalesce timers more effectively.
-enum TimerSlack {
-  // Lowest value for timer slack allowed by OS.
-  TIMER_SLACK_NONE,
-
-  // Maximal value for timer slack allowed by OS.
-  TIMER_SLACK_MAXIMUM
-};
-
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_TIMER_SLACK_H_
diff --git a/base/message_loop/watchable_io_message_pump_posix.cc b/base/message_loop/watchable_io_message_pump_posix.cc
deleted file mode 100644
index 1850137..0000000
--- a/base/message_loop/watchable_io_message_pump_posix.cc
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2018 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/message_loop/watchable_io_message_pump_posix.h"
-
-namespace base {
-
-WatchableIOMessagePumpPosix::FdWatchControllerInterface::
-    FdWatchControllerInterface(const Location& from_here)
-    : created_from_location_(from_here) {}
-
-WatchableIOMessagePumpPosix::FdWatchControllerInterface::
-    ~FdWatchControllerInterface() = default;
-
-}  // namespace base
diff --git a/base/message_loop/watchable_io_message_pump_posix.h b/base/message_loop/watchable_io_message_pump_posix.h
deleted file mode 100644
index 74583d9..0000000
--- a/base/message_loop/watchable_io_message_pump_posix.h
+++ /dev/null
@@ -1,88 +0,0 @@
-// Copyright 2018 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_MESSAGE_LOOP_WATCHABLE_IO_MESSAGE_PUMP_POSIX_H_
-#define BASE_MESSAGE_LOOP_WATCHABLE_IO_MESSAGE_PUMP_POSIX_H_
-
-#include "base/location.h"
-#include "base/macros.h"
-
-namespace base {
-
-class WatchableIOMessagePumpPosix {
- public:
-  // Used with WatchFileDescriptor to asynchronously monitor the I/O readiness
-  // of a file descriptor.
-  class FdWatcher {
-   public:
-    virtual void OnFileCanReadWithoutBlocking(int fd) = 0;
-    virtual void OnFileCanWriteWithoutBlocking(int fd) = 0;
-
-   protected:
-    virtual ~FdWatcher() = default;
-  };
-
-  class FdWatchControllerInterface {
-   public:
-    explicit FdWatchControllerInterface(const Location& from_here);
-    // Subclasses must call StopWatchingFileDescriptor() in their destructor
-    // (this parent class cannot generically do it for them as it must usually
-    // be invoked before they destroy their state which happens before the
-    // parent destructor is invoked).
-    virtual ~FdWatchControllerInterface();
-
-    // NOTE: This method isn't called StopWatching() to avoid confusion with the
-    // win32 ObjectWatcher class. While this doesn't really need to be virtual
-    // as there's only one impl per platform and users don't use pointers to the
-    // base class. Having this interface forces implementers to share similar
-    // implementations (a problem in the past).
-
-    // Stop watching the FD, always safe to call.  No-op if there's nothing to
-    // do.
-    virtual bool StopWatchingFileDescriptor() = 0;
-
-    const Location& created_from_location() const {
-      return created_from_location_;
-    }
-
-   private:
-    const Location created_from_location_;
-
-    DISALLOW_COPY_AND_ASSIGN(FdWatchControllerInterface);
-  };
-
-  enum Mode {
-    WATCH_READ = 1 << 0,
-    WATCH_WRITE = 1 << 1,
-    WATCH_READ_WRITE = WATCH_READ | WATCH_WRITE
-  };
-
-  // Every subclass of WatchableIOMessagePumpPosix must provide a
-  // WatchFileDescriptor() which has the following signature where
-  // |FdWatchController| must be the complete type based on
-  // FdWatchControllerInterface.
-
-  // Registers |delegate| with the current thread's message loop so that its
-  // methods are invoked when file descriptor |fd| becomes ready for reading or
-  // writing (or both) without blocking.  |mode| selects ready for reading, for
-  // writing, or both.  See "enum Mode" above.  |controller| manages the
-  // lifetime of registrations. ("Registrations" are also ambiguously called
-  // "events" in many places, for instance in libevent.)  It is an error to use
-  // the same |controller| for different file descriptors; however, the same
-  // controller can be reused to add registrations with a different |mode|.  If
-  // |controller| is already attached to one or more registrations, the new
-  // registration is added onto those.  If an error occurs while calling this
-  // method, any registration previously attached to |controller| is removed.
-  // Returns true on success.  Must be called on the same thread the MessagePump
-  // is running on.
-  // bool WatchFileDescriptor(int fd,
-  //                          bool persistent,
-  //                          int mode,
-  //                          FdWatchController* controller,
-  //                          FdWatcher* delegate) = 0;
-};
-
-}  // namespace base
-
-#endif  // BASE_MESSAGE_LOOP_WATCHABLE_IO_MESSAGE_PUMP_POSIX_H_
diff --git a/base/observer_list_threadsafe.cc b/base/observer_list_threadsafe.cc
deleted file mode 100644
index 95c852f..0000000
--- a/base/observer_list_threadsafe.cc
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2017 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/observer_list_threadsafe.h"
-
-namespace base {
-namespace internal {
-
-LazyInstance<ThreadLocalPointer<
-    const ObserverListThreadSafeBase::NotificationDataBase>>::Leaky
-    ObserverListThreadSafeBase::tls_current_notification_ =
-        LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/pending_task.cc b/base/pending_task.cc
deleted file mode 100644
index 50924fd..0000000
--- a/base/pending_task.cc
+++ /dev/null
@@ -1,41 +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 "base/pending_task.h"
-
-
-namespace base {
-
-PendingTask::PendingTask(const Location& posted_from,
-                         OnceClosure task,
-                         TimeTicks delayed_run_time,
-                         Nestable nestable)
-    : task(std::move(task)),
-      posted_from(posted_from),
-      delayed_run_time(delayed_run_time),
-      nestable(nestable) {}
-
-PendingTask::PendingTask(PendingTask&& other) = default;
-
-PendingTask::~PendingTask() = default;
-
-PendingTask& PendingTask::operator=(PendingTask&& other) = default;
-
-bool PendingTask::operator<(const PendingTask& other) const {
-  // Since the top of a priority queue is defined as the "greatest" element, we
-  // need to invert the comparison here.  We want the smaller time to be at the
-  // top of the heap.
-
-  if (delayed_run_time < other.delayed_run_time)
-    return false;
-
-  if (delayed_run_time > other.delayed_run_time)
-    return true;
-
-  // If the times happen to match, then we use the sequence number to decide.
-  // Compare the difference to support integer roll-over.
-  return (sequence_num - other.sequence_num) > 0;
-}
-
-}  // namespace base
diff --git a/base/pending_task.h b/base/pending_task.h
deleted file mode 100644
index 495015b..0000000
--- a/base/pending_task.h
+++ /dev/null
@@ -1,68 +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_PENDING_TASK_H_
-#define BASE_PENDING_TASK_H_
-
-#include <array>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/containers/queue.h"
-#include "base/location.h"
-#include "base/time/time.h"
-
-namespace base {
-
-enum class Nestable {
-  kNonNestable,
-  kNestable,
-};
-
-// Contains data about a pending task. Stored in TaskQueue and DelayedTaskQueue
-// for use by classes that queue and execute tasks.
-struct BASE_EXPORT PendingTask {
-  PendingTask(const Location& posted_from,
-              OnceClosure task,
-              TimeTicks delayed_run_time = TimeTicks(),
-              Nestable nestable = Nestable::kNestable);
-  PendingTask(PendingTask&& other);
-  ~PendingTask();
-
-  PendingTask& operator=(PendingTask&& other);
-
-  // Used to support sorting.
-  bool operator<(const PendingTask& other) const;
-
-  // The task to run.
-  OnceClosure task;
-
-  // The site this PendingTask was posted from.
-  Location posted_from;
-
-  // The time when the task should be run.
-  base::TimeTicks delayed_run_time;
-
-  // Task backtrace. mutable so it can be set while annotating const PendingTask
-  // objects from TaskAnnotator::DidQueueTask().
-  mutable std::array<const void*, 4> task_backtrace = {};
-
-  // Secondary sort key for run time.
-  int sequence_num = 0;
-
-  // OK to dispatch from a nested loop.
-  Nestable nestable;
-
-  // Needs high resolution timers.
-  bool is_high_res = false;
-};
-
-using TaskQueue = base::queue<PendingTask>;
-
-// PendingTasks are sorted by their |delayed_run_time| property.
-using DelayedTaskQueue = std::priority_queue<base::PendingTask>;
-
-}  // namespace base
-
-#endif  // BASE_PENDING_TASK_H_
diff --git a/base/posix/global_descriptors.cc b/base/posix/global_descriptors.cc
deleted file mode 100644
index 738d14e..0000000
--- a/base/posix/global_descriptors.cc
+++ /dev/null
@@ -1,101 +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 "base/posix/global_descriptors.h"
-
-#include <vector>
-#include <utility>
-
-#include "base/logging.h"
-
-namespace base {
-
-GlobalDescriptors::Descriptor::Descriptor(Key key, int fd)
-    : key(key), fd(fd), region(base::MemoryMappedFile::Region::kWholeFile) {
-}
-
-GlobalDescriptors::Descriptor::Descriptor(Key key,
-                                          int fd,
-                                          base::MemoryMappedFile::Region region)
-    : key(key), fd(fd), region(region) {
-}
-
-// static
-GlobalDescriptors* GlobalDescriptors::GetInstance() {
-  typedef Singleton<base::GlobalDescriptors,
-                    LeakySingletonTraits<base::GlobalDescriptors> >
-      GlobalDescriptorsSingleton;
-  return GlobalDescriptorsSingleton::get();
-}
-
-int GlobalDescriptors::Get(Key key) const {
-  const int ret = MaybeGet(key);
-
-  if (ret == -1)
-    DLOG(DCHECK) << "Unknown global descriptor: " << key;
-  return ret;
-}
-
-int GlobalDescriptors::MaybeGet(Key key) const {
-  for (Mapping::const_iterator
-       i = descriptors_.begin(); i != descriptors_.end(); ++i) {
-    if (i->key == key)
-      return i->fd;
-  }
-
-  return -1;
-}
-
-base::ScopedFD GlobalDescriptors::TakeFD(
-    Key key,
-    base::MemoryMappedFile::Region* region) {
-  base::ScopedFD fd;
-  for (Mapping::iterator i = descriptors_.begin(); i != descriptors_.end();
-       ++i) {
-    if (i->key == key) {
-      *region = i->region;
-      fd.reset(i->fd);
-      descriptors_.erase(i);
-      break;
-    }
-  }
-  return fd;
-}
-
-void GlobalDescriptors::Set(Key key, int fd) {
-  Set(key, fd, base::MemoryMappedFile::Region::kWholeFile);
-}
-
-void GlobalDescriptors::Set(Key key,
-                            int fd,
-                            base::MemoryMappedFile::Region region) {
-  for (auto& i : descriptors_) {
-    if (i.key == key) {
-      i.fd = fd;
-      i.region = region;
-      return;
-    }
-  }
-
-  descriptors_.push_back(Descriptor(key, fd, region));
-}
-
-base::MemoryMappedFile::Region GlobalDescriptors::GetRegion(Key key) const {
-  for (const auto& i : descriptors_) {
-    if (i.key == key)
-      return i.region;
-  }
-  DLOG(DCHECK) << "Unknown global descriptor: " << key;
-  return base::MemoryMappedFile::Region::kWholeFile;
-}
-
-void GlobalDescriptors::Reset(const Mapping& mapping) {
-  descriptors_ = mapping;
-}
-
-GlobalDescriptors::GlobalDescriptors() = default;
-
-GlobalDescriptors::~GlobalDescriptors() = default;
-
-}  // namespace base
diff --git a/base/posix/global_descriptors.h b/base/posix/global_descriptors.h
deleted file mode 100644
index 1afd12f..0000000
--- a/base/posix/global_descriptors.h
+++ /dev/null
@@ -1,98 +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_POSIX_GLOBAL_DESCRIPTORS_H_
-#define BASE_POSIX_GLOBAL_DESCRIPTORS_H_
-
-#include "build_config.h"
-
-#include <vector>
-#include <utility>
-
-#include <stdint.h>
-
-#include "base/files/memory_mapped_file.h"
-#include "base/files/scoped_file.h"
-#include "base/memory/singleton.h"
-
-namespace base {
-
-// It's common practice to install file descriptors into well known slot
-// numbers before execing a child; stdin, stdout and stderr are ubiqutous
-// examples.
-//
-// However, when using a zygote model, this becomes troublesome. Since the
-// descriptors which need to be in these slots generally aren't known, any code
-// could open a resource and take one of the reserved descriptors. Simply
-// overwriting the slot isn't a viable solution.
-//
-// We could try to fill the reserved slots as soon as possible, but this is a
-// fragile solution since global constructors etc are able to open files.
-//
-// Instead, we retreat from the idea of installing descriptors in specific
-// slots and add a layer of indirection in the form of this singleton object.
-// It maps from an abstract key to a descriptor. If independent modules each
-// need to define keys, then values should be chosen randomly so as not to
-// collide.
-//
-// Note that this class is deprecated and passing file descriptor should ideally
-// be done through the command line and using FileDescriptorStore.
-// See https://crbugs.com/detail?id=692619
-class BASE_EXPORT GlobalDescriptors {
- public:
-  typedef uint32_t Key;
-  struct Descriptor {
-    Descriptor(Key key, int fd);
-    Descriptor(Key key, int fd, base::MemoryMappedFile::Region region);
-
-    // Globally unique key.
-    Key key;
-    // Actual FD.
-    int fd;
-    // Optional region, defaults to kWholeFile.
-    base::MemoryMappedFile::Region region;
-  };
-  typedef std::vector<Descriptor> Mapping;
-
-  // Often we want a canonical descriptor for a given Key. In this case, we add
-  // the following constant to the key value:
-  static const int kBaseDescriptor = 3;  // 0, 1, 2 are already taken.
-
-  // Return the singleton instance of GlobalDescriptors.
-  static GlobalDescriptors* GetInstance();
-
-  // Get a descriptor given a key. It is a fatal error if the key is not known.
-  int Get(Key key) const;
-
-  // Get a descriptor given a key. Returns -1 on error.
-  int MaybeGet(Key key) const;
-
-  // Returns a descriptor given a key and removes it from this class mappings.
-  // Also populates |region|.
-  // It is a fatal error if the key is not known.
-  base::ScopedFD TakeFD(Key key, base::MemoryMappedFile::Region* region);
-
-  // Get a region given a key. It is a fatal error if the key is not known.
-  base::MemoryMappedFile::Region GetRegion(Key key) const;
-
-  // Set the descriptor for the given |key|. This sets the region associated
-  // with |key| to kWholeFile.
-  void Set(Key key, int fd);
-
-  // Set the descriptor and |region| for the given |key|.
-  void Set(Key key, int fd, base::MemoryMappedFile::Region region);
-
-  void Reset(const Mapping& mapping);
-
- private:
-  friend struct DefaultSingletonTraits<GlobalDescriptors>;
-  GlobalDescriptors();
-  ~GlobalDescriptors();
-
-  Mapping descriptors_;
-};
-
-}  // namespace base
-
-#endif  // BASE_POSIX_GLOBAL_DESCRIPTORS_H_
diff --git a/base/process/internal_linux.cc b/base/process/internal_linux.cc
index 7f38fff..c551502 100644
--- a/base/process/internal_linux.cc
+++ b/base/process/internal_linux.cc
@@ -16,7 +16,6 @@
 #include "base/strings/string_number_conversions.h"
 #include "base/strings/string_split.h"
 #include "base/strings/string_util.h"
-#include "base/threading/thread_restrictions.h"
 #include "base/time/time.h"
 
 // Not defined on AIX by default.
@@ -57,9 +56,6 @@
 
 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;
diff --git a/base/process/kill.cc b/base/process/kill.cc
index 0332ac0..f73266d 100644
--- a/base/process/kill.cc
+++ b/base/process/kill.cc
@@ -6,7 +6,6 @@
 
 #include "base/bind.h"
 #include "base/process/process_iterator.h"
-#include "base/task_scheduler/post_task.h"
 #include "base/time/time.h"
 
 namespace base {
@@ -31,31 +30,4 @@
   return result;
 }
 
-#if defined(OS_WIN) || defined(OS_FUCHSIA)
-// Common implementation for platforms under which |process| is a handle to
-// the process, rather than an identifier that must be "reaped".
-void EnsureProcessTerminated(Process process) {
-  DCHECK(!process.is_current());
-
-  if (process.WaitForExitWithTimeout(TimeDelta(), nullptr))
-    return;
-
-  PostDelayedTaskWithTraits(
-      FROM_HERE,
-      {TaskPriority::BACKGROUND, TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
-      BindOnce(
-          [](Process process) {
-            if (process.WaitForExitWithTimeout(TimeDelta(), nullptr))
-              return;
-#if defined(OS_WIN)
-            process.Terminate(win::kProcessKilledExitCode, false);
-#else
-            process.Terminate(-1, false);
-#endif
-          },
-          std::move(process)),
-      TimeDelta::FromSeconds(2));
-}
-#endif  // defined(OS_WIN) || defined(OS_FUCHSIA)
-
 }  // namespace base
diff --git a/base/process/kill.h b/base/process/kill.h
index a3a7c63..03c057c 100644
--- a/base/process/kill.h
+++ b/base/process/kill.h
@@ -118,14 +118,6 @@
 #endif  // defined(OS_LINUX)
 #endif  // defined(OS_POSIX) && !defined(OS_FUCHSIA)
 
-// Registers |process| to be asynchronously monitored for termination, forcibly
-// terminated if necessary, and reaped on exit. The caller should have signalled
-// |process| to exit before calling this API. The API will allow a couple of
-// seconds grace period before forcibly terminating |process|.
-// TODO(https://crbug.com/806451): The Mac implementation currently blocks the
-// calling thread for up to two seconds.
-BASE_EXPORT void EnsureProcessTerminated(Process process);
-
 // These are only sparingly used, and not needed on Fuchsia. They could be
 // implemented if necessary.
 #if !defined(OS_FUCHSIA)
diff --git a/base/process/kill_mac.cc b/base/process/kill_mac.cc
deleted file mode 100644
index 0110c90..0000000
--- a/base/process/kill_mac.cc
+++ /dev/null
@@ -1,173 +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/kill.h"
-
-#include <errno.h>
-#include <signal.h>
-#include <sys/event.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-
-#include "base/files/file_util.h"
-#include "base/files/scoped_file.h"
-#include "base/logging.h"
-#include "base/posix/eintr_wrapper.h"
-
-namespace base {
-
-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_GT(child, 0);
-  DCHECK_GT(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(Process process) {
-  WaitForChildToDie(process.Pid(), kWaitBeforeKillSeconds);
-}
-
-}  // namespace base
diff --git a/base/process/kill_posix.cc b/base/process/kill_posix.cc
index 7d75095..4027c6f 100644
--- a/base/process/kill_posix.cc
+++ b/base/process/kill_posix.cc
@@ -15,7 +15,6 @@
 #include "base/macros.h"
 #include "base/posix/eintr_wrapper.h"
 #include "base/process/process_iterator.h"
-#include "base/task_scheduler/post_task.h"
 #include "base/threading/platform_thread.h"
 #include "build_config.h"
 
diff --git a/base/process/launch_mac.cc b/base/process/launch_mac.cc
index 06dbb99..d9a24cc 100644
--- a/base/process/launch_mac.cc
+++ b/base/process/launch_mac.cc
@@ -12,7 +12,6 @@
 
 #include "base/logging.h"
 #include "base/posix/eintr_wrapper.h"
-#include "base/threading/thread_restrictions.h"
 
 namespace base {
 
@@ -167,9 +166,6 @@
   }
 
   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.
-    base::AssertBlockingAllowed();
     pid_t ret = HANDLE_EINTR(waitpid(pid, nullptr, 0));
     DPCHECK(ret > 0);
   }
diff --git a/base/process/launch_posix.cc b/base/process/launch_posix.cc
index fc9d188..454b2cb 100644
--- a/base/process/launch_posix.cc
+++ b/base/process/launch_posix.cc
@@ -38,7 +38,6 @@
 #include "base/strings/stringprintf.h"
 #include "base/synchronization/waitable_event.h"
 #include "base/threading/platform_thread.h"
-#include "base/threading/thread_restrictions.h"
 #include "base/time/time.h"
 #include "build_config.h"
 
@@ -512,9 +511,6 @@
   } 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.
-      base::AssertBlockingAllowed();
       pid_t ret = HANDLE_EINTR(waitpid(pid, nullptr, 0));
       DPCHECK(ret > 0);
     }
@@ -545,7 +541,6 @@
     std::string* output,
     bool do_search_path,
     int* exit_code) {
-  base::AssertBlockingAllowed();
   // exit_code must be supplied so calling function can determine success.
   DCHECK(exit_code);
   *exit_code = EXIT_FAILURE;
diff --git a/base/process/launch_win.cc b/base/process/launch_win.cc
index 839db17..f24b6dd 100644
--- a/base/process/launch_win.cc
+++ b/base/process/launch_win.cc
@@ -20,7 +20,6 @@
 #include "base/logging.h"
 #include "base/process/kill.h"
 #include "base/strings/utf_string_conversions.h"
-#include "base/sys_info.h"
 #include "base/win/scoped_handle.h"
 #include "base/win/scoped_process_information.h"
 #include "base/win/startup_information.h"
diff --git a/base/process/process_iterator_linux.cc b/base/process/process_iterator_linux.cc
index 9fea70e..a7b0b05 100644
--- a/base/process/process_iterator_linux.cc
+++ b/base/process/process_iterator_linux.cc
@@ -11,7 +11,6 @@
 #include "base/process/internal_linux.h"
 #include "base/strings/string_split.h"
 #include "base/strings/string_util.h"
-#include "base/threading/thread_restrictions.h"
 
 namespace base {
 
@@ -42,9 +41,6 @@
 // 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))
diff --git a/base/process/process_linux.cc b/base/process/process_linux.cc
index 8cfeef2..173daf9 100644
--- a/base/process/process_linux.cc
+++ b/base/process/process_linux.cc
@@ -13,7 +13,6 @@
 #include "base/strings/string_split.h"
 #include "base/strings/stringprintf.h"
 #include "base/synchronization/lock.h"
-#include "base/threading/thread_restrictions.h"
 #include "build_config.h"
 
 // Not defined on AIX by default.
@@ -100,8 +99,6 @@
 
 #if defined(OS_CHROMEOS)
   if (CGroups::Get().enabled) {
-    // Used to allow reading the process priority from proc on thread launch.
-    base::ThreadRestrictions::ScopedAllowIO allow_io;
     std::string proc;
     if (base::ReadFileToString(
             base::FilePath(StringPrintf(kProcPath, process_)), &proc)) {
@@ -165,8 +162,6 @@
 ProcessId Process::GetPidInNamespace() const {
   std::string status;
   {
-    // Synchronously reading files in /proc does not hit the disk.
-    ThreadRestrictions::ScopedAllowIO allow_io;
     FilePath status_file =
         FilePath("/proc").Append(IntToString(process_)).Append("status");
     if (!ReadFileToString(status_file, &status)) {
diff --git a/base/process/process_metrics.cc b/base/process/process_metrics.cc
deleted file mode 100644
index fe9f8d3..0000000
--- a/base/process/process_metrics.cc
+++ /dev/null
@@ -1,149 +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 "base/process/process_metrics.h"
-
-#include <utility>
-
-#include "base/logging.h"
-#include "base/values.h"
-#include "build_config.h"
-
-#if defined(OS_MACOSX) || defined(OS_LINUX) || defined(OS_AIX)
-namespace {
-int CalculateEventsPerSecond(uint64_t event_count,
-                             uint64_t* last_event_count,
-                             base::TimeTicks* last_calculated) {
-  base::TimeTicks time = base::TimeTicks::Now();
-
-  if (*last_event_count == 0) {
-    // First call, just set the last values.
-    *last_calculated = time;
-    *last_event_count = event_count;
-    return 0;
-  }
-
-  int64_t events_delta = event_count - *last_event_count;
-  int64_t time_delta = (time - *last_calculated).InMicroseconds();
-  if (time_delta == 0) {
-    NOTREACHED();
-    return 0;
-  }
-
-  *last_calculated = time;
-  *last_event_count = event_count;
-
-  int64_t events_delta_for_ms =
-      events_delta * base::Time::kMicrosecondsPerSecond;
-  // Round the result up by adding 1/2 (the second term resolves to 1/2 without
-  // dropping down into floating point).
-  return (events_delta_for_ms + time_delta / 2) / time_delta;
-}
-
-}  // namespace
-#endif  // defined(OS_MACOSX) || defined(OS_LINUX) || defined(OS_AIX)
-
-namespace base {
-
-SystemMemoryInfoKB::SystemMemoryInfoKB() = default;
-
-SystemMemoryInfoKB::SystemMemoryInfoKB(const SystemMemoryInfoKB& other) =
-    default;
-
-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_);
-  GetVmStatInfo(&system_metrics.vmstat_info_);
-  GetSystemDiskInfo(&system_metrics.disk_info_);
-#endif
-#if defined(OS_CHROMEOS)
-  GetSwapInfo(&system_metrics.swap_info_);
-#endif
-
-  return system_metrics;
-}
-
-std::unique_ptr<Value> SystemMetrics::ToValue() const {
-  std::unique_ptr<DictionaryValue> res(new DictionaryValue());
-
-  res->SetInteger("committed_memory", static_cast<int>(committed_memory_));
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-  std::unique_ptr<DictionaryValue> meminfo = memory_info_.ToValue();
-  std::unique_ptr<DictionaryValue> vmstat = vmstat_info_.ToValue();
-  meminfo->MergeDictionary(vmstat.get());
-  res->Set("meminfo", std::move(meminfo));
-  res->Set("diskinfo", disk_info_.ToValue());
-#endif
-#if defined(OS_CHROMEOS)
-  res->Set("swapinfo", swap_info_.ToValue());
-#endif
-
-  return std::move(res);
-}
-
-std::unique_ptr<ProcessMetrics> ProcessMetrics::CreateCurrentProcessMetrics() {
-#if !defined(OS_MACOSX) || defined(OS_IOS)
-  return CreateProcessMetrics(base::GetCurrentProcessHandle());
-#else
-  return CreateProcessMetrics(base::GetCurrentProcessHandle(), nullptr);
-#endif  // !defined(OS_MACOSX) || defined(OS_IOS)
-}
-
-#if !defined(OS_FREEBSD) || !defined(OS_POSIX)
-double ProcessMetrics::GetPlatformIndependentCPUUsage() {
-  TimeDelta cumulative_cpu = GetCumulativeCPUUsage();
-  TimeTicks time = TimeTicks::Now();
-
-  if (last_cumulative_cpu_.is_zero()) {
-    // First call, just set the last values.
-    last_cumulative_cpu_ = cumulative_cpu;
-    last_cpu_time_ = time;
-    return 0;
-  }
-
-  TimeDelta system_time_delta = cumulative_cpu - last_cumulative_cpu_;
-  TimeDelta time_delta = time - last_cpu_time_;
-  DCHECK(!time_delta.is_zero());
-  if (time_delta.is_zero())
-    return 0;
-
-  last_cumulative_cpu_ = cumulative_cpu;
-  last_cpu_time_ = time;
-
-  return 100.0 * system_time_delta.InMicrosecondsF() /
-         time_delta.InMicrosecondsF();
-}
-#endif
-
-#if defined(OS_MACOSX) || defined(OS_LINUX) || defined(OS_AIX)
-int ProcessMetrics::CalculateIdleWakeupsPerSecond(
-    uint64_t absolute_idle_wakeups) {
-  return CalculateEventsPerSecond(absolute_idle_wakeups,
-                                  &last_absolute_idle_wakeups_,
-                                  &last_idle_wakeups_time_);
-}
-#else
-int ProcessMetrics::GetIdleWakeupsPerSecond() {
-  NOTIMPLEMENTED();  // http://crbug.com/120488
-  return 0;
-}
-#endif  // defined(OS_MACOSX) || defined(OS_LINUX) || defined(OS_AIX)
-
-#if defined(OS_MACOSX)
-int ProcessMetrics::CalculatePackageIdleWakeupsPerSecond(
-    uint64_t absolute_package_idle_wakeups) {
-  return CalculateEventsPerSecond(absolute_package_idle_wakeups,
-                                  &last_absolute_package_idle_wakeups_,
-                                  &last_package_idle_wakeups_time_);
-}
-
-#endif  // defined(OS_MACOSX)
-}  // namespace base
diff --git a/base/process/process_metrics.h b/base/process/process_metrics.h
deleted file mode 100644
index 5d47abf..0000000
--- a/base/process/process_metrics.h
+++ /dev/null
@@ -1,542 +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 <stddef.h>
-#include <stdint.h>
-
-#include <memory>
-#include <string>
-
-#include "base/base_export.h"
-#include "base/gtest_prod_util.h"
-#include "base/macros.h"
-#include "base/process/process_handle.h"
-#include "base/time/time.h"
-#include "base/values.h"
-#include "build_config.h"
-
-#if defined(OS_MACOSX)
-#include <mach/mach.h>
-#include "base/process/port_provider_mac.h"
-
-#if !defined(OS_IOS)
-#include <mach/mach_vm.h>
-#endif
-#endif
-
-#if defined(OS_WIN)
-#include "base/win/scoped_handle.h"
-#include "base/win/windows_types.h"
-#endif
-
-namespace base {
-
-// Full declaration is in process_metrics_iocounters.h.
-struct IoCounters;
-
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-// Minor and major page fault counts since the process creation.
-// Both counts are process-wide, and exclude child processes.
-//
-// minor: Number of page faults that didn't require disk IO.
-// major: Number of page faults that required disk IO.
-struct PageFaultCounts {
-  int64_t minor;
-  int64_t major;
-};
-#endif  // defined(OS_LINUX) || defined(OS_ANDROID)
-
-// Convert a POSIX timeval to microseconds.
-BASE_EXPORT int64_t TimeValToMicroseconds(const struct timeval& tv);
-
-// Provides performance metrics for a specified process (CPU usage and IO
-// counters). Use CreateCurrentProcessMetrics() to get an instance for the
-// current process, or CreateProcessMetrics() to get an instance for an
-// arbitrary process. Then, access the information with the different get
-// methods.
-//
-// This class exposes a few platform-specific APIs for parsing memory usage, but
-// these are not intended to generalize to other platforms, since the memory
-// models differ substantially.
-//
-// To obtain consistent memory metrics, use the memory_instrumentation service.
-//
-// For further documentation on memory, see
-// https://chromium.googlesource.com/chromium/src/+/HEAD/docs/README.md
-class BASE_EXPORT ProcessMetrics {
- public:
-  ~ProcessMetrics();
-
-  // Creates a ProcessMetrics for the specified process.
-#if !defined(OS_MACOSX) || defined(OS_IOS)
-  static std::unique_ptr<ProcessMetrics> CreateProcessMetrics(
-      ProcessHandle process);
-#else
-
-  // 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 std::unique_ptr<ProcessMetrics> CreateProcessMetrics(
-      ProcessHandle process,
-      PortProvider* port_provider);
-#endif  // !defined(OS_MACOSX) || defined(OS_IOS)
-
-  // Creates a ProcessMetrics for the current process. This a cross-platform
-  // convenience wrapper for CreateProcessMetrics().
-  static std::unique_ptr<ProcessMetrics> CreateCurrentProcessMetrics();
-
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-  // Resident Set Size is a Linux/Android specific memory concept. Do not
-  // attempt to extend this to other platforms.
-  BASE_EXPORT size_t GetResidentSetSize() const;
-#endif
-
-#if defined(OS_CHROMEOS)
-  // /proc/<pid>/totmaps is a syscall that returns memory summary statistics for
-  // the process.
-  // totmaps is a Linux specific concept, currently only being used on ChromeOS.
-  // Do not attempt to extend this to other platforms.
-  //
-  struct TotalsSummary {
-    size_t private_clean_kb;
-    size_t private_dirty_kb;
-    size_t swap_kb;
-  };
-  BASE_EXPORT TotalsSummary GetTotalsSummary() const;
-#endif
-
-#if defined(OS_MACOSX)
-  struct TaskVMInfo {
-    // Only available on macOS 10.12+.
-    // Anonymous, non-discardable memory, including non-volatile IOKit.
-    // Measured in bytes.
-    uint64_t phys_footprint = 0;
-
-    // Anonymous, non-discardable, non-compressed memory, excluding IOKit.
-    // Measured in bytes.
-    uint64_t internal = 0;
-
-    // Compressed memory measured in bytes.
-    uint64_t compressed = 0;
-  };
-  TaskVMInfo GetTaskVMInfo() const;
-#endif
-
-  // Returns the percentage of time spent executing, across all threads of the
-  // process, in the interval since the last time the method was called. Since
-  // this considers the total execution time across all threads in a process,
-  // the result can easily exceed 100% in multi-thread processes running on
-  // multi-core systems. In general the result is therefore a value in the
-  // range 0% to SysInfo::NumberOfProcessors() * 100%.
-  //
-  // To obtain the percentage of total available CPU resources consumed by this
-  // process over the interval, the caller must divide by NumberOfProcessors().
-  //
-  // Since this API measures usage over an interval, it will return zero on the
-  // first call, and an actual value only on the second and subsequent calls.
-  double GetPlatformIndependentCPUUsage();
-
-  // Returns the cumulative CPU usage across all threads of the process since
-  // process start. In case of multi-core processors, a process can consume CPU
-  // at a rate higher than wall-clock time, e.g. two cores at full utilization
-  // will result in a time delta of 2 seconds/per 1 wall-clock second.
-  TimeDelta GetCumulativeCPUUsage();
-
-  // Returns the number of average idle cpu wakeups per second since the last
-  // call.
-  int GetIdleWakeupsPerSecond();
-
-#if defined(OS_MACOSX)
-  // Returns the number of average "package idle exits" per second, which have
-  // a higher energy impact than a regular wakeup, since the last call.
-  //
-  // From the powermetrics man page:
-  // "With the exception of some Mac Pro systems, Mac and
-  // iOS systems are typically single package systems, wherein all CPUs are
-  // part of a single processor complex (typically a single IC die) with shared
-  // logic that can include (depending on system specifics) shared last level
-  // caches, an integrated memory controller etc. When all CPUs in the package
-  // are idle, the hardware can power-gate significant portions of the shared
-  // logic in addition to each individual processor's logic, as well as take
-  // measures such as placing DRAM in to self-refresh (also referred to as
-  // auto-refresh), place interconnects into lower-power states etc"
-  int GetPackageIdleWakeupsPerSecond();
-#endif
-
-  // 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;
-
-#if defined(OS_LINUX) || defined(OS_AIX) || defined(OS_ANDROID)
-  // Returns the number of file descriptors currently open by the process, or
-  // -1 on error.
-  int GetOpenFdCount() const;
-
-  // Returns the soft limit of file descriptors that can be opened by the
-  // process, or -1 on error.
-  int GetOpenFdSoftLimit() const;
-#endif  // defined(OS_LINUX) || defined(OS_AIX) || defined(OS_ANDROID)
-
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-  // Bytes of swap as reported by /proc/[pid]/status.
-  uint64_t GetVmSwapBytes() const;
-
-  // Minor and major page fault count as reported by /proc/[pid]/stat.
-  // Returns true for success.
-  bool GetPageFaultCounts(PageFaultCounts* counts) const;
-#endif  // defined(OS_LINUX) || defined(OS_ANDROID)
-
-  // Returns total memory usage of malloc.
-  size_t GetMallocUsage();
-
- 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_MACOSX) || defined(OS_LINUX) || defined(OS_AIX)
-  int CalculateIdleWakeupsPerSecond(uint64_t absolute_idle_wakeups);
-#endif
-#if defined(OS_MACOSX)
-  // The subset of wakeups that cause a "package exit" can be tracked on macOS.
-  // See |GetPackageIdleWakeupsForSecond| comment for more info.
-  int CalculatePackageIdleWakeupsPerSecond(
-      uint64_t absolute_package_idle_wakeups);
-#endif
-
-#if defined(OS_WIN)
-  win::ScopedHandle process_;
-#else
-  ProcessHandle process_;
-#endif
-
-  // Used to store the previous times and CPU usage counts so we can
-  // compute the CPU usage between calls.
-  TimeTicks last_cpu_time_;
-#if !defined(OS_FREEBSD) || !defined(OS_POSIX)
-  TimeDelta last_cumulative_cpu_;
-#endif
-
-#if defined(OS_MACOSX) || defined(OS_LINUX) || defined(OS_AIX)
-  // Same thing for idle wakeups.
-  TimeTicks last_idle_wakeups_time_;
-  uint64_t last_absolute_idle_wakeups_;
-#endif
-
-#if defined(OS_MACOSX)
-  // And same thing for package idle exit wakeups.
-  TimeTicks last_package_idle_wakeups_time_;
-  uint64_t last_absolute_package_idle_wakeups_;
-#endif
-
-#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_;
-#endif  // defined(OS_MACOSX)
-#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();
-
-// Returns the number of bytes in a memory page. Do not use this to compute
-// the number of pages in a block of memory for calling mincore(). On some
-// platforms, e.g. iOS, mincore() uses a different page size from what is
-// returned by GetPageSize().
-BASE_EXPORT size_t GetPageSize();
-
-// 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.
-BASE_EXPORT size_t GetMaxFds();
-
-#if defined(OS_POSIX) && !defined(OS_FUCHSIA)
-// Increases the file descriptor soft limit to |max_descriptors| or the OS hard
-// limit, whichever is lower. If the limit is already higher than
-// |max_descriptors|, then nothing happens.
-BASE_EXPORT void IncreaseFdLimitTo(unsigned int max_descriptors);
-#endif  // defined(OS_POSIX) && !defined(OS_FUCHSIA)
-
-#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \
-    defined(OS_ANDROID) || defined(OS_AIX) || defined(OS_FUCHSIA)
-// Data about system-wide memory consumption. Values are in KB. Available on
-// Windows, Mac, Linux, Android and Chrome OS.
-//
-// Total memory are available on all platforms that implement
-// GetSystemMemoryInfo(). Total/free swap memory are available on all platforms
-// except on Mac. Buffers/cached/active_anon/inactive_anon/active_file/
-// inactive_file/dirty/reclaimable/pswpin/pswpout/pgmajfault are available on
-// Linux/Android/Chrome OS. Shmem/slab/gem_objects/gem_size are Chrome OS only.
-// Speculative/file_backed/purgeable are Mac and iOS only.
-// Free is absent on Windows (see "avail_phys" below).
-struct BASE_EXPORT SystemMemoryInfoKB {
-  SystemMemoryInfoKB();
-  SystemMemoryInfoKB(const SystemMemoryInfoKB& other);
-
-  // Serializes the platform specific fields to value.
-  std::unique_ptr<DictionaryValue> ToValue() const;
-
-  int total = 0;
-
-#if !defined(OS_WIN)
-  int free = 0;
-#endif
-
-#if defined(OS_WIN)
-  // "This is the amount of physical memory that can be immediately reused
-  // without having to write its contents to disk first. It is the sum of the
-  // size of the standby, free, and zero lists." (MSDN).
-  // Standby: not modified pages of physical ram (file-backed memory) that are
-  // not actively being used.
-  int avail_phys = 0;
-#endif
-
-#if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_AIX)
-  // This provides an estimate of available memory as described here:
-  // https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
-  // NOTE: this is ONLY valid in kernels 3.14 and up.  Its value will always
-  // be 0 in earlier kernel versions.
-  // Note: it includes _all_ file-backed memory (active + inactive).
-  int available = 0;
-#endif
-
-#if !defined(OS_MACOSX)
-  int swap_total = 0;
-  int swap_free = 0;
-#endif
-
-#if defined(OS_ANDROID) || defined(OS_LINUX) || defined(OS_AIX) || \
-    defined(OS_FUCHSIA)
-  int buffers = 0;
-  int cached = 0;
-  int active_anon = 0;
-  int inactive_anon = 0;
-  int active_file = 0;
-  int inactive_file = 0;
-  int dirty = 0;
-  int reclaimable = 0;
-#endif  // defined(OS_ANDROID) || defined(OS_LINUX) || defined(OS_AIX) ||
-        // defined(OS_FUCHSIA)
-
-#if defined(OS_CHROMEOS)
-  int shmem = 0;
-  int slab = 0;
-  // Gem data will be -1 if not supported.
-  int gem_objects = -1;
-  long long gem_size = -1;
-#endif  // defined(OS_CHROMEOS)
-
-#if defined(OS_MACOSX)
-  int speculative = 0;
-  int file_backed = 0;
-  int purgeable = 0;
-#endif  // defined(OS_MACOSX)
-};
-
-// On Linux/Android/Chrome OS, system-wide memory consumption data is parsed
-// from /proc/meminfo and /proc/vmstat. On Windows/Mac, it is obtained using
-// system API calls.
-//
-// Fills in the provided |meminfo| structure. Returns true on success.
-// Exposed for memory debugging widget.
-BASE_EXPORT bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo);
-
-#endif  // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) ||
-        // defined(OS_ANDROID) || defined(OS_AIX) || defined(OS_FUCHSIA)
-
-#if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_AIX)
-// 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(StringPiece 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[];
-
-// Parses a string containing the contents of /proc/meminfo
-// returns true on success or false for a parsing error
-// Exposed for testing.
-BASE_EXPORT bool ParseProcMeminfo(StringPiece input,
-                                  SystemMemoryInfoKB* meminfo);
-
-// Data from /proc/vmstat.
-struct BASE_EXPORT VmStatInfo {
-  // Serializes the platform specific fields to value.
-  std::unique_ptr<DictionaryValue> ToValue() const;
-
-  unsigned long pswpin = 0;
-  unsigned long pswpout = 0;
-  unsigned long pgmajfault = 0;
-};
-
-// Retrieves data from /proc/vmstat about system-wide vm operations.
-// Fills in the provided |vmstat| structure. Returns true on success.
-BASE_EXPORT bool GetVmStatInfo(VmStatInfo* vmstat);
-
-// Parses a string containing the contents of /proc/vmstat
-// returns true on success or false for a parsing error
-// Exposed for testing.
-BASE_EXPORT bool ParseProcVmstat(StringPiece input, VmStatInfo* vmstat);
-
-// Data from /proc/diskstats about system-wide disk I/O.
-struct BASE_EXPORT SystemDiskInfo {
-  SystemDiskInfo();
-  SystemDiskInfo(const SystemDiskInfo& other);
-
-  // Serializes the platform specific fields to value.
-  std::unique_ptr<Value> ToValue() const;
-
-  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;
-};
-
-// Checks whether the candidate string is a valid disk name, [hsv]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(StringPiece 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);
-
-// Returns the amount of time spent in user space since boot across all CPUs.
-BASE_EXPORT TimeDelta GetUserCpuTimeSinceBoot();
-
-#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) {
-  }
-
-  // Serializes the platform specific fields to value.
-  std::unique_ptr<Value> ToValue() const;
-
-  uint64_t num_reads = 0;
-  uint64_t num_writes = 0;
-  uint64_t compr_data_size = 0;
-  uint64_t orig_data_size = 0;
-  uint64_t mem_used_total = 0;
-};
-
-// Parses a string containing the contents of /sys/block/zram0/mm_stat.
-// This should be used for the new ZRAM sysfs interfaces.
-// Returns true on success or false for a parsing error.
-// Exposed for testing.
-BASE_EXPORT bool ParseZramMmStat(StringPiece mm_stat_data, SwapInfo* swap_info);
-
-// Parses a string containing the contents of /sys/block/zram0/stat
-// This should be used for the new ZRAM sysfs interfaces.
-// Returns true on success or false for a parsing error.
-// Exposed for testing.
-BASE_EXPORT bool ParseZramStat(StringPiece stat_data, SwapInfo* swap_info);
-
-// In ChromeOS, reads files from /sys/block/zram0 that contain ZRAM usage data.
-// Fills in the provided |swap_data| structure.
-// Returns true on success or false for a parsing error.
-BASE_EXPORT bool 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();
-
-  // Serializes the system metrics to value.
-  std::unique_ptr<Value> ToValue() const;
-
- private:
-  FRIEND_TEST_ALL_PREFIXES(SystemMetricsTest, SystemMetrics);
-
-  size_t committed_memory_;
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-  SystemMemoryInfoKB memory_info_;
-  VmStatInfo vmstat_info_;
-  SystemDiskInfo disk_info_;
-#endif
-#if defined(OS_CHROMEOS)
-  SwapInfo swap_info_;
-#endif
-};
-
-#if defined(OS_MACOSX) && !defined(OS_IOS)
-enum class MachVMRegionResult {
-  // There were no more memory regions between |address| and the end of the
-  // virtual address space.
-  Finished,
-
-  // All output parameters are invalid.
-  Error,
-
-  // All output parameters are filled in.
-  Success
-};
-
-// Returns info on the first memory region at or after |address|, including
-// resident memory and share mode. On Success, |size| reflects the size of the
-// memory region.
-// |size| and |info| are output parameters, only valid on Success.
-// |address| is an in-out parameter, than represents both the address to start
-// looking, and the start address of the memory region.
-BASE_EXPORT MachVMRegionResult GetTopInfo(mach_port_t task,
-                                          mach_vm_size_t* size,
-                                          mach_vm_address_t* address,
-                                          vm_region_top_info_data_t* info);
-
-// Returns info on the first memory region at or after |address|, including
-// protection values. On Success, |size| reflects the size of the
-// memory region.
-// Returns info on the first memory region at or after |address|, including
-// resident memory and share mode.
-// |size| and |info| are output parameters, only valid on Success.
-BASE_EXPORT MachVMRegionResult GetBasicInfo(mach_port_t task,
-                                            mach_vm_size_t* size,
-                                            mach_vm_address_t* address,
-                                            vm_region_basic_info_64* info);
-#endif  // defined(OS_MACOSX) && !defined(OS_IOS)
-
-}  // namespace base
-
-#endif  // BASE_PROCESS_PROCESS_METRICS_H_
diff --git a/base/process/process_metrics_freebsd.cc b/base/process/process_metrics_freebsd.cc
deleted file mode 100644
index a552c03..0000000
--- a/base/process/process_metrics_freebsd.cc
+++ /dev/null
@@ -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 "base/process/process_metrics.h"
-
-#include <stddef.h>
-#include <sys/sysctl.h>
-#include <sys/user.h>
-#include <unistd.h>
-
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/process/process_metrics_iocounters.h"
-#include "base/stl_util.h"
-
-namespace base {
-
-ProcessMetrics::ProcessMetrics(ProcessHandle process)
-    : process_(process),
-      last_cpu_(0) {}
-
-// static
-std::unique_ptr<ProcessMetrics> ProcessMetrics::CreateProcessMetrics(
-    ProcessHandle process) {
-  return WrapUnique(new ProcessMetrics(process));
-}
-
-double ProcessMetrics::GetPlatformIndependentCPUUsage() {
-  struct kinfo_proc info;
-  int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, process_};
-  size_t length = sizeof(info);
-
-  if (sysctl(mib, base::size(mib), &info, &length, NULL, 0) < 0)
-    return 0;
-
-  return (info.ki_pctcpu / FSCALE) * 100.0;
-}
-
-TimeDelta ProcessMetrics::GetCumulativeCPUUsage() {
-  NOTREACHED();
-  return TimeDelta();
-}
-
-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, base::size(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 base
diff --git a/base/process/process_metrics_iocounters.h b/base/process/process_metrics_iocounters.h
deleted file mode 100644
index 39f7d3b..0000000
--- a/base/process/process_metrics_iocounters.h
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2018 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 is a separate file so that users of process metrics don't need to
-// include windows.h unless they need IoCounters.
-
-#ifndef BASE_PROCESS_PROCESS_METRICS_IOCOUNTERS_H_
-#define BASE_PROCESS_PROCESS_METRICS_IOCOUNTERS_H_
-
-#include <stdint.h>
-
-#include "base/process/process_metrics.h"
-#include "build_config.h"
-
-#if defined(OS_WIN)
-#include <windows.h>
-#endif
-
-namespace base {
-
-#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
-
-}  // namespace base
-
-#endif  // BASE_PROCESS_PROCESS_METRICS_IOCOUNTERS_H_
diff --git a/base/process/process_metrics_linux.cc b/base/process/process_metrics_linux.cc
deleted file mode 100644
index f045e24..0000000
--- a/base/process/process_metrics_linux.cc
+++ /dev/null
@@ -1,975 +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/process_metrics.h"
-
-#include <dirent.h>
-#include <fcntl.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <utility>
-
-#include "base/files/dir_reader_posix.h"
-#include "base/files/file_util.h"
-#include "base/logging.h"
-#include "base/memory/ptr_util.h"
-#include "base/optional.h"
-#include "base/process/internal_linux.h"
-#include "base/process/process_metrics_iocounters.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_split.h"
-#include "base/strings/string_tokenizer.h"
-#include "base/strings/string_util.h"
-#include "base/threading/thread_restrictions.h"
-#include "build_config.h"
-
-namespace base {
-
-namespace {
-
-void TrimKeyValuePairs(StringPairs* pairs) {
-  for (auto& pair : *pairs) {
-    TrimWhitespaceASCII(pair.first, TRIM_ALL, &pair.first);
-    TrimWhitespaceASCII(pair.second, TRIM_ALL, &pair.second);
-  }
-}
-
-#if defined(OS_CHROMEOS)
-// Read a file with a single number string and return the number as a uint64_t.
-uint64_t ReadFileToUint64(const FilePath& file) {
-  std::string file_contents;
-  if (!ReadFileToString(file, &file_contents))
-    return 0;
-  TrimWhitespaceASCII(file_contents, TRIM_ALL, &file_contents);
-  uint64_t file_contents_uint64 = 0;
-  if (!StringToUint64(file_contents, &file_contents_uint64))
-    return 0;
-  return file_contents_uint64;
-}
-#endif
-
-// Read |filename| in /proc/<pid>/, split the entries into key/value pairs, and
-// trim the key and value. On success, return true and write the trimmed
-// key/value pairs into |key_value_pairs|.
-bool ReadProcFileToTrimmedStringPairs(pid_t pid,
-                                      StringPiece filename,
-                                      StringPairs* key_value_pairs) {
-  std::string status_data;
-  {
-    // Synchronously reading files in /proc does not hit the disk.
-    ThreadRestrictions::ScopedAllowIO allow_io;
-    FilePath status_file = internal::GetProcPidDir(pid).Append(filename);
-    if (!ReadFileToString(status_file, &status_data))
-      return false;
-  }
-  SplitStringIntoKeyValuePairs(status_data, ':', '\n', key_value_pairs);
-  TrimKeyValuePairs(key_value_pairs);
-  return true;
-}
-
-// Read /proc/<pid>/status and return 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, StringPiece field) {
-  StringPairs pairs;
-  if (!ReadProcFileToTrimmedStringPairs(pid, "status", &pairs))
-    return 0;
-
-  for (const auto& pair : pairs) {
-    const std::string& key = pair.first;
-    const std::string& value_str = pair.second;
-    if (key != field)
-      continue;
-
-    std::vector<StringPiece> split_value_str =
-        SplitStringPiece(value_str, " ", TRIM_WHITESPACE, SPLIT_WANT_ALL);
-    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;
-  }
-  // This can be reached if the process dies when proc is read -- in that case,
-  // the kernel can return missing fields.
-  return 0;
-}
-
-#if defined(OS_LINUX) || defined(OS_AIX)
-// Read /proc/<pid>/status and look for |field|. On success, return true and
-// write the value for |field| into |result|.
-// Only works for fields in the form of "field    :     uint_value"
-bool ReadProcStatusAndGetFieldAsUint64(pid_t pid,
-                                       StringPiece field,
-                                       uint64_t* result) {
-  StringPairs pairs;
-  if (!ReadProcFileToTrimmedStringPairs(pid, "status", &pairs))
-    return false;
-
-  for (const auto& pair : pairs) {
-    const std::string& key = pair.first;
-    const std::string& value_str = pair.second;
-    if (key != field)
-      continue;
-
-    uint64_t value;
-    if (!StringToUint64(value_str, &value))
-      return false;
-    *result = value;
-    return true;
-  }
-  return false;
-}
-#endif  // defined(OS_LINUX) || defined(OS_AIX)
-
-// Get the total CPU of a single process.  Return value is number of jiffies
-// on success or -1 on error.
-int64_t GetProcessCPU(pid_t pid) {
-  std::string buffer;
-  std::vector<std::string> proc_stats;
-  if (!internal::ReadProcStats(pid, &buffer) ||
-      !internal::ParseProcStats(buffer, &proc_stats)) {
-    return -1;
-  }
-
-  int64_t total_cpu =
-      internal::GetProcStatsFieldAsInt64(proc_stats, internal::VM_UTIME) +
-      internal::GetProcStatsFieldAsInt64(proc_stats, internal::VM_STIME);
-
-  return total_cpu;
-}
-
-#if defined(OS_CHROMEOS)
-// Report on Chrome OS GEM object graphics memory. /run/debugfs_gpu is a
-// bind mount into /sys/kernel/debug and synchronously reading the in-memory
-// files in /sys is fast.
-void ReadChromeOSGraphicsMemory(SystemMemoryInfoKB* meminfo) {
-#if defined(ARCH_CPU_ARM_FAMILY)
-  FilePath geminfo_file("/run/debugfs_gpu/exynos_gem_objects");
-#else
-  FilePath geminfo_file("/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)
-
-}  // namespace
-
-// static
-std::unique_ptr<ProcessMetrics> ProcessMetrics::CreateProcessMetrics(
-    ProcessHandle process) {
-  return WrapUnique(new ProcessMetrics(process));
-}
-
-size_t ProcessMetrics::GetResidentSetSize() const {
-  return internal::ReadProcStatsAndGetFieldAsSizeT(process_, internal::VM_RSS) *
-      getpagesize();
-}
-
-TimeDelta ProcessMetrics::GetCumulativeCPUUsage() {
-  return internal::ClockTicksToTimeDelta(GetProcessCPU(process_));
-}
-
-// For the /proc/self/io file to exist, the Linux kernel must have
-// CONFIG_TASK_IO_ACCOUNTING enabled.
-bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
-  StringPairs pairs;
-  if (!ReadProcFileToTrimmedStringPairs(process_, "io", &pairs))
-    return false;
-
-  io_counters->OtherOperationCount = 0;
-  io_counters->OtherTransferCount = 0;
-
-  for (const auto& pair : pairs) {
-    const std::string& key = pair.first;
-    const std::string& value_str = pair.second;
-    uint64_t* target_counter = nullptr;
-    if (key == "syscr")
-      target_counter = &io_counters->ReadOperationCount;
-    else if (key == "syscw")
-      target_counter = &io_counters->WriteOperationCount;
-    else if (key == "rchar")
-      target_counter = &io_counters->ReadTransferCount;
-    else if (key == "wchar")
-      target_counter = &io_counters->WriteTransferCount;
-    if (!target_counter)
-      continue;
-    bool converted = StringToUint64(value_str, target_counter);
-    DCHECK(converted);
-  }
-  return true;
-}
-
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-uint64_t ProcessMetrics::GetVmSwapBytes() const {
-  return ReadProcStatusAndGetFieldAsSizeT(process_, "VmSwap") * 1024;
-}
-#endif  // defined(OS_LINUX) || defined(OS_ANDROID)
-
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-bool ProcessMetrics::GetPageFaultCounts(PageFaultCounts* counts) const {
-  // We are not using internal::ReadStatsFileAndGetFieldAsInt64(), since it
-  // would read the file twice, and return inconsistent numbers.
-  std::string stats_data;
-  if (!internal::ReadProcStats(process_, &stats_data))
-    return false;
-  std::vector<std::string> proc_stats;
-  if (!internal::ParseProcStats(stats_data, &proc_stats))
-    return false;
-
-  counts->minor =
-      internal::GetProcStatsFieldAsInt64(proc_stats, internal::VM_MINFLT);
-  counts->major =
-      internal::GetProcStatsFieldAsInt64(proc_stats, internal::VM_MAJFLT);
-  return true;
-}
-#endif  // defined(OS_LINUX) || defined(OS_ANDROID)
-
-int ProcessMetrics::GetOpenFdCount() const {
-  // Use /proc/<pid>/fd to count the number of entries there.
-  FilePath fd_path = internal::GetProcPidDir(process_).Append("fd");
-
-  DirReaderPosix dir_reader(fd_path.value().c_str());
-  if (!dir_reader.IsValid())
-    return -1;
-
-  int total_count = 0;
-  for (; dir_reader.Next(); ) {
-    const char* name = dir_reader.name();
-    if (strcmp(name, ".") != 0 && strcmp(name, "..") != 0)
-      ++total_count;
-  }
-
-  return total_count;
-}
-
-int ProcessMetrics::GetOpenFdSoftLimit() const {
-  // Use /proc/<pid>/limits to read the open fd limit.
-  FilePath fd_path = internal::GetProcPidDir(process_).Append("limits");
-
-  std::string limits_contents;
-  if (!ReadFileToString(fd_path, &limits_contents))
-    return -1;
-
-  for (const auto& line : SplitStringPiece(
-           limits_contents, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
-    if (!line.starts_with("Max open files"))
-      continue;
-
-    auto tokens =
-        SplitStringPiece(line, " ", TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
-    if (tokens.size() > 3) {
-      int limit = -1;
-      if (!StringToInt(tokens[3], &limit))
-        return -1;
-      return limit;
-    }
-  }
-  return -1;
-}
-
-#if defined(OS_LINUX) || defined(OS_AIX)
-ProcessMetrics::ProcessMetrics(ProcessHandle process)
-    : process_(process), last_absolute_idle_wakeups_(0) {}
-#else
-ProcessMetrics::ProcessMetrics(ProcessHandle process) : process_(process) {}
-#endif
-
-#if defined(OS_CHROMEOS)
-// Private, Shared and Proportional working set sizes are obtained from
-// /proc/<pid>/totmaps
-ProcessMetrics::TotalsSummary ProcessMetrics::GetTotalsSummary() 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
-  ProcessMetrics::TotalsSummary summary = {};
-
-  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 summary;
-  }
-
-  std::vector<std::string> totmaps_fields = SplitString(
-      totmaps_data, kWhitespaceASCII, KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY);
-
-  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 private_clean_kb = 0;
-  int private_dirty_kb = 0;
-  int swap_kb = 0;
-  bool success = true;
-  success &=
-      StringToInt(totmaps_fields[kPrivate_CleanIndex], &private_clean_kb);
-  success &=
-      StringToInt(totmaps_fields[kPrivate_DirtyIndex], &private_dirty_kb);
-  success &= StringToInt(totmaps_fields[kSwapIndex], &swap_kb);
-
-  if (!success)
-    return summary;
-
-  summary.private_clean_kb = private_clean_kb;
-  summary.private_dirty_kb = private_dirty_kb;
-  summary.swap_kb = swap_kb;
-
-  return summary;
-}
-#endif
-
-size_t GetSystemCommitCharge() {
-  SystemMemoryInfoKB meminfo;
-  if (!GetSystemMemoryInfo(&meminfo))
-    return 0;
-  return meminfo.total - meminfo.free - meminfo.buffers - meminfo.cached;
-}
-
-int ParseProcStatCPU(StringPiece input) {
-  // |input| may be empty if the process disappeared somehow.
-  // e.g. http://crbug.com/145811.
-  if (input.empty())
-    return -1;
-
-  size_t start = input.find_last_of(')');
-  if (start == input.npos)
-    return -1;
-
-  // Number of spaces remaining until reaching utime's index starting after the
-  // last ')'.
-  int num_spaces_remaining = internal::VM_UTIME - 1;
-
-  size_t i = start;
-  while ((i = input.find(' ', i + 1)) != input.npos) {
-    // Validate the assumption that there aren't any contiguous spaces
-    // in |input| before utime.
-    DCHECK_NE(input[i - 1], ' ');
-    if (--num_spaces_remaining == 0) {
-      int utime = 0;
-      int stime = 0;
-      if (sscanf(&input.data()[i], "%d %d", &utime, &stime) != 2)
-        return -1;
-
-      return utime + stime;
-    }
-  }
-
-  return -1;
-}
-
-int GetNumberOfThreads(ProcessHandle process) {
-  return internal::ReadProcStatsAndGetFieldAsInt64(process,
-                                                   internal::VM_NUMTHREADS);
-}
-
-const char kProcSelfExe[] = "/proc/self/exe";
-
-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
-
-std::unique_ptr<DictionaryValue> SystemMemoryInfoKB::ToValue() const {
-  auto res = std::make_unique<DictionaryValue>();
-  res->SetInteger("total", total);
-  res->SetInteger("free", free);
-  res->SetInteger("available", available);
-  res->SetInteger("buffers", buffers);
-  res->SetInteger("cached", cached);
-  res->SetInteger("active_anon", active_anon);
-  res->SetInteger("inactive_anon", inactive_anon);
-  res->SetInteger("active_file", active_file);
-  res->SetInteger("inactive_file", inactive_file);
-  res->SetInteger("swap_total", swap_total);
-  res->SetInteger("swap_free", swap_free);
-  res->SetInteger("swap_used", swap_total - swap_free);
-  res->SetInteger("dirty", dirty);
-  res->SetInteger("reclaimable", reclaimable);
-#ifdef OS_CHROMEOS
-  res->SetInteger("shmem", shmem);
-  res->SetInteger("slab", slab);
-  res->SetInteger("gem_objects", gem_objects);
-  res->SetInteger("gem_size", gem_size);
-#endif
-
-  return res;
-}
-
-bool ParseProcMeminfo(StringPiece 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 at the end, make sure the MemTotal value will be at
-  // least non-zero. So start off with a zero total.
-  meminfo->total = 0;
-
-  for (const StringPiece& line : SplitStringPiece(
-           meminfo_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
-    std::vector<StringPiece> tokens = SplitStringPiece(
-        line, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
-    // HugePages_* only has a number and no suffix so there may not be exactly 3
-    // tokens.
-    if (tokens.size() <= 1) {
-      DLOG(WARNING) << "meminfo: tokens: " << tokens.size()
-                    << " malformed line: " << line.as_string();
-      continue;
-    }
-
-    int* target = nullptr;
-    if (tokens[0] == "MemTotal:")
-      target = &meminfo->total;
-    else if (tokens[0] == "MemFree:")
-      target = &meminfo->free;
-    else if (tokens[0] == "MemAvailable:")
-      target = &meminfo->available;
-    else if (tokens[0] == "Buffers:")
-      target = &meminfo->buffers;
-    else if (tokens[0] == "Cached:")
-      target = &meminfo->cached;
-    else if (tokens[0] == "Active(anon):")
-      target = &meminfo->active_anon;
-    else if (tokens[0] == "Inactive(anon):")
-      target = &meminfo->inactive_anon;
-    else if (tokens[0] == "Active(file):")
-      target = &meminfo->active_file;
-    else if (tokens[0] == "Inactive(file):")
-      target = &meminfo->inactive_file;
-    else if (tokens[0] == "SwapTotal:")
-      target = &meminfo->swap_total;
-    else if (tokens[0] == "SwapFree:")
-      target = &meminfo->swap_free;
-    else if (tokens[0] == "Dirty:")
-      target = &meminfo->dirty;
-    else if (tokens[0] == "SReclaimable:")
-      target = &meminfo->reclaimable;
-#if defined(OS_CHROMEOS)
-    // Chrome OS has a tweaked kernel that allows querying Shmem, which is
-    // usually video memory otherwise invisible to the OS.
-    else if (tokens[0] == "Shmem:")
-      target = &meminfo->shmem;
-    else if (tokens[0] == "Slab:")
-      target = &meminfo->slab;
-#endif
-    if (target)
-      StringToInt(tokens[1], target);
-  }
-
-  // Make sure the MemTotal is valid.
-  return meminfo->total > 0;
-}
-
-bool ParseProcVmstat(StringPiece vmstat_data, VmStatInfo* vmstat) {
-  // The format of /proc/vmstat is:
-  //
-  // nr_free_pages 299878
-  // nr_inactive_anon 239863
-  // nr_active_anon 1318966
-  // nr_inactive_file 2015629
-  // ...
-  //
-  // Iterate through the whole file because the position of the
-  // fields are dependent on the kernel version and configuration.
-  bool has_pswpin = false;
-  bool has_pswpout = false;
-  bool has_pgmajfault = false;
-  for (const StringPiece& line : SplitStringPiece(
-           vmstat_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
-    std::vector<StringPiece> tokens = SplitStringPiece(
-        line, " ", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY);
-    if (tokens.size() != 2)
-      continue;
-
-    uint64_t val;
-    if (!StringToUint64(tokens[1], &val))
-      continue;
-
-    if (tokens[0] == "pswpin") {
-      vmstat->pswpin = val;
-      DCHECK(!has_pswpin);
-      has_pswpin = true;
-    } else if (tokens[0] == "pswpout") {
-      vmstat->pswpout = val;
-      DCHECK(!has_pswpout);
-      has_pswpout = true;
-    } else if (tokens[0] == "pgmajfault") {
-      vmstat->pgmajfault = val;
-      DCHECK(!has_pgmajfault);
-      has_pgmajfault = true;
-    }
-    if (has_pswpin && has_pswpout && has_pgmajfault)
-      return true;
-  }
-
-  return false;
-}
-
-bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
-  // Synchronously reading files in /proc and /sys are 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)
-  ReadChromeOSGraphicsMemory(meminfo);
-#endif
-
-  return true;
-}
-
-std::unique_ptr<DictionaryValue> VmStatInfo::ToValue() const {
-  auto res = std::make_unique<DictionaryValue>();
-  res->SetInteger("pswpin", pswpin);
-  res->SetInteger("pswpout", pswpout);
-  res->SetInteger("pgmajfault", pgmajfault);
-  return res;
-}
-
-bool GetVmStatInfo(VmStatInfo* vmstat) {
-  // Synchronously reading files in /proc and /sys are safe.
-  ThreadRestrictions::ScopedAllowIO allow_io;
-
-  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, vmstat)) {
-    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;
-}
-
-SystemDiskInfo::SystemDiskInfo(const SystemDiskInfo& other) = default;
-
-std::unique_ptr<Value> SystemDiskInfo::ToValue() const {
-  auto res = std::make_unique<DictionaryValue>();
-
-  // Write out uint64_t variables as doubles.
-  // Note: this may discard some precision, but for JS there's no other option.
-  res->SetDouble("reads", static_cast<double>(reads));
-  res->SetDouble("reads_merged", static_cast<double>(reads_merged));
-  res->SetDouble("sectors_read", static_cast<double>(sectors_read));
-  res->SetDouble("read_time", static_cast<double>(read_time));
-  res->SetDouble("writes", static_cast<double>(writes));
-  res->SetDouble("writes_merged", static_cast<double>(writes_merged));
-  res->SetDouble("sectors_written", static_cast<double>(sectors_written));
-  res->SetDouble("write_time", static_cast<double>(write_time));
-  res->SetDouble("io", static_cast<double>(io));
-  res->SetDouble("io_time", static_cast<double>(io_time));
-  res->SetDouble("weighted_io_time", static_cast<double>(weighted_io_time));
-
-  return std::move(res);
-}
-
-bool IsValidDiskName(StringPiece candidate) {
-  if (candidate.length() < 3)
-    return false;
-
-  if (candidate[1] == 'd' &&
-      (candidate[0] == 'h' || candidate[0] == 's' || candidate[0] == 'v')) {
-    // [hsv]d[a-z]+ case
-    for (size_t i = 2; i < candidate.length(); ++i) {
-      if (!islower(candidate[i]))
-        return false;
-    }
-    return true;
-  }
-
-  const char kMMCName[] = "mmcblk";
-  if (!candidate.starts_with(kMMCName))
-    return false;
-
-  // mmcblk[0-9]+ case
-  for (size_t i = strlen(kMMCName); i < candidate.length(); ++i) {
-    if (!isdigit(candidate[i]))
-      return false;
-  }
-  return true;
-}
-
-bool GetSystemDiskInfo(SystemDiskInfo* diskinfo) {
-  // Synchronously reading files in /proc does not hit the disk.
-  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<StringPiece> diskinfo_lines = SplitStringPiece(
-      diskinfo_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY);
-  if (diskinfo_lines.empty()) {
-    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 (const StringPiece& line : diskinfo_lines) {
-    std::vector<StringPiece> disk_fields = SplitStringPiece(
-        line, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
-
-    // Fields may have overflowed and reset to zero.
-    if (!IsValidDiskName(disk_fields[kDiskDriveName].as_string()))
-      continue;
-
-    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;
-}
-
-TimeDelta GetUserCpuTimeSinceBoot() {
-  return internal::GetUserCpuTimeSinceBoot();
-}
-
-#if defined(OS_CHROMEOS)
-std::unique_ptr<Value> SwapInfo::ToValue() const {
-  auto res = std::make_unique<DictionaryValue>();
-
-  // Write out uint64_t variables as doubles.
-  // Note: this may discard some precision, but for JS there's no other option.
-  res->SetDouble("num_reads", static_cast<double>(num_reads));
-  res->SetDouble("num_writes", static_cast<double>(num_writes));
-  res->SetDouble("orig_data_size", static_cast<double>(orig_data_size));
-  res->SetDouble("compr_data_size", static_cast<double>(compr_data_size));
-  res->SetDouble("mem_used_total", static_cast<double>(mem_used_total));
-  double ratio = compr_data_size ? static_cast<double>(orig_data_size) /
-                                       static_cast<double>(compr_data_size)
-                                 : 0;
-  res->SetDouble("compression_ratio", ratio);
-
-  return std::move(res);
-}
-
-bool ParseZramMmStat(StringPiece mm_stat_data, SwapInfo* swap_info) {
-  // There are 7 columns in /sys/block/zram0/mm_stat,
-  // split by several spaces. The first three columns
-  // are orig_data_size, compr_data_size and mem_used_total.
-  // Example:
-  // 17715200 5008166 566062  0 1225715712  127 183842
-  //
-  // For more details:
-  // https://www.kernel.org/doc/Documentation/blockdev/zram.txt
-
-  std::vector<StringPiece> tokens = SplitStringPiece(
-      mm_stat_data, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
-  if (tokens.size() < 7) {
-    DLOG(WARNING) << "zram mm_stat: tokens: " << tokens.size()
-                  << " malformed line: " << mm_stat_data.as_string();
-    return false;
-  }
-
-  if (!StringToUint64(tokens[0], &swap_info->orig_data_size))
-    return false;
-  if (!StringToUint64(tokens[1], &swap_info->compr_data_size))
-    return false;
-  if (!StringToUint64(tokens[2], &swap_info->mem_used_total))
-    return false;
-
-  return true;
-}
-
-bool ParseZramStat(StringPiece stat_data, SwapInfo* swap_info) {
-  // There are 11 columns in /sys/block/zram0/stat,
-  // split by several spaces. The first column is read I/Os
-  // and fifth column is write I/Os.
-  // Example:
-  // 299    0    2392    0    1    0    8    0    0    0    0
-  //
-  // For more details:
-  // https://www.kernel.org/doc/Documentation/blockdev/zram.txt
-
-  std::vector<StringPiece> tokens = SplitStringPiece(
-      stat_data, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
-  if (tokens.size() < 11) {
-    DLOG(WARNING) << "zram stat: tokens: " << tokens.size()
-                  << " malformed line: " << stat_data.as_string();
-    return false;
-  }
-
-  if (!StringToUint64(tokens[0], &swap_info->num_reads))
-    return false;
-  if (!StringToUint64(tokens[4], &swap_info->num_writes))
-    return false;
-
-  return true;
-}
-
-namespace {
-
-bool IgnoreZramFirstPage(uint64_t orig_data_size, SwapInfo* swap_info) {
-  if (orig_data_size <= 4096) {
-    // A single page is compressed at startup, and has a high compression
-    // ratio. 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 true;
-  }
-  return false;
-}
-
-void ParseZramPath(SwapInfo* swap_info) {
-  FilePath zram_path("/sys/block/zram0");
-  uint64_t orig_data_size =
-      ReadFileToUint64(zram_path.Append("orig_data_size"));
-  if (IgnoreZramFirstPage(orig_data_size, swap_info))
-    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"));
-}
-
-bool GetSwapInfoImpl(SwapInfo* swap_info) {
-  // Synchronously reading files in /sys/block/zram0 does not hit the disk.
-  ThreadRestrictions::ScopedAllowIO allow_io;
-
-  // Since ZRAM update, it shows the usage data in different places.
-  // If file "/sys/block/zram0/mm_stat" exists, use the new way, otherwise,
-  // use the old way.
-  static Optional<bool> use_new_zram_interface;
-  FilePath zram_mm_stat_file("/sys/block/zram0/mm_stat");
-  if (!use_new_zram_interface.has_value()) {
-    use_new_zram_interface = PathExists(zram_mm_stat_file);
-  }
-
-  if (!use_new_zram_interface.value()) {
-    ParseZramPath(swap_info);
-    return true;
-  }
-
-  std::string mm_stat_data;
-  if (!ReadFileToString(zram_mm_stat_file, &mm_stat_data)) {
-    DLOG(WARNING) << "Failed to open " << zram_mm_stat_file.value();
-    return false;
-  }
-  if (!ParseZramMmStat(mm_stat_data, swap_info)) {
-    DLOG(WARNING) << "Failed to parse " << zram_mm_stat_file.value();
-    return false;
-  }
-  if (IgnoreZramFirstPage(swap_info->orig_data_size, swap_info))
-    return true;
-
-  FilePath zram_stat_file("/sys/block/zram0/stat");
-  std::string stat_data;
-  if (!ReadFileToString(zram_stat_file, &stat_data)) {
-    DLOG(WARNING) << "Failed to open " << zram_stat_file.value();
-    return false;
-  }
-  if (!ParseZramStat(stat_data, swap_info)) {
-    DLOG(WARNING) << "Failed to parse " << zram_stat_file.value();
-    return false;
-  }
-
-  return true;
-}
-
-}  // namespace
-
-bool GetSwapInfo(SwapInfo* swap_info) {
-  if (!GetSwapInfoImpl(swap_info)) {
-    *swap_info = SwapInfo();
-    return false;
-  }
-  return true;
-}
-#endif  // defined(OS_CHROMEOS)
-
-#if defined(OS_LINUX) || defined(OS_AIX)
-int ProcessMetrics::GetIdleWakeupsPerSecond() {
-  uint64_t num_switches;
-  static const char kSwitchStat[] = "voluntary_ctxt_switches";
-  return ReadProcStatusAndGetFieldAsUint64(process_, kSwitchStat, &num_switches)
-             ? CalculateIdleWakeupsPerSecond(num_switches)
-             : 0;
-}
-#endif  // defined(OS_LINUX) || defined(OS_AIX)
-
-}  // namespace base
diff --git a/base/process/process_metrics_mac.cc b/base/process/process_metrics_mac.cc
deleted file mode 100644
index 4ecf8cf..0000000
--- a/base/process/process_metrics_mac.cc
+++ /dev/null
@@ -1,302 +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/process_metrics.h"
-
-#include <mach/mach.h>
-#include <mach/mach_vm.h>
-#include <mach/shared_region.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <sys/sysctl.h>
-
-#include "base/containers/hash_tables.h"
-#include "base/logging.h"
-#include "base/mac/mac_util.h"
-#include "base/mac/mach_logging.h"
-#include "base/mac/scoped_mach_port.h"
-#include "base/memory/ptr_util.h"
-#include "base/numerics/safe_conversions.h"
-#include "base/numerics/safe_math.h"
-#include "base/process/process_metrics_iocounters.h"
-
-namespace base {
-
-namespace {
-
-#if !defined(MAC_OS_X_VERSION_10_11) || \
-    MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_11
-// The |phys_footprint| field was introduced in 10.11.
-struct ChromeTaskVMInfo {
-  mach_vm_size_t virtual_size;
-  integer_t region_count;
-  integer_t page_size;
-  mach_vm_size_t resident_size;
-  mach_vm_size_t resident_size_peak;
-  mach_vm_size_t device;
-  mach_vm_size_t device_peak;
-  mach_vm_size_t internal;
-  mach_vm_size_t internal_peak;
-  mach_vm_size_t external;
-  mach_vm_size_t external_peak;
-  mach_vm_size_t reusable;
-  mach_vm_size_t reusable_peak;
-  mach_vm_size_t purgeable_volatile_pmap;
-  mach_vm_size_t purgeable_volatile_resident;
-  mach_vm_size_t purgeable_volatile_virtual;
-  mach_vm_size_t compressed;
-  mach_vm_size_t compressed_peak;
-  mach_vm_size_t compressed_lifetime;
-  mach_vm_size_t phys_footprint;
-};
-#else
-using ChromeTaskVMInfo = task_vm_info;
-#endif  // MAC_OS_X_VERSION_10_11
-mach_msg_type_number_t ChromeTaskVMInfoCount =
-    sizeof(ChromeTaskVMInfo) / sizeof(natural_t);
-
-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;
-}
-
-MachVMRegionResult ParseOutputFromMachVMRegion(kern_return_t kr) {
-  if (kr == KERN_INVALID_ADDRESS) {
-    // We're at the end of the address space.
-    return MachVMRegionResult::Finished;
-  } else if (kr != KERN_SUCCESS) {
-    return MachVMRegionResult::Error;
-  }
-  return MachVMRegionResult::Success;
-}
-
-bool GetPowerInfo(mach_port_t task, task_power_info* power_info_data) {
-  if (task == MACH_PORT_NULL)
-    return false;
-
-  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);
-  // Most likely cause for failure: |task| is a zombie.
-  return kr == KERN_SUCCESS;
-}
-
-}  // 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
-std::unique_ptr<ProcessMetrics> ProcessMetrics::CreateProcessMetrics(
-    ProcessHandle process,
-    PortProvider* port_provider) {
-  return WrapUnique(new ProcessMetrics(process, port_provider));
-}
-
-ProcessMetrics::TaskVMInfo ProcessMetrics::GetTaskVMInfo() const {
-  TaskVMInfo info;
-  ChromeTaskVMInfo task_vm_info;
-  mach_msg_type_number_t count = ChromeTaskVMInfoCount;
-  kern_return_t result =
-      task_info(TaskForPid(process_), TASK_VM_INFO,
-                reinterpret_cast<task_info_t>(&task_vm_info), &count);
-  if (result != KERN_SUCCESS)
-    return info;
-
-  info.internal = task_vm_info.internal;
-  info.compressed = task_vm_info.compressed;
-  if (count == ChromeTaskVMInfoCount)
-    info.phys_footprint = task_vm_info.phys_footprint;
-  return info;
-}
-
-#define TIME_VALUE_TO_TIMEVAL(a, r) do {  \
-  (r)->tv_sec = (a)->seconds;             \
-  (r)->tv_usec = (a)->microseconds;       \
-} while (0)
-
-TimeDelta ProcessMetrics::GetCumulativeCPUUsage() {
-  mach_port_t task = TaskForPid(process_);
-  if (task == MACH_PORT_NULL)
-    return TimeDelta();
-
-  // 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 TimeDelta();
-  }
-
-  task_basic_info_64 task_info_data;
-  if (!GetTaskInfo(task, &task_info_data))
-    return TimeDelta();
-
-  /* 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);
-
-  return TimeDelta::FromMicroseconds(TimeValToMicroseconds(task_timeval));
-}
-
-int ProcessMetrics::GetPackageIdleWakeupsPerSecond() {
-  mach_port_t task = TaskForPid(process_);
-  task_power_info power_info_data;
-
-  GetPowerInfo(task, &power_info_data);
-
-  // The task_power_info struct contains two wakeup counters:
-  // task_interrupt_wakeups and task_platform_idle_wakeups.
-  // task_interrupt_wakeups is the total number of wakeups generated by the
-  // process, and is the number that Activity Monitor reports.
-  // task_platform_idle_wakeups is a subset of task_interrupt_wakeups that
-  // tallies the number of times the processor was taken out of its low-power
-  // idle state to handle a wakeup. task_platform_idle_wakeups therefore result
-  // in a greater power increase than the other interrupts which occur while the
-  // CPU is already working, and reducing them has a greater overall impact on
-  // power usage. See the powermetrics man page for more info.
-  return CalculatePackageIdleWakeupsPerSecond(
-      power_info_data.task_platform_idle_wakeups);
-}
-
-int ProcessMetrics::GetIdleWakeupsPerSecond() {
-  mach_port_t task = TaskForPid(process_);
-  task_power_info power_info_data;
-
-  GetPowerInfo(task, &power_info_data);
-
-  return CalculateIdleWakeupsPerSecond(power_info_data.task_interrupt_wakeups);
-}
-
-bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
-  return false;
-}
-
-ProcessMetrics::ProcessMetrics(ProcessHandle process,
-                               PortProvider* port_provider)
-    : process_(process),
-      last_absolute_idle_wakeups_(0),
-      last_absolute_package_idle_wakeups_(0),
-      port_provider_(port_provider) {}
-
-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() {
-  base::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.get(), 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;
-}
-
-bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
-  struct host_basic_info hostinfo;
-  mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
-  base::mac::ScopedMachSendRight host(mach_host_self());
-  int result = host_info(host.get(), HOST_BASIC_INFO,
-                         reinterpret_cast<host_info_t>(&hostinfo), &count);
-  if (result != KERN_SUCCESS)
-    return false;
-
-  DCHECK_EQ(HOST_BASIC_INFO_COUNT, count);
-  meminfo->total = static_cast<int>(hostinfo.max_mem / 1024);
-
-  vm_statistics64_data_t vm_info;
-  count = HOST_VM_INFO64_COUNT;
-
-  if (host_statistics64(host.get(), HOST_VM_INFO64,
-                        reinterpret_cast<host_info64_t>(&vm_info),
-                        &count) != KERN_SUCCESS) {
-    return false;
-  }
-  DCHECK_EQ(HOST_VM_INFO64_COUNT, count);
-
-  static_assert(PAGE_SIZE % 1024 == 0, "Invalid page size");
-  meminfo->free = saturated_cast<int>(
-      PAGE_SIZE / 1024 * (vm_info.free_count - vm_info.speculative_count));
-  meminfo->speculative =
-      saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.speculative_count);
-  meminfo->file_backed =
-      saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.external_page_count);
-  meminfo->purgeable =
-      saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.purgeable_count);
-
-  return true;
-}
-
-// Both |size| and |address| are in-out parameters.
-// |info| is an output parameter, only valid on Success.
-MachVMRegionResult GetTopInfo(mach_port_t task,
-                              mach_vm_size_t* size,
-                              mach_vm_address_t* address,
-                              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);
-  // 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(task, object_name);
-  return ParseOutputFromMachVMRegion(kr);
-}
-
-MachVMRegionResult GetBasicInfo(mach_port_t task,
-                                mach_vm_size_t* size,
-                                mach_vm_address_t* address,
-                                vm_region_basic_info_64* info) {
-  mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT_64;
-  mach_port_t object_name;
-  kern_return_t kr = mach_vm_region(
-      task, address, size, VM_REGION_BASIC_INFO_64,
-      reinterpret_cast<vm_region_info_t>(info), &info_count, &object_name);
-  // 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(task, object_name);
-  return ParseOutputFromMachVMRegion(kr);
-}
-
-}  // namespace base
diff --git a/base/process/process_metrics_nacl.cc b/base/process/process_metrics_nacl.cc
deleted file mode 100644
index 025ffd5..0000000
--- a/base/process/process_metrics_nacl.cc
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2015 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/process_metrics.h"
-
-#include <stddef.h>
-#include <unistd.h>
-
-namespace base {
-
-size_t GetPageSize() {
-  return getpagesize();
-}
-
-}  // namespace base
diff --git a/base/process/process_metrics_openbsd.cc b/base/process/process_metrics_openbsd.cc
deleted file mode 100644
index 509ed0b..0000000
--- a/base/process/process_metrics_openbsd.cc
+++ /dev/null
@@ -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.
-
-#include "base/process/process_metrics.h"
-
-#include <stddef.h>
-#include <stdint.h>
-#include <sys/param.h>
-#include <sys/sysctl.h>
-
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/process/process_metrics_iocounters.h"
-
-namespace base {
-
-// static
-std::unique_ptr<ProcessMetrics> ProcessMetrics::CreateProcessMetrics(
-    ProcessHandle process) {
-  return WrapUnique(new ProcessMetrics(process));
-}
-
-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::GetPlatformIndependentCPUUsage() {
-  TimeTicks time = TimeTicks::Now();
-
-  if (last_cpu_time_.is_zero()) {
-    // First call, just set the last values.
-    last_cpu_time_ = time;
-    return 0;
-  }
-
-  int cpu = GetProcessCPU(process_);
-
-  last_cpu_time_ = time;
-  double percentage = static_cast<double>((cpu * 100.0) / FSCALE);
-
-  return percentage;
-}
-
-TimeDelta ProcessMetrics::GetCumulativeCPUUsage() {
-  NOTREACHED();
-  return TimeDelta();
-}
-
-ProcessMetrics::ProcessMetrics(ProcessHandle process)
-    : process_(process),
-      last_cpu_(0) {}
-
-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 base
diff --git a/base/process/process_metrics_posix.cc b/base/process/process_metrics_posix.cc
deleted file mode 100644
index 858ab05..0000000
--- a/base/process/process_metrics_posix.cc
+++ /dev/null
@@ -1,116 +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/process_metrics.h"
-
-#include <limits.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <sys/time.h>
-#include <unistd.h>
-
-#include "base/logging.h"
-#include "build_config.h"
-
-#if !defined(OS_FUCHSIA)
-#include <sys/resource.h>
-#endif
-
-#if defined(OS_MACOSX)
-#include <malloc/malloc.h>
-#else
-#include <malloc.h>
-#endif
-
-namespace base {
-
-int64_t TimeValToMicroseconds(const struct timeval& tv) {
-  int64_t ret = tv.tv_sec;  // Avoid (int * int) integer overflow.
-  ret *= Time::kMicrosecondsPerSecond;
-  ret += tv.tv_usec;
-  return ret;
-}
-
-ProcessMetrics::~ProcessMetrics() = default;
-
-#if !defined(OS_FUCHSIA)
-
-#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_NETBSD)
-static const rlim_t kSystemDefaultMaxFds = 1024;
-#elif defined(OS_OPENBSD)
-static const rlim_t kSystemDefaultMaxFds = 256;
-#elif defined(OS_ANDROID)
-static const rlim_t kSystemDefaultMaxFds = 1024;
-#elif defined(OS_AIX)
-static const rlim_t kSystemDefaultMaxFds = 8192;
-#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 IncreaseFdLimitTo(unsigned int max_descriptors) {
-  struct rlimit limits;
-  if (getrlimit(RLIMIT_NOFILE, &limits) == 0) {
-    unsigned int new_limit = max_descriptors;
-    if (max_descriptors <= limits.rlim_cur)
-      return;
-    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";
-  }
-}
-
-#endif  // !defined(OS_FUCHSIA)
-
-size_t GetPageSize() {
-  return getpagesize();
-}
-
-size_t ProcessMetrics::GetMallocUsage() {
-#if defined(OS_MACOSX) || defined(OS_IOS)
-  malloc_statistics_t stats = {0};
-  malloc_zone_statistics(nullptr, &stats);
-  return stats.size_in_use;
-#elif defined(OS_LINUX) || defined(OS_ANDROID)
-  struct mallinfo minfo = mallinfo();
-#if defined(USE_TCMALLOC)
-  return minfo.uordblks;
-#else
-  return minfo.hblkhd + minfo.arena;
-#endif
-#elif defined(OS_FUCHSIA)
-  // TODO(fuchsia): Not currently exposed. https://crbug.com/735087.
-  return 0;
-#endif
-}
-
-}  // namespace base
diff --git a/base/process/process_metrics_win.cc b/base/process/process_metrics_win.cc
deleted file mode 100644
index 18ef58a..0000000
--- a/base/process/process_metrics_win.cc
+++ /dev/null
@@ -1,207 +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/process_metrics.h"
-
-#include <windows.h>  // Must be in front of other Windows header files.
-
-#include <psapi.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <winternl.h>
-
-#include <algorithm>
-
-#include "base/logging.h"
-#include "base/memory/ptr_util.h"
-#include "base/process/memory.h"
-#include "base/process/process_metrics_iocounters.h"
-#include "base/sys_info.h"
-
-namespace base {
-namespace {
-
-// System pagesize. This value remains constant on x86/64 architectures.
-const int PAGESIZE_KB = 4;
-
-typedef NTSTATUS(WINAPI* NTQUERYSYSTEMINFORMATION)(
-    SYSTEM_INFORMATION_CLASS SystemInformationClass,
-    PVOID SystemInformation,
-    ULONG SystemInformationLength,
-    PULONG ReturnLength);
-
-}  // namespace
-
-ProcessMetrics::~ProcessMetrics() { }
-
-size_t GetMaxFds() {
-  // Windows is only limited by the amount of physical memory.
-  return std::numeric_limits<size_t>::max();
-}
-
-// static
-std::unique_ptr<ProcessMetrics> ProcessMetrics::CreateProcessMetrics(
-    ProcessHandle process) {
-  return WrapUnique(new ProcessMetrics(process));
-}
-
-namespace {
-
-class WorkingSetInformationBuffer {
- public:
-  WorkingSetInformationBuffer() {}
-  ~WorkingSetInformationBuffer() { Clear(); }
-
-  bool Reserve(size_t size) {
-    Clear();
-    // Use UncheckedMalloc here because this can be called from the code
-    // that handles low memory condition.
-    return UncheckedMalloc(size, reinterpret_cast<void**>(&buffer_));
-  }
-
-  const PSAPI_WORKING_SET_INFORMATION* operator ->() const { return buffer_; }
-
-  size_t GetPageEntryCount() const { return number_of_entries; }
-
-  // This function is used to get page entries for a process.
-  bool QueryPageEntries(const ProcessHandle& process) {
-    int retries = 5;
-    number_of_entries = 4096;  // Just a guess.
-
-    for (;;) {
-      size_t buffer_size =
-          sizeof(PSAPI_WORKING_SET_INFORMATION) +
-          (number_of_entries * sizeof(PSAPI_WORKING_SET_BLOCK));
-
-      if (!Reserve(buffer_size))
-        return false;
-
-      // On success, |buffer_| is populated with info about the working set of
-      // |process|. On ERROR_BAD_LENGTH failure, increase the size of the
-      // buffer and try again.
-      if (QueryWorkingSet(process, buffer_, buffer_size))
-        break;  // Success
-
-      if (GetLastError() != ERROR_BAD_LENGTH)
-        return false;
-
-      number_of_entries = buffer_->NumberOfEntries;
-
-      // Maybe some entries are being added right now. Increase the buffer to
-      // take that into account. Increasing by 10% should generally be enough,
-      // especially considering the potentially low memory condition during the
-      // call (when called from OomMemoryDetails) and the potentially high
-      // number of entries (300K was observed in crash dumps).
-      number_of_entries *= 1.1;
-
-      if (--retries == 0) {
-        // If we're looping, eventually fail.
-        return false;
-      }
-    }
-
-    // TODO(chengx): Remove the comment and the logic below. It is no longer
-    // needed since we don't have Win2000 support.
-    // On windows 2000 the function returns 1 even when the buffer is too small.
-    // The number of entries that we are going to parse is the minimum between
-    // the size we allocated and the real number of entries.
-    number_of_entries = std::min(number_of_entries,
-                                 static_cast<size_t>(buffer_->NumberOfEntries));
-
-    return true;
-  }
-
- private:
-  void Clear() {
-    free(buffer_);
-    buffer_ = nullptr;
-  }
-
-  PSAPI_WORKING_SET_INFORMATION* buffer_ = nullptr;
-
-  // Number of page entries.
-  size_t number_of_entries = 0;
-
-  DISALLOW_COPY_AND_ASSIGN(WorkingSetInformationBuffer);
-};
-
-}  // namespace
-
-TimeDelta ProcessMetrics::GetCumulativeCPUUsage() {
-  FILETIME creation_time;
-  FILETIME exit_time;
-  FILETIME kernel_time;
-  FILETIME user_time;
-
-  if (!GetProcessTimes(process_.Get(), &creation_time, &exit_time, &kernel_time,
-                       &user_time)) {
-    // We don't assert here because in some cases (such as in the Task Manager)
-    // we may call this function on a process that has just exited but we have
-    // not yet received the notification.
-    return TimeDelta();
-  }
-
-  return TimeDelta::FromFileTime(kernel_time) +
-         TimeDelta::FromFileTime(user_time);
-}
-
-bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
-  return GetProcessIoCounters(process_.Get(), io_counters) != FALSE;
-}
-
-ProcessMetrics::ProcessMetrics(ProcessHandle process) {
-  if (process) {
-    HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
-    BOOL result = ::DuplicateHandle(::GetCurrentProcess(), process,
-                                    ::GetCurrentProcess(), &duplicate_handle,
-                                    PROCESS_QUERY_INFORMATION, FALSE, 0);
-    DPCHECK(result);
-    process_.Set(duplicate_handle);
-  }
-}
-
-size_t GetSystemCommitCharge() {
-  // Get the System Page Size.
-  SYSTEM_INFO system_info;
-  GetSystemInfo(&system_info);
-
-  PERFORMANCE_INFORMATION info;
-  if (!GetPerformanceInfo(&info, sizeof(info))) {
-    DLOG(ERROR) << "Failed to fetch internal performance info.";
-    return 0;
-  }
-  return (info.CommitTotal * system_info.dwPageSize) / 1024;
-}
-
-size_t GetPageSize() {
-  return PAGESIZE_KB * 1024;
-}
-
-// This function uses the following mapping between MEMORYSTATUSEX and
-// SystemMemoryInfoKB:
-//   ullTotalPhys ==> total
-//   ullAvailPhys ==> avail_phys
-//   ullTotalPageFile ==> swap_total
-//   ullAvailPageFile ==> swap_free
-bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
-  MEMORYSTATUSEX mem_status;
-  mem_status.dwLength = sizeof(mem_status);
-  if (!::GlobalMemoryStatusEx(&mem_status))
-    return false;
-
-  meminfo->total = mem_status.ullTotalPhys / 1024;
-  meminfo->avail_phys = mem_status.ullAvailPhys / 1024;
-  meminfo->swap_total = mem_status.ullTotalPageFile / 1024;
-  meminfo->swap_free = mem_status.ullAvailPageFile / 1024;
-
-  return true;
-}
-
-size_t ProcessMetrics::GetMallocUsage() {
-  // Unsupported as getting malloc usage on Windows requires iterating through
-  // the heap which is slow and crashes.
-  return 0;
-}
-
-}  // namespace base
diff --git a/base/process/process_posix.cc b/base/process/process_posix.cc
index 6b758a2..57a4f67 100644
--- a/base/process/process_posix.cc
+++ b/base/process/process_posix.cc
@@ -14,7 +14,6 @@
 #include "base/logging.h"
 #include "base/posix/eintr_wrapper.h"
 #include "base/process/kill.h"
-#include "base/threading/thread_restrictions.h"
 #include "build_config.h"
 
 #if defined(OS_MACOSX)
@@ -335,9 +334,6 @@
 }
 
 bool Process::WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const {
-  if (!timeout.is_zero())
-    internal::AssertBaseSyncPrimitivesAllowed();
-
   int local_exit_code;
   bool exited = WaitForExitWithTimeoutImpl(Handle(), &local_exit_code, timeout);
   if (exited) {
diff --git a/base/process/process_win.cc b/base/process/process_win.cc
index 3763d0f..48f598f 100644
--- a/base/process/process_win.cc
+++ b/base/process/process_win.cc
@@ -7,7 +7,6 @@
 #include "base/logging.h"
 #include "base/numerics/safe_conversions.h"
 #include "base/process/kill.h"
-#include "base/threading/thread_restrictions.h"
 
 #include <windows.h>
 
@@ -164,9 +163,6 @@
 }
 
 bool Process::WaitForExitWithTimeout(TimeDelta timeout, int* exit_code) const {
-  if (!timeout.is_zero())
-    internal::AssertBaseSyncPrimitivesAllowed();
-
   // Limit timeout to INFINITE.
   DWORD timeout_ms = saturated_cast<DWORD>(timeout.InMilliseconds());
   if (::WaitForSingleObject(Handle(), timeout_ms) != WAIT_OBJECT_0)
diff --git a/base/rand_util_posix.cc b/base/rand_util_posix.cc
index 2c1653d..4dbb35d 100644
--- a/base/rand_util_posix.cc
+++ b/base/rand_util_posix.cc
@@ -11,7 +11,6 @@
 #include <unistd.h>
 
 #include "base/files/file_util.h"
-#include "base/lazy_instance.h"
 #include "base/logging.h"
 #include "base/posix/eintr_wrapper.h"
 
@@ -43,21 +42,24 @@
   const int fd_;
 };
 
-base::LazyInstance<URandomFd>::Leaky g_urandom_fd = LAZY_INSTANCE_INITIALIZER;
+URandomFd* GetInstance() {
+  static URandomFd* instance = new URandomFd;
+  return instance;
+}
 
 }  // namespace
 
 namespace base {
 
 void RandBytes(void* output, size_t output_length) {
-  const int urandom_fd = g_urandom_fd.Pointer()->fd();
+  const int urandom_fd = GetInstance()->fd();
   const bool success =
       ReadFromFD(urandom_fd, static_cast<char*>(output), output_length);
   CHECK(success);
 }
 
 int GetUrandomFD(void) {
-  return g_urandom_fd.Pointer()->fd();
+  return GetInstance()->fd();
 }
 
 }  // namespace base
diff --git a/base/run_loop.cc b/base/run_loop.cc
deleted file mode 100644
index f15d62a..0000000
--- a/base/run_loop.cc
+++ /dev/null
@@ -1,298 +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 "base/run_loop.h"
-
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/lazy_instance.h"
-#include "base/message_loop/message_loop.h"
-#include "base/single_thread_task_runner.h"
-#include "base/threading/thread_local.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "build_config.h"
-
-namespace base {
-
-namespace {
-
-LazyInstance<ThreadLocalPointer<RunLoop::Delegate>>::Leaky tls_delegate =
-    LAZY_INSTANCE_INITIALIZER;
-
-// Runs |closure| immediately if this is called on |task_runner|, otherwise
-// forwards |closure| to it.
-void ProxyToTaskRunner(scoped_refptr<SequencedTaskRunner> task_runner,
-                       OnceClosure closure) {
-  if (task_runner->RunsTasksInCurrentSequence()) {
-    std::move(closure).Run();
-    return;
-  }
-  task_runner->PostTask(FROM_HERE, std::move(closure));
-}
-
-}  // namespace
-
-RunLoop::Delegate::Delegate() {
-  // The Delegate can be created on another thread. It is only bound in
-  // RegisterDelegateForCurrentThread().
-  DETACH_FROM_THREAD(bound_thread_checker_);
-}
-
-RunLoop::Delegate::~Delegate() {
-  DCHECK_CALLED_ON_VALID_THREAD(bound_thread_checker_);
-  // A RunLoop::Delegate may be destroyed before it is bound, if so it may still
-  // be on its creation thread (e.g. a Thread that fails to start) and
-  // shouldn't disrupt that thread's state.
-  if (bound_)
-    tls_delegate.Get().Set(nullptr);
-}
-
-bool RunLoop::Delegate::ShouldQuitWhenIdle() {
-  return active_run_loops_.top()->quit_when_idle_received_;
-}
-
-// static
-void RunLoop::RegisterDelegateForCurrentThread(Delegate* delegate) {
-  // Bind |delegate| to this thread.
-  DCHECK(!delegate->bound_);
-  DCHECK_CALLED_ON_VALID_THREAD(delegate->bound_thread_checker_);
-
-  // There can only be one RunLoop::Delegate per thread.
-  DCHECK(!tls_delegate.Get().Get())
-      << "Error: Multiple RunLoop::Delegates registered on the same thread.\n\n"
-         "Hint: You perhaps instantiated a second "
-         "MessageLoop/ScopedTaskEnvironment on a thread that already had one?";
-  tls_delegate.Get().Set(delegate);
-  delegate->bound_ = true;
-}
-
-RunLoop::RunLoop(Type type)
-    : delegate_(tls_delegate.Get().Get()),
-      type_(type),
-      origin_task_runner_(ThreadTaskRunnerHandle::Get()),
-      weak_factory_(this) {
-  DCHECK(delegate_) << "A RunLoop::Delegate must be bound to this thread prior "
-                       "to using RunLoop.";
-  DCHECK(origin_task_runner_);
-}
-
-RunLoop::~RunLoop() {
-  // TODO(gab): Fix bad usage and enable this check, http://crbug.com/715235.
-  // DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-}
-
-void RunLoop::Run() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
-  if (!BeforeRun())
-    return;
-
-  // It is okay to access this RunLoop from another sequence while Run() is
-  // active as this RunLoop won't touch its state until after that returns (if
-  // the RunLoop's state is accessed while processing Run(), it will be re-bound
-  // to the accessing sequence for the remainder of that Run() -- accessing from
-  // multiple sequences is still disallowed).
-  DETACH_FROM_SEQUENCE(sequence_checker_);
-
-  DCHECK_EQ(this, delegate_->active_run_loops_.top());
-  const bool application_tasks_allowed =
-      delegate_->active_run_loops_.size() == 1U ||
-      type_ == Type::kNestableTasksAllowed;
-  delegate_->Run(application_tasks_allowed);
-
-  // Rebind this RunLoop to the current thread after Run().
-  DETACH_FROM_SEQUENCE(sequence_checker_);
-  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
-  AfterRun();
-}
-
-void RunLoop::RunUntilIdle() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
-  quit_when_idle_received_ = true;
-  Run();
-}
-
-void RunLoop::Quit() {
-  // Thread-safe.
-
-  // This can only be hit if run_loop->Quit() is called directly (QuitClosure()
-  // proxies through ProxyToTaskRunner() as it can only deref its WeakPtr on
-  // |origin_task_runner_|).
-  if (!origin_task_runner_->RunsTasksInCurrentSequence()) {
-    origin_task_runner_->PostTask(
-        FROM_HERE, base::BindOnce(&RunLoop::Quit, Unretained(this)));
-    return;
-  }
-
-  quit_called_ = true;
-  if (running_ && delegate_->active_run_loops_.top() == this) {
-    // This is the inner-most RunLoop, so quit now.
-    delegate_->Quit();
-  }
-}
-
-void RunLoop::QuitWhenIdle() {
-  // Thread-safe.
-
-  // This can only be hit if run_loop->QuitWhenIdle() is called directly
-  // (QuitWhenIdleClosure() proxies through ProxyToTaskRunner() as it can only
-  // deref its WeakPtr on |origin_task_runner_|).
-  if (!origin_task_runner_->RunsTasksInCurrentSequence()) {
-    origin_task_runner_->PostTask(
-        FROM_HERE, base::BindOnce(&RunLoop::QuitWhenIdle, Unretained(this)));
-    return;
-  }
-
-  quit_when_idle_received_ = true;
-}
-
-base::Closure RunLoop::QuitClosure() {
-  // TODO(gab): Fix bad usage and enable this check, http://crbug.com/715235.
-  // DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
-  // Need to use ProxyToTaskRunner() as WeakPtrs vended from
-  // |weak_factory_| may only be accessed on |origin_task_runner_|.
-  // TODO(gab): It feels wrong that QuitClosure() is bound to a WeakPtr.
-  return base::Bind(&ProxyToTaskRunner, origin_task_runner_,
-                    base::Bind(&RunLoop::Quit, weak_factory_.GetWeakPtr()));
-}
-
-base::Closure RunLoop::QuitWhenIdleClosure() {
-  // TODO(gab): Fix bad usage and enable this check, http://crbug.com/715235.
-  // DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
-  // Need to use ProxyToTaskRunner() as WeakPtrs vended from
-  // |weak_factory_| may only be accessed on |origin_task_runner_|.
-  // TODO(gab): It feels wrong that QuitWhenIdleClosure() is bound to a WeakPtr.
-  return base::Bind(
-      &ProxyToTaskRunner, origin_task_runner_,
-      base::Bind(&RunLoop::QuitWhenIdle, weak_factory_.GetWeakPtr()));
-}
-
-// static
-bool RunLoop::IsRunningOnCurrentThread() {
-  Delegate* delegate = tls_delegate.Get().Get();
-  return delegate && !delegate->active_run_loops_.empty();
-}
-
-// static
-bool RunLoop::IsNestedOnCurrentThread() {
-  Delegate* delegate = tls_delegate.Get().Get();
-  return delegate && delegate->active_run_loops_.size() > 1;
-}
-
-// static
-void RunLoop::AddNestingObserverOnCurrentThread(NestingObserver* observer) {
-  Delegate* delegate = tls_delegate.Get().Get();
-  DCHECK(delegate);
-  delegate->nesting_observers_.AddObserver(observer);
-}
-
-// static
-void RunLoop::RemoveNestingObserverOnCurrentThread(NestingObserver* observer) {
-  Delegate* delegate = tls_delegate.Get().Get();
-  DCHECK(delegate);
-  delegate->nesting_observers_.RemoveObserver(observer);
-}
-
-// static
-void RunLoop::QuitCurrentDeprecated() {
-  DCHECK(IsRunningOnCurrentThread());
-  tls_delegate.Get().Get()->active_run_loops_.top()->Quit();
-}
-
-// static
-void RunLoop::QuitCurrentWhenIdleDeprecated() {
-  DCHECK(IsRunningOnCurrentThread());
-  tls_delegate.Get().Get()->active_run_loops_.top()->QuitWhenIdle();
-}
-
-// static
-Closure RunLoop::QuitCurrentWhenIdleClosureDeprecated() {
-  return Bind(&RunLoop::QuitCurrentWhenIdleDeprecated);
-}
-
-#if DCHECK_IS_ON()
-RunLoop::ScopedDisallowRunningForTesting::ScopedDisallowRunningForTesting()
-    : current_delegate_(tls_delegate.Get().Get()),
-      previous_run_allowance_(
-          current_delegate_ ? current_delegate_->allow_running_for_testing_
-                            : false) {
-  if (current_delegate_)
-    current_delegate_->allow_running_for_testing_ = false;
-}
-
-RunLoop::ScopedDisallowRunningForTesting::~ScopedDisallowRunningForTesting() {
-  DCHECK_EQ(current_delegate_, tls_delegate.Get().Get());
-  if (current_delegate_)
-    current_delegate_->allow_running_for_testing_ = previous_run_allowance_;
-}
-#else   // DCHECK_IS_ON()
-// Defined out of line so that the compiler doesn't inline these and realize
-// the scope has no effect and then throws an "unused variable" warning in
-// non-dcheck builds.
-RunLoop::ScopedDisallowRunningForTesting::ScopedDisallowRunningForTesting() =
-    default;
-RunLoop::ScopedDisallowRunningForTesting::~ScopedDisallowRunningForTesting() =
-    default;
-#endif  // DCHECK_IS_ON()
-
-bool RunLoop::BeforeRun() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
-#if DCHECK_IS_ON()
-  DCHECK(delegate_->allow_running_for_testing_)
-      << "RunLoop::Run() isn't allowed in the scope of a "
-         "ScopedDisallowRunningForTesting. Hint: if mixing "
-         "TestMockTimeTaskRunners on same thread, use TestMockTimeTaskRunner's "
-         "API instead of RunLoop to drive individual task runners.";
-  DCHECK(!run_called_);
-  run_called_ = true;
-#endif  // DCHECK_IS_ON()
-
-  // Allow Quit to be called before Run.
-  if (quit_called_)
-    return false;
-
-  auto& active_run_loops_ = delegate_->active_run_loops_;
-  active_run_loops_.push(this);
-
-  const bool is_nested = active_run_loops_.size() > 1;
-
-  if (is_nested) {
-    for (auto& observer : delegate_->nesting_observers_)
-      observer.OnBeginNestedRunLoop();
-    if (type_ == Type::kNestableTasksAllowed)
-      delegate_->EnsureWorkScheduled();
-  }
-
-  running_ = true;
-  return true;
-}
-
-void RunLoop::AfterRun() {
-  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-
-  running_ = false;
-
-  auto& active_run_loops_ = delegate_->active_run_loops_;
-  DCHECK_EQ(active_run_loops_.top(), this);
-  active_run_loops_.pop();
-
-  RunLoop* previous_run_loop =
-      active_run_loops_.empty() ? nullptr : active_run_loops_.top();
-
-  if (previous_run_loop) {
-    for (auto& observer : delegate_->nesting_observers_)
-      observer.OnExitNestedRunLoop();
-  }
-
-  // Execute deferred Quit, if any:
-  if (previous_run_loop && previous_run_loop->quit_called_)
-    delegate_->Quit();
-}
-
-}  // namespace base
diff --git a/base/run_loop.h b/base/run_loop.h
deleted file mode 100644
index 493d934..0000000
--- a/base/run_loop.h
+++ /dev/null
@@ -1,304 +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_RUN_LOOP_H_
-#define BASE_RUN_LOOP_H_
-
-#include <utility>
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/containers/stack.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/weak_ptr.h"
-#include "base/observer_list.h"
-#include "base/sequence_checker.h"
-#include "base/threading/thread_checker.h"
-#include "build_config.h"
-
-namespace base {
-#if defined(OS_ANDROID)
-class MessagePumpForUI;
-#endif
-
-#if defined(OS_IOS)
-class MessagePumpUIApplication;
-#endif
-
-class SingleThreadTaskRunner;
-
-// Helper class to run the RunLoop::Delegate associated with the current thread.
-// A RunLoop::Delegate must have been bound to this thread (ref.
-// RunLoop::RegisterDelegateForCurrentThread()) prior to using any of RunLoop's
-// member and static methods unless explicitly indicated otherwise (e.g.
-// IsRunning/IsNestedOnCurrentThread()). RunLoop::Run can only be called once
-// per RunLoop lifetime. Create a RunLoop on the stack and call Run/Quit to run
-// a nested RunLoop but please do not use nested loops in production code!
-class BASE_EXPORT RunLoop {
- public:
-  // The type of RunLoop: a kDefault RunLoop at the top-level (non-nested) will
-  // process system and application tasks assigned to its Delegate. When nested
-  // however a kDefault RunLoop will only process system tasks while a
-  // kNestableTasksAllowed RunLoop will continue to process application tasks
-  // even if nested.
-  //
-  // This is relevant in the case of recursive RunLoops. Some unwanted run loops
-  // may occur when using common controls or printer functions. By default,
-  // recursive task processing is disabled.
-  //
-  // In general, nestable RunLoops are to be avoided. They are dangerous and
-  // difficult to get right, so please use with extreme caution.
-  //
-  // A specific example where this makes a difference is:
-  // - The thread is running a RunLoop.
-  // - It receives a task #1 and executes it.
-  // - The task #1 implicitly starts a RunLoop, like a MessageBox in the unit
-  //   test. This can also be StartDoc or GetSaveFileName.
-  // - The thread receives a task #2 before or while in this second RunLoop.
-  // - With a kNestableTasksAllowed RunLoop, the task #2 will run right away.
-  //   Otherwise, it will get executed right after task #1 completes in the main
-  //   RunLoop.
-  enum class Type {
-    kDefault,
-    kNestableTasksAllowed,
-  };
-
-  RunLoop(Type type = Type::kDefault);
-  ~RunLoop();
-
-  // Run the current RunLoop::Delegate. This blocks until Quit is called. Before
-  // calling Run, be sure to grab the QuitClosure in order to stop the
-  // RunLoop::Delegate asynchronously.
-  void Run();
-
-  // Run the current RunLoop::Delegate until it doesn't find any tasks or
-  // messages in its queue (it goes idle). WARNING: This may never return! Only
-  // use this when repeating tasks such as animated web pages have been shut
-  // down.
-  void RunUntilIdle();
-
-  bool running() const {
-    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
-    return running_;
-  }
-
-  // Quit() quits an earlier call to Run() immediately. QuitWhenIdle() quits an
-  // earlier call to Run() when there aren't any tasks or messages in the queue.
-  //
-  // These methods are thread-safe but note that Quit() is best-effort when
-  // called from another thread (will quit soon but tasks that were already
-  // queued on this RunLoop will get to run first).
-  //
-  // There can be other nested RunLoops servicing the same task queue. Quitting
-  // one RunLoop has no bearing on the others. Quit() and QuitWhenIdle() can be
-  // called before, during or after Run(). If called before Run(), Run() will
-  // return immediately when called. Calling Quit() or QuitWhenIdle() after the
-  // RunLoop has already finished running has no effect.
-  //
-  // WARNING: You must NEVER assume that a call to Quit() or QuitWhenIdle() will
-  // terminate the targetted message loop. If a nested RunLoop continues
-  // running, the target may NEVER terminate. It is very easy to livelock (run
-  // forever) in such a case.
-  void Quit();
-  void QuitWhenIdle();
-
-  // Convenience methods to get a closure that safely calls Quit() or
-  // QuitWhenIdle() (has no effect if the RunLoop instance is gone).
-  //
-  // The resulting Closure is thread-safe (note however that invoking the
-  // QuitClosure() from another thread than this RunLoop's will result in an
-  // asynchronous rather than immediate Quit()).
-  //
-  // Example:
-  //   RunLoop run_loop;
-  //   PostTask(run_loop.QuitClosure());
-  //   run_loop.Run();
-  base::Closure QuitClosure();
-  base::Closure QuitWhenIdleClosure();
-
-  // Returns true if there is an active RunLoop on this thread.
-  // Safe to call before RegisterDelegateForCurrentThread().
-  static bool IsRunningOnCurrentThread();
-
-  // Returns true if there is an active RunLoop on this thread and it's nested
-  // within another active RunLoop.
-  // Safe to call before RegisterDelegateForCurrentThread().
-  static bool IsNestedOnCurrentThread();
-
-  // A NestingObserver is notified when a nested RunLoop begins and ends.
-  class BASE_EXPORT NestingObserver {
-   public:
-    // Notified before a nested loop starts running work on the current thread.
-    virtual void OnBeginNestedRunLoop() = 0;
-    // Notified after a nested loop is done running work on the current thread.
-    virtual void OnExitNestedRunLoop() {}
-
-   protected:
-    virtual ~NestingObserver() = default;
-  };
-
-  static void AddNestingObserverOnCurrentThread(NestingObserver* observer);
-  static void RemoveNestingObserverOnCurrentThread(NestingObserver* observer);
-
-  // A RunLoop::Delegate is a generic interface that allows RunLoop to be
-  // separate from the underlying implementation of the message loop for this
-  // thread. It holds private state used by RunLoops on its associated thread.
-  // One and only one RunLoop::Delegate must be registered on a given thread
-  // via RunLoop::RegisterDelegateForCurrentThread() before RunLoop instances
-  // and RunLoop static methods can be used on it.
-  class BASE_EXPORT Delegate {
-   public:
-    Delegate();
-    virtual ~Delegate();
-
-    // Used by RunLoop to inform its Delegate to Run/Quit. Implementations are
-    // expected to keep on running synchronously from the Run() call until the
-    // eventual matching Quit() call. Upon receiving a Quit() call it should
-    // return from the Run() call as soon as possible without executing
-    // remaining tasks/messages. Run() calls can nest in which case each Quit()
-    // call should result in the topmost active Run() call returning. The only
-    // other trigger for Run() to return is the
-    // |should_quit_when_idle_callback_| which the Delegate should probe before
-    // sleeping when it becomes idle. |application_tasks_allowed| is true if
-    // this is the first Run() call on the stack or it was made from a nested
-    // RunLoop of Type::kNestableTasksAllowed (otherwise this Run() level should
-    // only process system tasks).
-    virtual void Run(bool application_tasks_allowed) = 0;
-    virtual void Quit() = 0;
-
-    // Invoked right before a RunLoop enters a nested Run() call on this
-    // Delegate iff this RunLoop is of type kNestableTasksAllowed. The Delegate
-    // should ensure that the upcoming Run() call will result in processing
-    // application tasks queued ahead of it without further probing. e.g.
-    // message pumps on some platforms, like Mac, need an explicit request to
-    // process application tasks when nested, otherwise they'll only wait for
-    // system messages.
-    virtual void EnsureWorkScheduled() = 0;
-
-   protected:
-    // Returns the result of this Delegate's |should_quit_when_idle_callback_|.
-    // "protected" so it can be invoked only by the Delegate itself.
-    bool ShouldQuitWhenIdle();
-
-   private:
-    // While the state is owned by the Delegate subclass, only RunLoop can use
-    // it.
-    friend class RunLoop;
-
-    // A vector-based stack is more memory efficient than the default
-    // deque-based stack as the active RunLoop stack isn't expected to ever
-    // have more than a few entries.
-    using RunLoopStack = base::stack<RunLoop*, std::vector<RunLoop*>>;
-
-    RunLoopStack active_run_loops_;
-    ObserverList<RunLoop::NestingObserver> nesting_observers_;
-
-#if DCHECK_IS_ON()
-    bool allow_running_for_testing_ = true;
-#endif
-
-    // True once this Delegate is bound to a thread via
-    // RegisterDelegateForCurrentThread().
-    bool bound_ = false;
-
-    // Thread-affine per its use of TLS.
-    THREAD_CHECKER(bound_thread_checker_);
-
-    DISALLOW_COPY_AND_ASSIGN(Delegate);
-  };
-
-  // Registers |delegate| on the current thread. Must be called once and only
-  // once per thread before using RunLoop methods on it. |delegate| is from then
-  // on forever bound to that thread (including its destruction).
-  static void RegisterDelegateForCurrentThread(Delegate* delegate);
-
-  // Quits the active RunLoop (when idle) -- there must be one. These were
-  // introduced as prefered temporary replacements to the long deprecated
-  // MessageLoop::Quit(WhenIdle)(Closure) methods. Callers should properly plumb
-  // a reference to the appropriate RunLoop instance (or its QuitClosure)
-  // instead of using these in order to link Run()/Quit() to a single RunLoop
-  // instance and increase readability.
-  static void QuitCurrentDeprecated();
-  static void QuitCurrentWhenIdleDeprecated();
-  static Closure QuitCurrentWhenIdleClosureDeprecated();
-
-  // Run() will DCHECK if called while there's a ScopedDisallowRunningForTesting
-  // in scope on its thread. This is useful to add safety to some test
-  // constructs which allow multiple task runners to share the main thread in
-  // unit tests. While the main thread can be shared by multiple runners to
-  // deterministically fake multi threading, there can still only be a single
-  // RunLoop::Delegate per thread and RunLoop::Run() should only be invoked from
-  // it (or it would result in incorrectly driving TaskRunner A while in
-  // TaskRunner B's context).
-  class BASE_EXPORT ScopedDisallowRunningForTesting {
-   public:
-    ScopedDisallowRunningForTesting();
-    ~ScopedDisallowRunningForTesting();
-
-   private:
-#if DCHECK_IS_ON()
-    Delegate* current_delegate_;
-    const bool previous_run_allowance_;
-#endif  // DCHECK_IS_ON()
-
-    DISALLOW_COPY_AND_ASSIGN(ScopedDisallowRunningForTesting);
-  };
-
- private:
-#if defined(OS_ANDROID)
-  // Android doesn't support the blocking RunLoop::Run, so it calls
-  // BeforeRun and AfterRun directly.
-  friend class base::MessagePumpForUI;
-#endif
-
-#if defined(OS_IOS)
-  // iOS doesn't support the blocking RunLoop::Run, so it calls
-  // BeforeRun directly.
-  friend class base::MessagePumpUIApplication;
-#endif
-
-  // Return false to abort the Run.
-  bool BeforeRun();
-  void AfterRun();
-
-  // A copy of RunLoop::Delegate for the thread driven by tis RunLoop for quick
-  // access without using TLS (also allows access to state from another sequence
-  // during Run(), ref. |sequence_checker_| below).
-  Delegate* delegate_;
-
-  const Type type_;
-
-#if DCHECK_IS_ON()
-  bool run_called_ = false;
-#endif
-
-  bool quit_called_ = false;
-  bool running_ = false;
-  // Used to record that QuitWhenIdle() was called on this RunLoop, meaning that
-  // the Delegate should quit Run() once it becomes idle (it's responsible for
-  // probing this state via ShouldQuitWhenIdle()). This state is stored here
-  // rather than pushed to Delegate to support nested RunLoops.
-  bool quit_when_idle_received_ = false;
-
-  // RunLoop is not thread-safe. Its state/methods, unless marked as such, may
-  // not be accessed from any other sequence than the thread it was constructed
-  // on. Exception: RunLoop can be safely accessed from one other sequence (or
-  // single parallel task) during Run() -- e.g. to Quit() without having to
-  // plumb ThreatTaskRunnerHandle::Get() throughout a test to repost QuitClosure
-  // to origin thread.
-  SEQUENCE_CHECKER(sequence_checker_);
-
-  const scoped_refptr<SingleThreadTaskRunner> origin_task_runner_;
-
-  // WeakPtrFactory for QuitClosure safety.
-  base::WeakPtrFactory<RunLoop> weak_factory_;
-
-  DISALLOW_COPY_AND_ASSIGN(RunLoop);
-};
-
-}  // namespace base
-
-#endif  // BASE_RUN_LOOP_H_
diff --git a/base/sequence_checker.h b/base/sequence_checker.h
deleted file mode 100644
index 48b593b..0000000
--- a/base/sequence_checker.h
+++ /dev/null
@@ -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.
-
-#ifndef BASE_SEQUENCE_CHECKER_H_
-#define BASE_SEQUENCE_CHECKER_H_
-
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/sequence_checker_impl.h"
-
-// SequenceChecker is a helper class used to help verify that some methods of a
-// class are called sequentially (for thread-safety).
-//
-// Use the macros below instead of the SequenceChecker directly so that the
-// unused member doesn't result in an extra byte (four when padded) per
-// instance in production.
-//
-// This class is much prefered to ThreadChecker for thread-safety checks.
-// ThreadChecker should only be used for classes that are truly thread-affine
-// (use thread-local-storage or a third-party API that does).
-//
-// Usage:
-//   class MyClass {
-//    public:
-//     MyClass() {
-//       // It's sometimes useful to detach on construction for objects that are
-//       // constructed in one place and forever after used from another
-//       // sequence.
-//       DETACH_FROM_SEQUENCE(my_sequence_checker_);
-//     }
-//
-//     ~MyClass() {
-//       // SequenceChecker doesn't automatically check it's destroyed on origin
-//       // sequence for the same reason it's sometimes detached in the
-//       // constructor. It's okay to destroy off sequence if the owner
-//       // otherwise knows usage on the associated sequence is done. If you're
-//       // not detaching in the constructor, you probably want to explicitly
-//       // check in the destructor.
-//       DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_);
-//     }
-//     void MyMethod() {
-//       DCHECK_CALLED_ON_VALID_SEQUENCE(my_sequence_checker_);
-//       ... (do stuff) ...
-//     }
-//
-//    private:
-//     SEQUENCE_CHECKER(my_sequence_checker_);
-//   }
-
-#if DCHECK_IS_ON()
-#define SEQUENCE_CHECKER(name) base::SequenceChecker name
-#define DCHECK_CALLED_ON_VALID_SEQUENCE(name) \
-  DCHECK((name).CalledOnValidSequence())
-#define DETACH_FROM_SEQUENCE(name) (name).DetachFromSequence()
-#else  // DCHECK_IS_ON()
-#define SEQUENCE_CHECKER(name)
-#define DCHECK_CALLED_ON_VALID_SEQUENCE(name) EAT_STREAM_PARAMETERS
-#define DETACH_FROM_SEQUENCE(name)
-#endif  // DCHECK_IS_ON()
-
-namespace base {
-
-// Do nothing implementation, for use in release mode.
-//
-// Note: You should almost always use the SequenceChecker class (through the
-// above macros) to get the right version for your build configuration.
-class SequenceCheckerDoNothing {
- public:
-  SequenceCheckerDoNothing() = default;
-  bool CalledOnValidSequence() const WARN_UNUSED_RESULT { return true; }
-  void DetachFromSequence() {}
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(SequenceCheckerDoNothing);
-};
-
-#if DCHECK_IS_ON()
-class SequenceChecker : public SequenceCheckerImpl {
-};
-#else
-class SequenceChecker : public SequenceCheckerDoNothing {
-};
-#endif  // DCHECK_IS_ON()
-
-}  // namespace base
-
-#endif  // BASE_SEQUENCE_CHECKER_H_
diff --git a/base/sequence_checker_impl.cc b/base/sequence_checker_impl.cc
deleted file mode 100644
index daa774b..0000000
--- a/base/sequence_checker_impl.cc
+++ /dev/null
@@ -1,51 +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 "base/sequence_checker_impl.h"
-
-#include "base/logging.h"
-#include "base/memory/ptr_util.h"
-#include "base/sequence_token.h"
-#include "base/threading/thread_checker_impl.h"
-
-namespace base {
-
-class SequenceCheckerImpl::Core {
- public:
-  Core() : sequence_token_(SequenceToken::GetForCurrentThread()) {}
-
-  ~Core() = default;
-
-  bool CalledOnValidSequence() const {
-    if (sequence_token_.IsValid())
-      return sequence_token_ == SequenceToken::GetForCurrentThread();
-
-    // SequenceChecker behaves as a ThreadChecker when it is not bound to a
-    // valid sequence token.
-    return thread_checker_.CalledOnValidThread();
-  }
-
- private:
-  SequenceToken sequence_token_;
-
-  // Used when |sequence_token_| is invalid.
-  ThreadCheckerImpl thread_checker_;
-};
-
-SequenceCheckerImpl::SequenceCheckerImpl() : core_(std::make_unique<Core>()) {}
-SequenceCheckerImpl::~SequenceCheckerImpl() = default;
-
-bool SequenceCheckerImpl::CalledOnValidSequence() const {
-  AutoLock auto_lock(lock_);
-  if (!core_)
-    core_ = std::make_unique<Core>();
-  return core_->CalledOnValidSequence();
-}
-
-void SequenceCheckerImpl::DetachFromSequence() {
-  AutoLock auto_lock(lock_);
-  core_.reset();
-}
-
-}  // namespace base
diff --git a/base/sequence_checker_impl.h b/base/sequence_checker_impl.h
deleted file mode 100644
index a54c388..0000000
--- a/base/sequence_checker_impl.h
+++ /dev/null
@@ -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.
-
-#ifndef BASE_SEQUENCE_CHECKER_IMPL_H_
-#define BASE_SEQUENCE_CHECKER_IMPL_H_
-
-#include <memory>
-
-#include "base/base_export.h"
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/synchronization/lock.h"
-
-namespace base {
-
-// Real implementation of SequenceChecker for use in debug mode or for temporary
-// use in release mode (e.g. to CHECK on a threading issue seen only in the
-// wild).
-//
-// Note: You should almost always use the SequenceChecker class to get the right
-// version for your build configuration.
-class BASE_EXPORT SequenceCheckerImpl {
- public:
-  SequenceCheckerImpl();
-  ~SequenceCheckerImpl();
-
-  // Returns true if called in sequence with previous calls to this method and
-  // the constructor.
-  bool CalledOnValidSequence() const WARN_UNUSED_RESULT;
-
-  // Unbinds the checker from the currently associated sequence. The checker
-  // will be re-bound on the next call to CalledOnValidSequence().
-  void DetachFromSequence();
-
- private:
-  class Core;
-
-  // Guards all variables below.
-  mutable Lock lock_;
-  mutable std::unique_ptr<Core> core_;
-
-  DISALLOW_COPY_AND_ASSIGN(SequenceCheckerImpl);
-};
-
-}  // namespace base
-
-#endif  // BASE_SEQUENCE_CHECKER_IMPL_H_
diff --git a/base/sequence_token.cc b/base/sequence_token.cc
deleted file mode 100644
index 0bf2b44..0000000
--- a/base/sequence_token.cc
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2016 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/sequence_token.h"
-
-#include "base/atomic_sequence_num.h"
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/threading/thread_local.h"
-
-namespace base {
-
-namespace {
-
-base::AtomicSequenceNumber g_sequence_token_generator;
-
-base::AtomicSequenceNumber g_task_token_generator;
-
-LazyInstance<ThreadLocalPointer<const SequenceToken>>::Leaky
-    tls_current_sequence_token = LAZY_INSTANCE_INITIALIZER;
-
-LazyInstance<ThreadLocalPointer<const TaskToken>>::Leaky
-    tls_current_task_token = LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace
-
-bool SequenceToken::operator==(const SequenceToken& other) const {
-  return token_ == other.token_ && IsValid();
-}
-
-bool SequenceToken::operator!=(const SequenceToken& other) const {
-  return !(*this == other);
-}
-
-bool SequenceToken::IsValid() const {
-  return token_ != kInvalidSequenceToken;
-}
-
-int SequenceToken::ToInternalValue() const {
-  return token_;
-}
-
-SequenceToken SequenceToken::Create() {
-  return SequenceToken(g_sequence_token_generator.GetNext());
-}
-
-SequenceToken SequenceToken::GetForCurrentThread() {
-  const SequenceToken* current_sequence_token =
-      tls_current_sequence_token.Get().Get();
-  return current_sequence_token ? *current_sequence_token : SequenceToken();
-}
-
-bool TaskToken::operator==(const TaskToken& other) const {
-  return token_ == other.token_ && IsValid();
-}
-
-bool TaskToken::operator!=(const TaskToken& other) const {
-  return !(*this == other);
-}
-
-bool TaskToken::IsValid() const {
-  return token_ != kInvalidTaskToken;
-}
-
-TaskToken TaskToken::Create() {
-  return TaskToken(g_task_token_generator.GetNext());
-}
-
-TaskToken TaskToken::GetForCurrentThread() {
-  const TaskToken* current_task_token = tls_current_task_token.Get().Get();
-  return current_task_token ? *current_task_token : TaskToken();
-}
-
-ScopedSetSequenceTokenForCurrentThread::ScopedSetSequenceTokenForCurrentThread(
-    const SequenceToken& sequence_token)
-    : sequence_token_(sequence_token), task_token_(TaskToken::Create()) {
-  DCHECK(!tls_current_sequence_token.Get().Get());
-  DCHECK(!tls_current_task_token.Get().Get());
-  tls_current_sequence_token.Get().Set(&sequence_token_);
-  tls_current_task_token.Get().Set(&task_token_);
-}
-
-ScopedSetSequenceTokenForCurrentThread::
-    ~ScopedSetSequenceTokenForCurrentThread() {
-  DCHECK_EQ(tls_current_sequence_token.Get().Get(), &sequence_token_);
-  DCHECK_EQ(tls_current_task_token.Get().Get(), &task_token_);
-  tls_current_sequence_token.Get().Set(nullptr);
-  tls_current_task_token.Get().Set(nullptr);
-}
-
-}  // namespace base
diff --git a/base/sequence_token.h b/base/sequence_token.h
deleted file mode 100644
index 6e7d191..0000000
--- a/base/sequence_token.h
+++ /dev/null
@@ -1,115 +0,0 @@
-// Copyright 2016 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_SEQUENCE_TOKEN_H_
-#define BASE_SEQUENCE_TOKEN_H_
-
-#include "base/base_export.h"
-#include "base/macros.h"
-
-namespace base {
-
-// A token that identifies a series of sequenced tasks (i.e. tasks that run one
-// at a time in posting order).
-class BASE_EXPORT SequenceToken {
- public:
-  // Instantiates an invalid SequenceToken.
-  SequenceToken() = default;
-
-  // Explicitly allow copy.
-  SequenceToken(const SequenceToken& other) = default;
-  SequenceToken& operator=(const SequenceToken& other) = default;
-
-  // An invalid SequenceToken is not equal to any other SequenceToken, including
-  // other invalid SequenceTokens.
-  bool operator==(const SequenceToken& other) const;
-  bool operator!=(const SequenceToken& other) const;
-
-  // Returns true if this is a valid SequenceToken.
-  bool IsValid() const;
-
-  // Returns the integer uniquely representing this SequenceToken. This method
-  // should only be used for tracing and debugging.
-  int ToInternalValue() const;
-
-  // Returns a valid SequenceToken which isn't equal to any previously returned
-  // SequenceToken.
-  static SequenceToken Create();
-
-  // Returns the SequenceToken associated with the task running on the current
-  // thread, as determined by the active ScopedSetSequenceTokenForCurrentThread
-  // if any.
-  static SequenceToken GetForCurrentThread();
-
- private:
-  explicit SequenceToken(int token) : token_(token) {}
-
-  static constexpr int kInvalidSequenceToken = -1;
-  int token_ = kInvalidSequenceToken;
-};
-
-// A token that identifies a task.
-//
-// This is used by ThreadCheckerImpl to determine whether calls to
-// CalledOnValidThread() come from the same task and hence are deterministically
-// single-threaded (vs. calls coming from different sequenced or parallel tasks,
-// which may or may not run on the same thread).
-class BASE_EXPORT TaskToken {
- public:
-  // Instantiates an invalid TaskToken.
-  TaskToken() = default;
-
-  // Explicitly allow copy.
-  TaskToken(const TaskToken& other) = default;
-  TaskToken& operator=(const TaskToken& other) = default;
-
-  // An invalid TaskToken is not equal to any other TaskToken, including
-  // other invalid TaskTokens.
-  bool operator==(const TaskToken& other) const;
-  bool operator!=(const TaskToken& other) const;
-
-  // Returns true if this is a valid TaskToken.
-  bool IsValid() const;
-
-  // In the scope of a ScopedSetSequenceTokenForCurrentThread, returns a valid
-  // TaskToken which isn't equal to any TaskToken returned in the scope of a
-  // different ScopedSetSequenceTokenForCurrentThread. Otherwise, returns an
-  // invalid TaskToken.
-  static TaskToken GetForCurrentThread();
-
- private:
-  friend class ScopedSetSequenceTokenForCurrentThread;
-
-  explicit TaskToken(int token) : token_(token) {}
-
-  // Returns a valid TaskToken which isn't equal to any previously returned
-  // TaskToken. This is private as it only meant to be instantiated by
-  // ScopedSetSequenceTokenForCurrentThread.
-  static TaskToken Create();
-
-  static constexpr int kInvalidTaskToken = -1;
-  int token_ = kInvalidTaskToken;
-};
-
-// Instantiate this in the scope where a single task runs.
-class BASE_EXPORT ScopedSetSequenceTokenForCurrentThread {
- public:
-  // Throughout the lifetime of the constructed object,
-  // SequenceToken::GetForCurrentThread() will return |sequence_token| and
-  // TaskToken::GetForCurrentThread() will return a TaskToken which is not equal
-  // to any TaskToken returned in the scope of another
-  // ScopedSetSequenceTokenForCurrentThread.
-  ScopedSetSequenceTokenForCurrentThread(const SequenceToken& sequence_token);
-  ~ScopedSetSequenceTokenForCurrentThread();
-
- private:
-  const SequenceToken sequence_token_;
-  const TaskToken task_token_;
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedSetSequenceTokenForCurrentThread);
-};
-
-}  // namespace base
-
-#endif  // BASE_SEQUENCE_TOKEN_H_
diff --git a/base/sequenced_task_runner.cc b/base/sequenced_task_runner.cc
deleted file mode 100644
index 86771c6..0000000
--- a/base/sequenced_task_runner.cc
+++ /dev/null
@@ -1,38 +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 "base/sequenced_task_runner.h"
-
-#include <utility>
-
-#include "base/bind.h"
-
-namespace base {
-
-bool SequencedTaskRunner::PostNonNestableTask(const Location& from_here,
-                                              OnceClosure task) {
-  return PostNonNestableDelayedTask(from_here, std::move(task),
-                                    base::TimeDelta());
-}
-
-bool SequencedTaskRunner::DeleteOrReleaseSoonInternal(
-    const Location& from_here,
-    void (*deleter)(const void*),
-    const void* object) {
-  return PostNonNestableTask(from_here, BindOnce(deleter, object));
-}
-
-OnTaskRunnerDeleter::OnTaskRunnerDeleter(
-    scoped_refptr<SequencedTaskRunner> task_runner)
-    : task_runner_(std::move(task_runner)) {
-}
-
-OnTaskRunnerDeleter::~OnTaskRunnerDeleter() = default;
-
-OnTaskRunnerDeleter::OnTaskRunnerDeleter(OnTaskRunnerDeleter&&) = default;
-
-OnTaskRunnerDeleter& OnTaskRunnerDeleter::operator=(
-    OnTaskRunnerDeleter&&) = default;
-
-}  // namespace base
diff --git a/base/sequenced_task_runner.h b/base/sequenced_task_runner.h
deleted file mode 100644
index 53d21ad..0000000
--- a/base/sequenced_task_runner.h
+++ /dev/null
@@ -1,176 +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_SEQUENCED_TASK_RUNNER_H_
-#define BASE_SEQUENCED_TASK_RUNNER_H_
-
-#include <memory>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/sequenced_task_runner_helpers.h"
-#include "base/task_runner.h"
-
-namespace base {
-
-// A SequencedTaskRunner is a subclass of TaskRunner that provides
-// additional guarantees on the order that tasks are started, as well
-// as guarantees on when tasks are in sequence, i.e. one task finishes
-// before the other one starts.
-//
-// Summary
-// -------
-// Non-nested tasks with the same delay will run one by one in FIFO
-// order.
-//
-// Detailed guarantees
-// -------------------
-//
-// SequencedTaskRunner also adds additional methods for posting
-// non-nestable tasks.  In general, an implementation of TaskRunner
-// may expose task-running methods which are themselves callable from
-// within tasks.  A non-nestable task is one that is guaranteed to not
-// be run from within an already-running task.  Conversely, a nestable
-// task (the default) is a task that can be run from within an
-// already-running task.
-//
-// The guarantees of SequencedTaskRunner are as follows:
-//
-//   - Given two tasks T2 and T1, T2 will start after T1 starts if:
-//
-//       * T2 is posted after T1; and
-//       * T2 has equal or higher delay than T1; and
-//       * T2 is non-nestable or T1 is nestable.
-//
-//   - If T2 will start after T1 starts by the above guarantee, then
-//     T2 will start after T1 finishes and is destroyed if:
-//
-//       * T2 is non-nestable, or
-//       * T1 doesn't call any task-running methods.
-//
-//   - If T2 will start after T1 finishes by the above guarantee, then
-//     all memory changes in T1 and T1's destruction will be visible
-//     to T2.
-//
-//   - If T2 runs nested within T1 via a call to the task-running
-//     method M, then all memory changes in T1 up to the call to M
-//     will be visible to T2, and all memory changes in T2 will be
-//     visible to T1 from the return from M.
-//
-// Note that SequencedTaskRunner does not guarantee that tasks are run
-// on a single dedicated thread, although the above guarantees provide
-// most (but not all) of the same guarantees.  If you do need to
-// guarantee that tasks are run on a single dedicated thread, see
-// SingleThreadTaskRunner (in single_thread_task_runner.h).
-//
-// Some corollaries to the above guarantees, assuming the tasks in
-// question don't call any task-running methods:
-//
-//   - Tasks posted via PostTask are run in FIFO order.
-//
-//   - Tasks posted via PostNonNestableTask are run in FIFO order.
-//
-//   - Tasks posted with the same delay and the same nestable state
-//     are run in FIFO order.
-//
-//   - A list of tasks with the same nestable state posted in order of
-//     non-decreasing delay is run in FIFO order.
-//
-//   - A list of tasks posted in order of non-decreasing delay with at
-//     most a single change in nestable state from nestable to
-//     non-nestable is run in FIFO order. (This is equivalent to the
-//     statement of the first guarantee above.)
-//
-// Some theoretical implementations of SequencedTaskRunner:
-//
-//   - A SequencedTaskRunner that wraps a regular TaskRunner but makes
-//     sure that only one task at a time is posted to the TaskRunner,
-//     with appropriate memory barriers in between tasks.
-//
-//   - A SequencedTaskRunner that, for each task, spawns a joinable
-//     thread to run that task and immediately quit, and then
-//     immediately joins that thread.
-//
-//   - A SequencedTaskRunner that stores the list of posted tasks and
-//     has a method Run() that runs each runnable task in FIFO order
-//     that can be called from any thread, but only if another
-//     (non-nested) Run() call isn't already happening.
-class BASE_EXPORT SequencedTaskRunner : public TaskRunner {
- public:
-  // The two PostNonNestable*Task methods below are like their
-  // nestable equivalents in TaskRunner, but they guarantee that the
-  // posted task will not run nested within an already-running task.
-  //
-  // A simple corollary is that posting a task as non-nestable can
-  // only delay when the task gets run.  That is, posting a task as
-  // non-nestable may not affect when the task gets run, or it could
-  // make it run later than it normally would, but it won't make it
-  // run earlier than it normally would.
-
-  // TODO(akalin): Get rid of the boolean return value for the methods
-  // below.
-
-  bool PostNonNestableTask(const Location& from_here, OnceClosure task);
-
-  virtual bool PostNonNestableDelayedTask(const Location& from_here,
-                                          OnceClosure task,
-                                          base::TimeDelta delay) = 0;
-
-  // Submits a non-nestable task to delete the given object.  Returns
-  // true if the object may be deleted at some point in the future,
-  // and false if the object definitely will not be deleted.
-  template <class T>
-  bool DeleteSoon(const Location& from_here, const T* object) {
-    return DeleteOrReleaseSoonInternal(from_here, &DeleteHelper<T>::DoDelete,
-                                       object);
-  }
-
-  template <class T>
-  bool DeleteSoon(const Location& from_here, std::unique_ptr<T> object) {
-    return DeleteSoon(from_here, object.release());
-  }
-
-  // Submits a non-nestable task to release the given object.  Returns
-  // true if the object may be released at some point in the future,
-  // and false if the object definitely will not be released.
-  template <class T>
-  bool ReleaseSoon(const Location& from_here, const T* object) {
-    return DeleteOrReleaseSoonInternal(from_here, &ReleaseHelper<T>::DoRelease,
-                                       object);
-  }
-
- protected:
-  ~SequencedTaskRunner() override = default;
-
- private:
-  bool DeleteOrReleaseSoonInternal(const Location& from_here,
-                                   void (*deleter)(const void*),
-                                   const void* object);
-};
-
-// Sample usage with std::unique_ptr :
-// std::unique_ptr<Foo, base::OnTaskRunnerDeleter> ptr(
-//     new Foo, base::OnTaskRunnerDeleter(my_task_runner));
-//
-// For RefCounted see base::RefCountedDeleteOnSequence.
-struct BASE_EXPORT OnTaskRunnerDeleter {
-  explicit OnTaskRunnerDeleter(scoped_refptr<SequencedTaskRunner> task_runner);
-  ~OnTaskRunnerDeleter();
-
-  OnTaskRunnerDeleter(OnTaskRunnerDeleter&&);
-  OnTaskRunnerDeleter& operator=(OnTaskRunnerDeleter&&);
-
-  // For compatibility with std:: deleters.
-  template <typename T>
-  void operator()(const T* ptr) {
-    if (ptr)
-      task_runner_->DeleteSoon(FROM_HERE, ptr);
-  }
-
-  scoped_refptr<SequencedTaskRunner> task_runner_;
-};
-
-}  // namespace base
-
-#endif  // BASE_SEQUENCED_TASK_RUNNER_H_
diff --git a/base/sequenced_task_runner_helpers.h b/base/sequenced_task_runner_helpers.h
deleted file mode 100644
index 18ec0e2..0000000
--- a/base/sequenced_task_runner_helpers.h
+++ /dev/null
@@ -1,42 +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_SEQUENCED_TASK_RUNNER_HELPERS_H_
-#define BASE_SEQUENCED_TASK_RUNNER_HELPERS_H_
-
-namespace base {
-
-class SequencedTaskRunner;
-
-// Template helpers which use function indirection to erase T from the
-// function signature while still remembering it so we can call the
-// correct destructor/release function.
-//
-// We use this trick so we don't need to include bind.h in a header
-// file like sequenced_task_runner.h. We also wrap the helpers in a
-// templated class to make it easier for users of DeleteSoon to
-// declare the helper as a friend.
-template <class T>
-class DeleteHelper {
- private:
-  static void DoDelete(const void* object) {
-    delete static_cast<const T*>(object);
-  }
-
-  friend class SequencedTaskRunner;
-};
-
-template <class T>
-class ReleaseHelper {
- private:
-  static void DoRelease(const void* object) {
-    static_cast<const T*>(object)->Release();
-  }
-
-  friend class SequencedTaskRunner;
-};
-
-}  // namespace base
-
-#endif  // BASE_SEQUENCED_TASK_RUNNER_HELPERS_H_
diff --git a/base/single_thread_task_runner.h b/base/single_thread_task_runner.h
deleted file mode 100644
index 4d6938e..0000000
--- a/base/single_thread_task_runner.h
+++ /dev/null
@@ -1,36 +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_SINGLE_THREAD_TASK_RUNNER_H_
-#define BASE_SINGLE_THREAD_TASK_RUNNER_H_
-
-#include "base/base_export.h"
-#include "base/sequenced_task_runner.h"
-
-namespace base {
-
-// A SingleThreadTaskRunner is a SequencedTaskRunner with one more
-// guarantee; namely, that all tasks are run on a single dedicated
-// thread.  Most use cases require only a SequencedTaskRunner, unless
-// there is a specific need to run tasks on only a single thread.
-//
-// SingleThreadTaskRunner implementations might:
-//   - Post tasks to an existing thread's MessageLoop (see
-//     MessageLoop::task_runner()).
-//   - Create their own worker thread and MessageLoop to post tasks to.
-//   - Add tasks to a FIFO and signal to a non-MessageLoop thread for them to
-//     be processed. This allows TaskRunner-oriented code run on threads
-//     running other kinds of message loop, e.g. Jingle threads.
-class BASE_EXPORT SingleThreadTaskRunner : public SequencedTaskRunner {
- public:
-  // A more explicit alias to RunsTasksInCurrentSequence().
-  bool BelongsToCurrentThread() const { return RunsTasksInCurrentSequence(); }
-
- protected:
-  ~SingleThreadTaskRunner() override = default;
-};
-
-}  // namespace base
-
-#endif  // BASE_SINGLE_THREAD_TASK_RUNNER_H_
diff --git a/base/strings/string_number_conversions.cc b/base/strings/string_number_conversions.cc
index 86fa2e3..c2a606f 100644
--- a/base/strings/string_number_conversions.cc
+++ b/base/strings/string_number_conversions.cc
@@ -16,7 +16,6 @@
 #include "base/numerics/safe_math.h"
 #include "base/scoped_clear_errno.h"
 #include "base/strings/utf_string_conversions.h"
-#include "base/third_party/dmg_fp/dmg_fp.h"
 
 namespace base {
 
@@ -360,23 +359,6 @@
   return IntToStringT<string16, unsigned long long>::IntToString(value);
 }
 
-std::string NumberToString(double value) {
-  // According to g_fmt.cc, it is sufficient to declare a buffer of size 32.
-  char buffer[32];
-  dmg_fp::g_fmt(buffer, value);
-  return std::string(buffer);
-}
-
-base::string16 NumberToString16(double value) {
-  // According to g_fmt.cc, it is sufficient to declare a buffer of size 32.
-  char buffer[32];
-  dmg_fp::g_fmt(buffer, value);
-
-  // The number will be ASCII. This creates the string using the "input
-  // iterator" variant which promotes from 8-bit to 16-bit via "=".
-  return base::string16(&buffer[0], &buffer[strlen(buffer)]);
-}
-
 bool StringToInt(StringPiece input, int* output) {
   return StringToIntImpl(input, output);
 }
@@ -417,28 +399,6 @@
   return String16ToIntImpl(input, output);
 }
 
-bool StringToDouble(const std::string& input, double* output) {
-  // Thread-safe?  It is on at least Mac, Linux, and Windows.
-  ScopedClearErrno clear_errno;
-
-  char* endptr = nullptr;
-  *output = dmg_fp::strtod(input.c_str(), &endptr);
-
-  // Cases to return false:
-  //  - If errno is ERANGE, there was an overflow or underflow.
-  //  - If the input string is empty, there was nothing to parse.
-  //  - If endptr does not point to the end of the string, there are either
-  //    characters remaining in the string after a parsed number, or the string
-  //    does not begin with a parseable number.  endptr is compared to the
-  //    expected end given the string's stated length to correctly catch cases
-  //    where the string contains embedded NUL characters.
-  //  - If the first character is a space, there was leading whitespace
-  return errno == 0 &&
-         !input.empty() &&
-         input.c_str() + input.length() == endptr &&
-         !isspace(input[0]);
-}
-
 // Note: if you need to add String16ToDouble, first ask yourself if it's
 // really necessary. If it is, probably the best implementation here is to
 // convert to 8-bit and then use the 8-bit version.
diff --git a/base/strings/string_number_conversions.h b/base/strings/string_number_conversions.h
index b59ce46..4eb870e 100644
--- a/base/strings/string_number_conversions.h
+++ b/base/strings/string_number_conversions.h
@@ -29,7 +29,7 @@
 //
 // DO NOT use these functions in any UI unless it's NOT localized on purpose.
 // Instead, use base::MessageFormatter for a complex message with numbers
-// (integer, float, double) embedded or base::Format{Number,Double,Percent} to
+// (integer, float) embedded or base::Format{Number,Percent} to
 // just format a single number/percent. Note that some languages use native
 // digits instead of ASCII digits while others use a group separator or decimal
 // point different from ',' and '.'. Using these functions in the UI would lead
@@ -53,8 +53,6 @@
 BASE_EXPORT string16 NumberToString16(long long value);
 BASE_EXPORT std::string NumberToString(unsigned long long value);
 BASE_EXPORT string16 NumberToString16(unsigned long long value);
-BASE_EXPORT std::string NumberToString(double value);
-BASE_EXPORT string16 NumberToString16(double value);
 
 // Type-specific naming for backwards compatibility.
 //
@@ -112,16 +110,6 @@
 BASE_EXPORT bool StringToSizeT(StringPiece input, size_t* output);
 BASE_EXPORT bool StringToSizeT(StringPiece16 input, size_t* output);
 
-// For floating-point conversions, only conversions of input strings in decimal
-// form are defined to work.  Behavior with strings representing floating-point
-// numbers in hexadecimal, and strings representing non-finite values (such as
-// NaN and inf) is undefined.  Otherwise, these behave the same as the integral
-// variants.  This expects the input string to NOT be specific to the locale.
-// If your input is locale specific, use ICU to read the number.
-// WARNING: Will write to |output| even when returning false.
-//          Read the comments here and above StringToInt() carefully.
-BASE_EXPORT bool StringToDouble(const std::string& input, double* output);
-
 // Hex encoding ----------------------------------------------------------------
 
 // Returns a hex string representation of a binary buffer. The returned hex
diff --git a/base/strings/string_util.cc b/base/strings/string_util.cc
index 6293f6d..82ce02c 100644
--- a/base/strings/string_util.cc
+++ b/base/strings/string_util.cc
@@ -22,7 +22,6 @@
 
 #include "base/logging.h"
 #include "base/macros.h"
-#include "base/memory/singleton.h"
 #include "base/strings/utf_string_conversion_utils.h"
 #include "base/strings/utf_string_conversions.h"
 #include "base/third_party/icu/icu_utf.h"
@@ -32,19 +31,6 @@
 
 namespace {
 
-// Force the singleton used by EmptyString[16] to be a unique type. This
-// prevents other code that might accidentally use Singleton<string> from
-// getting our internal one.
-struct EmptyStrings {
-  EmptyStrings() = default;
-  const std::string s;
-  const string16 s16;
-
-  static EmptyStrings* GetInstance() {
-    return Singleton<EmptyStrings>::get();
-  }
-};
-
 // Used by ReplaceStringPlaceholders to track the position in the string of
 // replaced parameters.
 struct ReplacementOffset {
@@ -237,14 +223,6 @@
   return CompareCaseInsensitiveASCIIT<string16>(a, b) == 0;
 }
 
-const std::string& EmptyString() {
-  return EmptyStrings::GetInstance()->s;
-}
-
-const string16& EmptyString16() {
-  return EmptyStrings::GetInstance()->s16;
-}
-
 template <class StringType>
 bool ReplaceCharsT(const StringType& input,
                    BasicStringPiece<StringType> find_any_of_these,
diff --git a/base/strings/string_util.h b/base/strings/string_util.h
index f1045bb..eaef690 100644
--- a/base/strings/string_util.h
+++ b/base/strings/string_util.h
@@ -143,22 +143,6 @@
 BASE_EXPORT bool EqualsCaseInsensitiveASCII(StringPiece a, StringPiece b);
 BASE_EXPORT bool EqualsCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b);
 
-// These threadsafe functions return references to globally unique empty
-// strings.
-//
-// It is likely faster to construct a new empty string object (just a few
-// instructions to set the length to 0) than to get the empty string singleton
-// returned by these functions (which requires threadsafe singleton access).
-//
-// Therefore, DO NOT USE THESE AS A GENERAL-PURPOSE SUBSTITUTE FOR DEFAULT
-// CONSTRUCTORS. There is only one case where you should use these: functions
-// which need to return a string by reference (e.g. as a class member
-// accessor), and don't have an empty string to use (e.g. in an error case).
-// These should not be used as initializers, function arguments, or return
-// values for functions which return by value or outparam.
-BASE_EXPORT const std::string& EmptyString();
-BASE_EXPORT const string16& EmptyString16();
-
 // Contains the set of characters representing whitespace in the corresponding
 // encoding. Null-terminated. The ASCII versions are the whitespaces as defined
 // by HTML5, and don't include control characters.
diff --git a/base/synchronization/atomic_flag.cc b/base/synchronization/atomic_flag.cc
index 8c2018d..6cc0e87 100644
--- a/base/synchronization/atomic_flag.cc
+++ b/base/synchronization/atomic_flag.cc
@@ -9,15 +9,9 @@
 namespace base {
 
 AtomicFlag::AtomicFlag() {
-  // It doesn't matter where the AtomicFlag is built so long as it's always
-  // Set() from the same sequence after. Note: the sequencing requirements are
-  // necessary for IsSet()'s callers to know which sequence's memory operations
-  // they are synchronized with.
-  set_sequence_checker_.DetachFromSequence();
 }
 
 void AtomicFlag::Set() {
-  DCHECK(set_sequence_checker_.CalledOnValidSequence());
   base::subtle::Release_Store(&flag_, 1);
 }
 
diff --git a/base/synchronization/atomic_flag.h b/base/synchronization/atomic_flag.h
index ff175e1..d033054 100644
--- a/base/synchronization/atomic_flag.h
+++ b/base/synchronization/atomic_flag.h
@@ -8,7 +8,6 @@
 #include "base/atomicops.h"
 #include "base/base_export.h"
 #include "base/macros.h"
-#include "base/sequence_checker.h"
 
 namespace base {
 
@@ -34,7 +33,6 @@
 
  private:
   base::subtle::Atomic32 flag_ = 0;
-  SequenceChecker set_sequence_checker_;
 
   DISALLOW_COPY_AND_ASSIGN(AtomicFlag);
 };
diff --git a/base/synchronization/condition_variable.h b/base/synchronization/condition_variable.h
index 9ec9cd8..6b5e56a 100644
--- a/base/synchronization/condition_variable.h
+++ b/base/synchronization/condition_variable.h
@@ -112,10 +112,6 @@
   pthread_mutex_t* user_mutex_;
 #endif
 
-#if DCHECK_IS_ON()
-  base::Lock* const user_lock_;  // Needed to adjust shadow lock state on wait.
-#endif
-
   DISALLOW_COPY_AND_ASSIGN(ConditionVariable);
 };
 
diff --git a/base/synchronization/condition_variable_posix.cc b/base/synchronization/condition_variable_posix.cc
index b234341..7d6824d 100644
--- a/base/synchronization/condition_variable_posix.cc
+++ b/base/synchronization/condition_variable_posix.cc
@@ -9,8 +9,6 @@
 #include <sys/time.h>
 
 #include "base/synchronization/lock.h"
-#include "base/threading/scoped_blocking_call.h"
-#include "base/threading/thread_restrictions.h"
 #include "base/time/time.h"
 #include "build_config.h"
 
@@ -18,9 +16,6 @@
 
 ConditionVariable::ConditionVariable(Lock* user_lock)
     : user_mutex_(user_lock->lock_.native_handle())
-#if DCHECK_IS_ON()
-    , user_lock_(user_lock)
-#endif
 {
   int rv = 0;
   // http://crbug.com/293736
@@ -63,31 +58,17 @@
 }
 
 void ConditionVariable::Wait() {
-  internal::AssertBaseSyncPrimitivesAllowed();
-  ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
-#if DCHECK_IS_ON()
-  user_lock_->CheckHeldAndUnmark();
-#endif
   int rv = pthread_cond_wait(&condition_, user_mutex_);
   DCHECK_EQ(0, rv);
-#if DCHECK_IS_ON()
-  user_lock_->CheckUnheldAndMark();
-#endif
 }
 
 void ConditionVariable::TimedWait(const TimeDelta& max_time) {
-  internal::AssertBaseSyncPrimitivesAllowed();
-  ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
   int64_t usecs = max_time.InMicroseconds();
   struct timespec relative_time;
   relative_time.tv_sec = usecs / Time::kMicrosecondsPerSecond;
   relative_time.tv_nsec =
       (usecs % Time::kMicrosecondsPerSecond) * Time::kNanosecondsPerMicrosecond;
 
-#if DCHECK_IS_ON()
-  user_lock_->CheckHeldAndUnmark();
-#endif
-
 #if defined(OS_MACOSX)
   int rv = pthread_cond_timedwait_relative_np(
       &condition_, user_mutex_, &relative_time);
@@ -124,9 +105,6 @@
   // On failure, we only expect the CV to timeout. Any other error value means
   // that we've unexpectedly woken up.
   DCHECK(rv == 0 || rv == ETIMEDOUT);
-#if DCHECK_IS_ON()
-  user_lock_->CheckUnheldAndMark();
-#endif
 }
 
 void ConditionVariable::Broadcast() {
diff --git a/base/synchronization/condition_variable_win.cc b/base/synchronization/condition_variable_win.cc
index ddaef07..d247e22 100644
--- a/base/synchronization/condition_variable_win.cc
+++ b/base/synchronization/condition_variable_win.cc
@@ -5,8 +5,6 @@
 #include "base/synchronization/condition_variable.h"
 
 #include "base/synchronization/lock.h"
-#include "base/threading/scoped_blocking_call.h"
-#include "base/threading/thread_restrictions.h"
 #include "base/time/time.h"
 
 #include <windows.h>
@@ -15,9 +13,6 @@
 
 ConditionVariable::ConditionVariable(Lock* user_lock)
     : srwlock_(user_lock->lock_.native_handle())
-#if DCHECK_IS_ON()
-    , user_lock_(user_lock)
-#endif
 {
   DCHECK(user_lock);
   InitializeConditionVariable(reinterpret_cast<PCONDITION_VARIABLE>(&cv_));
@@ -30,14 +25,8 @@
 }
 
 void ConditionVariable::TimedWait(const TimeDelta& max_time) {
-  internal::AssertBaseSyncPrimitivesAllowed();
-  ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
   DWORD timeout = static_cast<DWORD>(max_time.InMilliseconds());
 
-#if DCHECK_IS_ON()
-  user_lock_->CheckHeldAndUnmark();
-#endif
-
   if (!SleepConditionVariableSRW(reinterpret_cast<PCONDITION_VARIABLE>(&cv_),
                                  reinterpret_cast<PSRWLOCK>(srwlock_), timeout,
                                  0)) {
@@ -48,10 +37,6 @@
     // used with GetLastError().
     DCHECK_EQ(static_cast<DWORD>(ERROR_TIMEOUT), GetLastError());
   }
-
-#if DCHECK_IS_ON()
-  user_lock_->CheckUnheldAndMark();
-#endif
 }
 
 void ConditionVariable::Broadcast() {
diff --git a/base/synchronization/lock.cc b/base/synchronization/lock.cc
deleted file mode 100644
index 03297ad..0000000
--- a/base/synchronization/lock.cc
+++ /dev/null
@@ -1,38 +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.
-
-// This file is used for debugging assertion support.  The Lock class
-// is functionally a wrapper around the LockImpl class, so the only
-// real intelligence in the class is in the debugging logic.
-
-#include "base/synchronization/lock.h"
-
-#if DCHECK_IS_ON()
-
-namespace base {
-
-Lock::Lock() : lock_() {
-}
-
-Lock::~Lock() {
-  DCHECK(owning_thread_ref_.is_null());
-}
-
-void Lock::AssertAcquired() const {
-  DCHECK(owning_thread_ref_ == PlatformThread::CurrentRef());
-}
-
-void Lock::CheckHeldAndUnmark() {
-  DCHECK(owning_thread_ref_ == PlatformThread::CurrentRef());
-  owning_thread_ref_ = PlatformThreadRef();
-}
-
-void Lock::CheckUnheldAndMark() {
-  DCHECK(owning_thread_ref_.is_null());
-  owning_thread_ref_ = PlatformThread::CurrentRef();
-}
-
-}  // namespace base
-
-#endif  // DCHECK_IS_ON()
diff --git a/base/synchronization/lock.h b/base/synchronization/lock.h
index ecfa854..f913a81 100644
--- a/base/synchronization/lock.h
+++ b/base/synchronization/lock.h
@@ -9,7 +9,6 @@
 #include "base/logging.h"
 #include "base/macros.h"
 #include "base/synchronization/lock_impl.h"
-#include "base/threading/platform_thread.h"
 #include "build_config.h"
 
 namespace base {
@@ -19,7 +18,6 @@
 // AssertAcquired() method.
 class BASE_EXPORT Lock {
  public:
-#if !DCHECK_IS_ON()
    // Optimized wrapper implementation
   Lock() : lock_() {}
   ~Lock() {}
@@ -34,32 +32,6 @@
 
   // Null implementation if not debug.
   void AssertAcquired() const {}
-#else
-  Lock();
-  ~Lock();
-
-  // NOTE: We do not permit recursive locks and will commonly fire a DCHECK() if
-  // a thread attempts to acquire the lock a second time (while already holding
-  // it).
-  void Acquire() {
-    lock_.Lock();
-    CheckUnheldAndMark();
-  }
-  void Release() {
-    CheckHeldAndUnmark();
-    lock_.Unlock();
-  }
-
-  bool Try() {
-    bool rv = lock_.Try();
-    if (rv) {
-      CheckUnheldAndMark();
-    }
-    return rv;
-  }
-
-  void AssertAcquired() const;
-#endif  // DCHECK_IS_ON()
 
   // Whether Lock mitigates priority inversion when used from different thread
   // priorities.
@@ -84,20 +56,6 @@
   friend class ConditionVariable;
 
  private:
-#if DCHECK_IS_ON()
-  // Members and routines taking care of locks assertions.
-  // Note that this checks for recursive locks and allows them
-  // if the variable is set.  This is allowed by the underlying implementation
-  // on windows but not on Posix, so we're doing unneeded checks on Posix.
-  // It's worth it to share the code.
-  void CheckHeldAndUnmark();
-  void CheckUnheldAndMark();
-
-  // All private data is implicitly protected by lock_.
-  // Be VERY careful to only access members under that lock.
-  base::PlatformThreadRef owning_thread_ref_;
-#endif  // DCHECK_IS_ON()
-
   // Platform specific underlying lock implementation.
   internal::LockImpl lock_;
 
diff --git a/base/synchronization/waitable_event_mac.cc b/base/synchronization/waitable_event_mac.cc
index 7979553..67eca5b 100644
--- a/base/synchronization/waitable_event_mac.cc
+++ b/base/synchronization/waitable_event_mac.cc
@@ -15,8 +15,7 @@
 #include "base/mac/mach_logging.h"
 #include "base/mac/scoped_dispatch_object.h"
 #include "base/posix/eintr_wrapper.h"
-#include "base/threading/scoped_blocking_call.h"
-#include "base/threading/thread_restrictions.h"
+#include "base/time/time.h"
 #include "build_config.h"
 
 namespace base {
@@ -111,9 +110,6 @@
 }
 
 bool WaitableEvent::TimedWaitUntil(const TimeTicks& end_time) {
-  internal::AssertBaseSyncPrimitivesAllowed();
-  ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
-
   TimeDelta wait_time = end_time - TimeTicks::Now();
   if (wait_time < TimeDelta()) {
     // A negative delta would be treated by the system as indefinite, but
@@ -164,9 +160,7 @@
 
 // static
 size_t WaitableEvent::WaitMany(WaitableEvent** raw_waitables, size_t count) {
-  internal::AssertBaseSyncPrimitivesAllowed();
   DCHECK(count) << "Cannot wait on no events";
-  ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
 
   // On macOS 10.11+, using Mach port sets may cause system instability, per
   // https://crbug.com/756102. On macOS 10.12+, a kqueue can be used
diff --git a/base/synchronization/waitable_event_posix.cc b/base/synchronization/waitable_event_posix.cc
index 34d54c7..3e32686 100644
--- a/base/synchronization/waitable_event_posix.cc
+++ b/base/synchronization/waitable_event_posix.cc
@@ -12,8 +12,7 @@
 #include "base/synchronization/condition_variable.h"
 #include "base/synchronization/lock.h"
 #include "base/synchronization/waitable_event.h"
-#include "base/threading/scoped_blocking_call.h"
-#include "base/threading/thread_restrictions.h"
+#include "base/time/time.h"
 
 // -----------------------------------------------------------------------------
 // A WaitableEvent on POSIX is implemented as a wait-list. Currently we don't
@@ -161,9 +160,6 @@
 }
 
 bool WaitableEvent::TimedWaitUntil(const TimeTicks& end_time) {
-  internal::AssertBaseSyncPrimitivesAllowed();
-  ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
-
   const bool finite_time = !end_time.is_max();
 
   kernel_->lock_.Acquire();
@@ -234,9 +230,7 @@
 // static
 size_t WaitableEvent::WaitMany(WaitableEvent** raw_waitables,
                                size_t count) {
-  internal::AssertBaseSyncPrimitivesAllowed();
   DCHECK(count) << "Cannot wait on no events";
-  ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
 
   // We need to acquire the locks in a globally consistent order. Thus we sort
   // the array of waitables by address. We actually sort a pairs so that we can
diff --git a/base/synchronization/waitable_event_watcher.h b/base/synchronization/waitable_event_watcher.h
deleted file mode 100644
index 5d0cf71..0000000
--- a/base/synchronization/waitable_event_watcher.h
+++ /dev/null
@@ -1,160 +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_SYNCHRONIZATION_WAITABLE_EVENT_WATCHER_H_
-#define BASE_SYNCHRONIZATION_WAITABLE_EVENT_WATCHER_H_
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/sequenced_task_runner.h"
-#include "build_config.h"
-
-#if defined(OS_WIN)
-#include "base/win/object_watcher.h"
-#include "base/win/scoped_handle.h"
-#elif defined(OS_MACOSX)
-#include <dispatch/dispatch.h>
-
-#include "base/mac/scoped_dispatch_object.h"
-#include "base/memory/weak_ptr.h"
-#include "base/synchronization/waitable_event.h"
-#else
-#include "base/sequence_checker.h"
-#include "base/synchronization/waitable_event.h"
-#endif
-
-#if !defined(OS_WIN)
-#include "base/callback.h"
-#endif
-
-namespace base {
-
-class Flag;
-class AsyncWaiter;
-class WaitableEvent;
-
-// This class provides a way to wait on a WaitableEvent asynchronously.
-//
-// Each instance of this object can be waiting on a single WaitableEvent. When
-// the waitable event is signaled, a callback is invoked on the sequence that
-// called StartWatching(). This callback can be deleted by deleting the waiter.
-//
-// Typical usage:
-//
-//   class MyClass {
-//    public:
-//     void DoStuffWhenSignaled(WaitableEvent *waitable_event) {
-//       watcher_.StartWatching(waitable_event,
-//           base::BindOnce(&MyClass::OnWaitableEventSignaled, this);
-//     }
-//    private:
-//     void OnWaitableEventSignaled(WaitableEvent* waitable_event) {
-//       // OK, time to do stuff!
-//     }
-//     base::WaitableEventWatcher watcher_;
-//   };
-//
-// In the above example, MyClass wants to "do stuff" when waitable_event
-// becomes signaled. WaitableEventWatcher makes this task easy. When MyClass
-// goes out of scope, the watcher_ will be destroyed, and there is no need to
-// worry about OnWaitableEventSignaled being called on a deleted MyClass
-// pointer.
-//
-// BEWARE: With automatically reset WaitableEvents, a signal may be lost if it
-// occurs just before a WaitableEventWatcher is deleted. There is currently no
-// safe way to stop watching an automatic reset WaitableEvent without possibly
-// missing a signal.
-//
-// NOTE: you /are/ allowed to delete the WaitableEvent while still waiting on
-// it with a Watcher. But pay attention: if the event was signaled and deleted
-// right after, the callback may be called with deleted WaitableEvent pointer.
-
-class BASE_EXPORT WaitableEventWatcher
-#if defined(OS_WIN)
-    : public win::ObjectWatcher::Delegate
-#endif
-{
- public:
-  using EventCallback = OnceCallback<void(WaitableEvent*)>;
-
-  WaitableEventWatcher();
-
-#if defined(OS_WIN)
-  ~WaitableEventWatcher() override;
-#else
-  ~WaitableEventWatcher();
-#endif
-
-  // When |event| is signaled, |callback| is called on the sequence that called
-  // StartWatching().
-  // |task_runner| is used for asynchronous executions of calling |callback|.
-  bool StartWatching(WaitableEvent* event,
-                     EventCallback callback,
-                     scoped_refptr<SequencedTaskRunner> task_runner);
-
-  // Cancel the current watch. Must be called from the same sequence which
-  // started the watch.
-  //
-  // Does nothing if no event is being watched, nor if the watch has completed.
-  // The callback will *not* be called for the current watch after this
-  // function returns. Since the callback runs on the same sequence as this
-  // function, it cannot be called during this function either.
-  void StopWatching();
-
- private:
-#if defined(OS_WIN)
-  void OnObjectSignaled(HANDLE h) override;
-
-  // Duplicated handle of the event passed to StartWatching().
-  win::ScopedHandle duplicated_event_handle_;
-
-  // A watcher for |duplicated_event_handle_|. The handle MUST outlive
-  // |watcher_|.
-  win::ObjectWatcher watcher_;
-
-  EventCallback callback_;
-  WaitableEvent* event_ = nullptr;
-#elif defined(OS_MACOSX)
-  // Invokes the callback and resets the source. Must be called on the task
-  // runner on which StartWatching() was called.
-  void InvokeCallback();
-
-  // Closure bound to the event being watched. This will be is_null() if
-  // nothing is being watched.
-  OnceClosure callback_;
-
-  // A reference to the receive right that is kept alive while a watcher
-  // is waiting. Null if no event is being watched.
-  scoped_refptr<WaitableEvent::ReceiveRight> receive_right_;
-
-  // A TYPE_MACH_RECV dispatch source on |receive_right_|. When a receive event
-  // is delivered, the message queue will be peeked and the bound |callback_|
-  // may be run. This will be null if nothing is currently being watched.
-  ScopedDispatchObject<dispatch_source_t> source_;
-
-  // Used to vend a weak pointer for calling InvokeCallback() from the
-  // |source_| event handler.
-  WeakPtrFactory<WaitableEventWatcher> weak_ptr_factory_;
-#else
-  // Instantiated in StartWatching(). Set before the callback runs. Reset in
-  // StopWatching() or StartWatching().
-  scoped_refptr<Flag> cancel_flag_;
-
-  // Enqueued in the wait list of the watched WaitableEvent.
-  AsyncWaiter* waiter_ = nullptr;
-
-  // Kernel of the watched WaitableEvent.
-  scoped_refptr<WaitableEvent::WaitableEventKernel> kernel_;
-
-  // Ensures that StartWatching() and StopWatching() are called on the same
-  // sequence.
-  SequenceChecker sequence_checker_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(WaitableEventWatcher);
-};
-
-}  // namespace base
-
-#endif  // BASE_SYNCHRONIZATION_WAITABLE_EVENT_WATCHER_H_
diff --git a/base/synchronization/waitable_event_watcher_mac.cc b/base/synchronization/waitable_event_watcher_mac.cc
deleted file mode 100644
index 772fd10..0000000
--- a/base/synchronization/waitable_event_watcher_mac.cc
+++ /dev/null
@@ -1,113 +0,0 @@
-// Copyright 2017 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/synchronization/waitable_event_watcher.h"
-
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-
-namespace base {
-
-WaitableEventWatcher::WaitableEventWatcher() : weak_ptr_factory_(this) {}
-
-WaitableEventWatcher::~WaitableEventWatcher() {
-  StopWatching();
-}
-
-bool WaitableEventWatcher::StartWatching(
-    WaitableEvent* event,
-    EventCallback callback,
-    scoped_refptr<SequencedTaskRunner> task_runner) {
-  DCHECK(task_runner->RunsTasksInCurrentSequence());
-  DCHECK(!source_ || dispatch_source_testcancel(source_));
-
-  // Keep a reference to the receive right, so that if the event is deleted
-  // out from under the watcher, a signal can still be observed.
-  receive_right_ = event->receive_right_;
-
-  callback_ = BindOnce(std::move(callback), event);
-
-  // Locals for capture by the block. Accessing anything through the |this| or
-  // |event| pointers is not safe, since either may have been deleted by the
-  // time the handler block is invoked.
-  WeakPtr<WaitableEventWatcher> weak_this = weak_ptr_factory_.GetWeakPtr();
-  const bool auto_reset =
-      event->policy_ == WaitableEvent::ResetPolicy::AUTOMATIC;
-
-  // Auto-reset events always use a dispatch source. Manual-reset events
-  // only do so if dispatch provides reliable delivery, otherwise a manual
-  // watcher list is used.
-  if (!WaitableEvent::UseSlowWatchList(event->policy_)) {
-    // Use the global concurrent queue here, since it is only used to thunk
-    // to the real callback on the target task runner.
-    source_.reset(dispatch_source_create(
-        DISPATCH_SOURCE_TYPE_MACH_RECV, receive_right_->Name(), 0,
-        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)));
-
-    // Additional locals for block capture.
-    dispatch_source_t source = source_.get();
-    mach_port_t name = receive_right_->Name();
-
-    dispatch_source_set_event_handler(source_, ^{
-      // For automatic-reset events, only fire the callback if this watcher
-      // can claim/dequeue the event. For manual-reset events, all watchers can
-      // be called back.
-      if (auto_reset && !WaitableEvent::PeekPort(name, true)) {
-        return;
-      }
-
-      // The event has been consumed. A watcher is one-shot, so cancel the
-      // source to prevent receiving future event signals.
-      dispatch_source_cancel(source);
-
-      task_runner->PostTask(
-          FROM_HERE,
-          BindOnce(&WaitableEventWatcher::InvokeCallback, weak_this));
-    });
-    dispatch_resume(source_);
-  } else {
-    // The |event->watch_list_| closures can be run from any thread, so bind
-    // the callback as an invocation of PostTask.
-    OnceClosure watcher =
-        BindOnce(IgnoreResult(&TaskRunner::PostTask), task_runner, FROM_HERE,
-                 BindOnce(&WaitableEventWatcher::InvokeCallback, weak_this));
-
-    // Hold an additional reference to the ReceiveRight, in case |watcher|
-    // runs and deletes the event while the lock is held.
-    // Hold the lock for the duration of IsSignaled() so that if Signal()
-    // is called by another thread, it waits for this to be added to the
-    // watch list.
-    scoped_refptr<WaitableEvent::ReceiveRight> receive_right(receive_right_);
-    AutoLock lock(receive_right->SlowWatchList()->lock);
-    if (event->IsSignaled()) {
-      std::move(watcher).Run();
-      return true;
-    }
-    receive_right_->SlowWatchList()->list.push_back(std::move(watcher));
-  }
-
-  return true;
-}
-
-void WaitableEventWatcher::StopWatching() {
-  callback_.Reset();
-  receive_right_ = nullptr;
-  if (source_) {
-    dispatch_source_cancel(source_);
-    source_.reset();
-  }
-}
-
-void WaitableEventWatcher::InvokeCallback() {
-  // The callback can be null if StopWatching() is called between signaling
-  // and the |callback_| getting run on the target task runner.
-  if (callback_.is_null())
-    return;
-  source_.reset();
-  receive_right_ = nullptr;
-  std::move(callback_).Run();
-}
-
-}  // namespace base
diff --git a/base/synchronization/waitable_event_watcher_posix.cc b/base/synchronization/waitable_event_watcher_posix.cc
deleted file mode 100644
index 2b296da..0000000
--- a/base/synchronization/waitable_event_watcher_posix.cc
+++ /dev/null
@@ -1,234 +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 "base/synchronization/waitable_event_watcher.h"
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/logging.h"
-#include "base/synchronization/lock.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-
-namespace base {
-
-// -----------------------------------------------------------------------------
-// WaitableEventWatcher (async waits).
-//
-// The basic design is that we add an AsyncWaiter to the wait-list of the event.
-// That AsyncWaiter has a pointer to SequencedTaskRunner, and a Task to be
-// posted to it. The task ends up calling the callback when it runs on the
-// sequence.
-//
-// Since the wait can be canceled, we have a thread-safe Flag object which is
-// set when the wait has been canceled. At each stage in the above, we check the
-// flag before going onto the next stage. Since the wait may only be canceled in
-// the sequence which runs the Task, we are assured that the callback cannot be
-// called after canceling...
-
-// -----------------------------------------------------------------------------
-// A thread-safe, reference-counted, write-once flag.
-// -----------------------------------------------------------------------------
-class Flag : public RefCountedThreadSafe<Flag> {
- public:
-  Flag() { flag_ = false; }
-
-  void Set() {
-    AutoLock locked(lock_);
-    flag_ = true;
-  }
-
-  bool value() const {
-    AutoLock locked(lock_);
-    return flag_;
-  }
-
- private:
-  friend class RefCountedThreadSafe<Flag>;
-  ~Flag() = default;
-
-  mutable Lock lock_;
-  bool flag_;
-
-  DISALLOW_COPY_AND_ASSIGN(Flag);
-};
-
-// -----------------------------------------------------------------------------
-// This is an asynchronous waiter which posts a task to a SequencedTaskRunner
-// when fired. An AsyncWaiter may only be in a single wait-list.
-// -----------------------------------------------------------------------------
-class AsyncWaiter : public WaitableEvent::Waiter {
- public:
-  AsyncWaiter(scoped_refptr<SequencedTaskRunner> task_runner,
-              base::OnceClosure callback,
-              Flag* flag)
-      : task_runner_(std::move(task_runner)),
-        callback_(std::move(callback)),
-        flag_(flag) {}
-
-  bool Fire(WaitableEvent* event) override {
-    // Post the callback if we haven't been cancelled.
-    if (!flag_->value())
-      task_runner_->PostTask(FROM_HERE, std::move(callback_));
-
-    // We are removed from the wait-list by the WaitableEvent itself. It only
-    // remains to delete ourselves.
-    delete this;
-
-    // We can always return true because an AsyncWaiter is never in two
-    // different wait-lists at the same time.
-    return true;
-  }
-
-  // See StopWatching for discussion
-  bool Compare(void* tag) override { return tag == flag_.get(); }
-
- private:
-  const scoped_refptr<SequencedTaskRunner> task_runner_;
-  base::OnceClosure callback_;
-  const scoped_refptr<Flag> flag_;
-};
-
-// -----------------------------------------------------------------------------
-// For async waits we need to run a callback on a sequence. We do this by
-// posting an AsyncCallbackHelper task, which calls the callback and keeps track
-// of when the event is canceled.
-// -----------------------------------------------------------------------------
-void AsyncCallbackHelper(Flag* flag,
-                         WaitableEventWatcher::EventCallback callback,
-                         WaitableEvent* event) {
-  // Runs on the sequence that called StartWatching().
-  if (!flag->value()) {
-    // This is to let the WaitableEventWatcher know that the event has occured.
-    flag->Set();
-    std::move(callback).Run(event);
-  }
-}
-
-WaitableEventWatcher::WaitableEventWatcher() {
-  sequence_checker_.DetachFromSequence();
-}
-
-WaitableEventWatcher::~WaitableEventWatcher() {
-  // The destructor may be called from a different sequence than StartWatching()
-  // when there is no active watch. To avoid triggering a DCHECK in
-  // StopWatching(), do not call it when there is no active watch.
-  if (cancel_flag_ && !cancel_flag_->value())
-    StopWatching();
-}
-
-// -----------------------------------------------------------------------------
-// The Handle is how the user cancels a wait. After deleting the Handle we
-// insure that the delegate cannot be called.
-// -----------------------------------------------------------------------------
-bool WaitableEventWatcher::StartWatching(
-    WaitableEvent* event,
-    EventCallback callback,
-    scoped_refptr<SequencedTaskRunner> task_runner) {
-  DCHECK(sequence_checker_.CalledOnValidSequence());
-
-  // A user may call StartWatching from within the callback function. In this
-  // case, we won't know that we have finished watching, expect that the Flag
-  // will have been set in AsyncCallbackHelper().
-  if (cancel_flag_.get() && cancel_flag_->value())
-    cancel_flag_ = nullptr;
-
-  DCHECK(!cancel_flag_) << "StartWatching called while still watching";
-
-  cancel_flag_ = new Flag;
-  OnceClosure internal_callback =
-      base::BindOnce(&AsyncCallbackHelper, base::RetainedRef(cancel_flag_),
-                     std::move(callback), event);
-  WaitableEvent::WaitableEventKernel* kernel = event->kernel_.get();
-
-  AutoLock locked(kernel->lock_);
-
-  if (kernel->signaled_) {
-    if (!kernel->manual_reset_)
-      kernel->signaled_ = false;
-
-    // No hairpinning - we can't call the delegate directly here. We have to
-    // post a task to |task_runner| as usual.
-    task_runner->PostTask(FROM_HERE, std::move(internal_callback));
-    return true;
-  }
-
-  kernel_ = kernel;
-  waiter_ = new AsyncWaiter(std::move(task_runner),
-                            std::move(internal_callback), cancel_flag_.get());
-  event->Enqueue(waiter_);
-
-  return true;
-}
-
-void WaitableEventWatcher::StopWatching() {
-  DCHECK(sequence_checker_.CalledOnValidSequence());
-
-  if (!cancel_flag_.get())  // if not currently watching...
-    return;
-
-  if (cancel_flag_->value()) {
-    // In this case, the event has fired, but we haven't figured that out yet.
-    // The WaitableEvent may have been deleted too.
-    cancel_flag_ = nullptr;
-    return;
-  }
-
-  if (!kernel_.get()) {
-    // We have no kernel. This means that we never enqueued a Waiter on an
-    // event because the event was already signaled when StartWatching was
-    // called.
-    //
-    // In this case, a task was enqueued on the MessageLoop and will run.
-    // We set the flag in case the task hasn't yet run. The flag will stop the
-    // delegate getting called. If the task has run then we have the last
-    // reference to the flag and it will be deleted immedately after.
-    cancel_flag_->Set();
-    cancel_flag_ = nullptr;
-    return;
-  }
-
-  AutoLock locked(kernel_->lock_);
-  // We have a lock on the kernel. No one else can signal the event while we
-  // have it.
-
-  // We have a possible ABA issue here. If Dequeue was to compare only the
-  // pointer values then it's possible that the AsyncWaiter could have been
-  // fired, freed and the memory reused for a different Waiter which was
-  // enqueued in the same wait-list. We would think that that waiter was our
-  // AsyncWaiter and remove it.
-  //
-  // To stop this, Dequeue also takes a tag argument which is passed to the
-  // virtual Compare function before the two are considered a match. So we need
-  // a tag which is good for the lifetime of this handle: the Flag. Since we
-  // have a reference to the Flag, its memory cannot be reused while this object
-  // still exists. So if we find a waiter with the correct pointer value, and
-  // which shares a Flag pointer, we have a real match.
-  if (kernel_->Dequeue(waiter_, cancel_flag_.get())) {
-    // Case 2: the waiter hasn't been signaled yet; it was still on the wait
-    // list. We've removed it, thus we can delete it and the task (which cannot
-    // have been enqueued with the MessageLoop because the waiter was never
-    // signaled)
-    delete waiter_;
-    cancel_flag_ = nullptr;
-    return;
-  }
-
-  // Case 3: the waiter isn't on the wait-list, thus it was signaled. It may not
-  // have run yet, so we set the flag to tell it not to bother enqueuing the
-  // task on the SequencedTaskRunner, but to delete it instead. The Waiter
-  // deletes itself once run.
-  cancel_flag_->Set();
-  cancel_flag_ = nullptr;
-
-  // If the waiter has already run then the task has been enqueued. If the Task
-  // hasn't yet run, the flag will stop the delegate from getting called. (This
-  // is thread safe because one may only delete a Handle from the sequence that
-  // called StartWatching()).
-  //
-  // If the delegate has already been called then we have nothing to do. The
-  // task has been deleted by the MessageLoop.
-}
-
-}  // namespace base
diff --git a/base/synchronization/waitable_event_watcher_win.cc b/base/synchronization/waitable_event_watcher_win.cc
deleted file mode 100644
index 6003fd4..0000000
--- a/base/synchronization/waitable_event_watcher_win.cc
+++ /dev/null
@@ -1,61 +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 "base/synchronization/waitable_event_watcher.h"
-
-#include "base/compiler_specific.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/win/object_watcher.h"
-
-#include <windows.h>
-
-namespace base {
-
-WaitableEventWatcher::WaitableEventWatcher() = default;
-
-WaitableEventWatcher::~WaitableEventWatcher() {}
-
-bool WaitableEventWatcher::StartWatching(
-    WaitableEvent* event,
-    EventCallback callback,
-    scoped_refptr<SequencedTaskRunner> task_runner) {
-  DCHECK(event);
-  callback_ = std::move(callback);
-  event_ = event;
-
-  // Duplicate and hold the event handle until a callback is returned or
-  // waiting is stopped.
-  HANDLE handle = nullptr;
-  if (!::DuplicateHandle(::GetCurrentProcess(),  // hSourceProcessHandle
-                         event->handle(),
-                         ::GetCurrentProcess(),  // hTargetProcessHandle
-                         &handle,
-                         0,      // dwDesiredAccess ignored due to SAME_ACCESS
-                         FALSE,  // !bInheritHandle
-                         DUPLICATE_SAME_ACCESS)) {
-    return false;
-  }
-  duplicated_event_handle_.Set(handle);
-  return watcher_.StartWatchingOnce(handle, this);
-}
-
-void WaitableEventWatcher::StopWatching() {
-  callback_.Reset();
-  event_ = NULL;
-  watcher_.StopWatching();
-  duplicated_event_handle_.Close();
-}
-
-void WaitableEventWatcher::OnObjectSignaled(HANDLE h) {
-  DCHECK_EQ(duplicated_event_handle_.Get(), h);
-  WaitableEvent* event = event_;
-  EventCallback callback = std::move(callback_);
-  event_ = NULL;
-  duplicated_event_handle_.Close();
-  DCHECK(event);
-
-  std::move(callback).Run(event);
-}
-
-}  // namespace base
diff --git a/base/synchronization/waitable_event_win.cc b/base/synchronization/waitable_event_win.cc
index 1ee6c5f..15dd10a 100644
--- a/base/synchronization/waitable_event_win.cc
+++ b/base/synchronization/waitable_event_win.cc
@@ -12,8 +12,6 @@
 
 #include "base/logging.h"
 #include "base/numerics/safe_conversions.h"
-#include "base/threading/scoped_blocking_call.h"
-#include "base/threading/thread_restrictions.h"
 #include "base/time/time.h"
 
 namespace base {
@@ -52,9 +50,6 @@
 }
 
 void WaitableEvent::Wait() {
-  internal::AssertBaseSyncPrimitivesAllowed();
-  ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
-
   DWORD result = WaitForSingleObject(handle_.Get(), INFINITE);
   // It is most unexpected that this should ever fail.  Help consumers learn
   // about it if it should ever fail.
@@ -66,8 +61,6 @@
 
 // Helper function called from TimedWait and TimedWaitUntil.
 bool WaitUntil(HANDLE handle, const TimeTicks& now, const TimeTicks& end_time) {
-  ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
-
   TimeDelta delta = end_time - now;
   DCHECK_GT(delta, TimeDelta());
 
@@ -104,8 +97,6 @@
   if (wait_delta.is_zero())
     return IsSignaled();
 
-  internal::AssertBaseSyncPrimitivesAllowed();
-
   TimeTicks now(TimeTicks::Now());
   // TimeTicks takes care of overflow including the cases when wait_delta
   // is a maximum value.
@@ -116,8 +107,6 @@
   if (end_time.is_null())
     return IsSignaled();
 
-  internal::AssertBaseSyncPrimitivesAllowed();
-
   TimeTicks now(TimeTicks::Now());
   if (end_time <= now)
     return IsSignaled();
@@ -129,9 +118,6 @@
 size_t WaitableEvent::WaitMany(WaitableEvent** events, size_t count) {
   DCHECK(count) << "Cannot wait on no events";
 
-  internal::AssertBaseSyncPrimitivesAllowed();
-  ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
-
   HANDLE handles[MAXIMUM_WAIT_OBJECTS];
   CHECK_LE(count, static_cast<size_t>(MAXIMUM_WAIT_OBJECTS))
       << "Can only wait on " << MAXIMUM_WAIT_OBJECTS << " with WaitMany";
diff --git a/base/sys_info.cc b/base/sys_info.cc
deleted file mode 100644
index 4250ca9..0000000
--- a/base/sys_info.cc
+++ /dev/null
@@ -1,94 +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 "base/sys_info.h"
-
-#include <algorithm>
-
-#include "base/base_switches.h"
-#include "base/command_line.h"
-#include "base/lazy_instance.h"
-#include "base/sys_info_internal.h"
-#include "base/time/time.h"
-#include "build_config.h"
-
-namespace base {
-namespace {
-static const int kLowMemoryDeviceThresholdMB = 512;
-}
-
-// static
-int64_t SysInfo::AmountOfPhysicalMemory() {
-  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
-          switches::kEnableLowEndDeviceMode)) {
-    return kLowMemoryDeviceThresholdMB * 1024 * 1024;
-  }
-
-  return AmountOfPhysicalMemoryImpl();
-}
-
-// static
-int64_t SysInfo::AmountOfAvailablePhysicalMemory() {
-  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
-          switches::kEnableLowEndDeviceMode)) {
-    // Estimate the available memory by subtracting our memory used estimate
-    // from the fake |kLowMemoryDeviceThresholdMB| limit.
-    size_t memory_used =
-        AmountOfPhysicalMemoryImpl() - AmountOfAvailablePhysicalMemoryImpl();
-    size_t memory_limit = kLowMemoryDeviceThresholdMB * 1024 * 1024;
-    // std::min ensures no underflow, as |memory_used| can be > |memory_limit|.
-    return memory_limit - std::min(memory_used, memory_limit);
-  }
-
-  return AmountOfAvailablePhysicalMemoryImpl();
-}
-
-bool SysInfo::IsLowEndDevice() {
-  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
-          switches::kEnableLowEndDeviceMode)) {
-    return true;
-  }
-
-  return IsLowEndDeviceImpl();
-}
-
-#if !defined(OS_ANDROID)
-
-bool DetectLowEndDevice() {
-  CommandLine* command_line = CommandLine::ForCurrentProcess();
-  if (command_line->HasSwitch(switches::kEnableLowEndDeviceMode))
-    return true;
-  if (command_line->HasSwitch(switches::kDisableLowEndDeviceMode))
-    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::IsLowEndDeviceImpl() {
-  return g_lazy_low_end_device.Get().value();
-}
-#endif
-
-#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
-std::string SysInfo::HardwareModelName() {
-  return std::string();
-}
-#endif
-
-// static
-base::TimeDelta 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 base::TimeDelta::FromMicroseconds(uptime_in_microseconds);
-}
-
-}  // namespace base
diff --git a/base/sys_info.h b/base/sys_info.h
deleted file mode 100644
index 03fb647..0000000
--- a/base/sys_info.h
+++ /dev/null
@@ -1,184 +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 <stddef.h>
-#include <stdint.h>
-
-#include <map>
-#include <string>
-
-#include "base/base_export.h"
-#include "base/files/file_path.h"
-#include "base/gtest_prod_util.h"
-#include "base/time/time.h"
-#include "build_config.h"
-
-namespace base {
-
-namespace debug {
-FORWARD_DECLARE_TEST(SystemMetricsTest, ParseMeminfo);
-}
-
-struct SystemMemoryInfoKB;
-
-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.
-  // (The amount of memory that can be allocated without any significant
-  // impact on the system. It can lead to freeing inactive file-backed
-  // and/or speculative file-backed memory).
-  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);
-
-  // Return the total disk space in bytes on the volume containing |path|, or -1
-  // on failure.
-  static int64_t AmountOfTotalDiskSpace(const FilePath& path);
-
-  // Returns system uptime.
-  static TimeDelta Uptime();
-
-  // Returns a descriptive string for the current machine model or an empty
-  // string if the machine model is unknown or an error occured.
-  // e.g. "MacPro1,1" on Mac, "iPhone9,3" on iOS or "Nexus 5" on Android. Only
-  // implemented on OS X, iOS, Android, and Chrome OS. This returns an empty
-  // string on other platforms.
-  static std::string HardwareModelName();
-
-  // 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.
-  // 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 base::mac::IsOS*
-  // family from base/mac/mac_util.h, or base::win::GetVersion from
-  // base/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 base/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_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. Otherwise, returns
-  // the full name of the board. Note that the returned value often differs
-  // between developers' systems and devices that use official builds. E.g. for
-  // a developer-built image, the function could return 'glimmer', while in an
-  // official build, it may be something like 'glimmer-signed-mp-v4keys'.
-  //
-  // NOTE: Strings returned by this function should be treated as opaque values
-  // within Chrome (e.g. for reporting metrics elsewhere). If you need to make
-  // Chrome behave differently for different Chrome OS devices, either directly
-  // check for the hardware feature that you care about (preferred) or add a
-  // command-line flag to Chrome and pass it from session_manager (based on
-  // whether a USE flag is set or not). See https://goo.gl/BbBkzg for more
-  // details.
-  static std::string GetLsbReleaseBoard();
-
-  // DEPRECATED: Please see GetLsbReleaseBoard's comment.
-  // Convenience function for GetLsbReleaseBoard() removing trailing "-signed-*"
-  // if present. Returns "unknown" if CHROMEOS_RELEASE_BOARD is not set.
-  // TODO(derat): Delete this after October 2017.
-  static std::string GetStrippedReleaseBoard();
-
-  // 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();
-
-  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 a very low amount of total
-  // system memory, typically <= 1GB.
-  // See also SysUtils.java, method isLowEndDevice.
-  static bool IsLowEndDevice();
-
- private:
-  FRIEND_TEST_ALL_PREFIXES(SysInfoTest, AmountOfAvailablePhysicalMemory);
-
-  static int64_t AmountOfPhysicalMemoryImpl();
-  static int64_t AmountOfAvailablePhysicalMemoryImpl();
-  static bool IsLowEndDeviceImpl();
-
-#if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_AIX)
-  static int64_t AmountOfAvailablePhysicalMemory(
-      const SystemMemoryInfoKB& meminfo);
-#endif
-};
-
-}  // namespace base
-
-#endif  // BASE_SYS_INFO_H_
diff --git a/base/sys_info_chromeos.cc b/base/sys_info_chromeos.cc
deleted file mode 100644
index b9ec2c9..0000000
--- a/base/sys_info_chromeos.cc
+++ /dev/null
@@ -1,228 +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 "base/sys_info.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "base/environment.h"
-#include "base/files/file.h"
-#include "base/files/file_path.h"
-#include "base/files/file_util.h"
-#include "base/lazy_instance.h"
-#include "base/macros.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_piece.h"
-#include "base/strings/string_split.h"
-#include "base/strings/string_tokenizer.h"
-#include "base/strings/string_util.h"
-#include "base/threading/thread_restrictions.h"
-
-namespace base {
-
-namespace {
-
-const char* const kLinuxStandardBaseVersionKeys[] = {
-  "CHROMEOS_RELEASE_VERSION",
-  "GOOGLE_RELEASE",
-  "DISTRIB_RELEASE",
-};
-
-const char kChromeOsReleaseNameKey[] = "CHROMEOS_RELEASE_NAME";
-
-const char* const kChromeOsReleaseNames[] = {
-  "Chrome OS",
-  "Chromium OS",
-};
-
-const char kLinuxStandardBaseReleaseFile[] = "/etc/lsb-release";
-
-const char kLsbReleaseKey[] = "LSB_RELEASE";
-const char kLsbReleaseTimeKey[] = "LSB_RELEASE_TIME";  // Seconds since epoch
-
-const char kLsbReleaseSourceKey[] = "lsb-release";
-const char kLsbReleaseSourceEnv[] = "env";
-const char kLsbReleaseSourceFile[] = "file";
-
-class ChromeOSVersionInfo {
- public:
-  ChromeOSVersionInfo() {
-    Parse();
-  }
-
-  void Parse() {
-    lsb_release_map_.clear();
-    major_version_ = 0;
-    minor_version_ = 0;
-    bugfix_version_ = 0;
-    is_running_on_chromeos_ = false;
-
-    std::string lsb_release, lsb_release_time_str;
-    std::unique_ptr<Environment> env(Environment::Create());
-    bool parsed_from_env =
-        env->GetVar(kLsbReleaseKey, &lsb_release) &&
-        env->GetVar(kLsbReleaseTimeKey, &lsb_release_time_str);
-    if (parsed_from_env) {
-      double us = 0;
-      if (StringToDouble(lsb_release_time_str, &us))
-        lsb_release_time_ = Time::FromDoubleT(us);
-    } else {
-      // If the LSB_RELEASE and LSB_RELEASE_TIME environment variables are not
-      // set, fall back to a blocking read of the lsb_release file. This should
-      // only happen in non Chrome OS environments.
-      ThreadRestrictions::ScopedAllowIO allow_io;
-      FilePath path(kLinuxStandardBaseReleaseFile);
-      ReadFileToString(path, &lsb_release);
-      File::Info fileinfo;
-      if (GetFileInfo(path, &fileinfo))
-        lsb_release_time_ = fileinfo.creation_time;
-    }
-    ParseLsbRelease(lsb_release);
-    // For debugging:
-    lsb_release_map_[kLsbReleaseSourceKey] =
-        parsed_from_env ? kLsbReleaseSourceEnv : kLsbReleaseSourceFile;
-  }
-
-  bool GetLsbReleaseValue(const std::string& key, std::string* value) {
-    SysInfo::LsbReleaseMap::const_iterator iter = lsb_release_map_.find(key);
-    if (iter == lsb_release_map_.end())
-      return false;
-    *value = iter->second;
-    return true;
-  }
-
-  void GetVersionNumbers(int32_t* major_version,
-                         int32_t* minor_version,
-                         int32_t* bugfix_version) {
-    *major_version = major_version_;
-    *minor_version = minor_version_;
-    *bugfix_version = bugfix_version_;
-  }
-
-  const Time& lsb_release_time() const { return lsb_release_time_; }
-  const SysInfo::LsbReleaseMap& lsb_release_map() const {
-    return lsb_release_map_;
-  }
-  bool is_running_on_chromeos() const { return is_running_on_chromeos_; }
-
- private:
-  void ParseLsbRelease(const std::string& lsb_release) {
-    // Parse and cache lsb_release key pairs. There should only be a handful
-    // of entries so the overhead for this will be small, and it can be
-    // useful for debugging.
-    base::StringPairs pairs;
-    SplitStringIntoKeyValuePairs(lsb_release, '=', '\n', &pairs);
-    for (size_t i = 0; i < pairs.size(); ++i) {
-      std::string key, value;
-      TrimWhitespaceASCII(pairs[i].first, TRIM_ALL, &key);
-      TrimWhitespaceASCII(pairs[i].second, TRIM_ALL, &value);
-      if (key.empty())
-        continue;
-      lsb_release_map_[key] = value;
-    }
-    // Parse the version from the first matching recognized version key.
-    std::string version;
-    for (size_t i = 0; i < arraysize(kLinuxStandardBaseVersionKeys); ++i) {
-      std::string key = kLinuxStandardBaseVersionKeys[i];
-      if (GetLsbReleaseValue(key, &version) && !version.empty())
-        break;
-    }
-    StringTokenizer tokenizer(version, ".");
-    if (tokenizer.GetNext()) {
-      StringToInt(tokenizer.token_piece(), &major_version_);
-    }
-    if (tokenizer.GetNext()) {
-      StringToInt(tokenizer.token_piece(), &minor_version_);
-    }
-    if (tokenizer.GetNext()) {
-      StringToInt(tokenizer.token_piece(), &bugfix_version_);
-    }
-
-    // Check release name for Chrome OS.
-    std::string release_name;
-    if (GetLsbReleaseValue(kChromeOsReleaseNameKey, &release_name)) {
-      for (size_t i = 0; i < arraysize(kChromeOsReleaseNames); ++i) {
-        if (release_name == kChromeOsReleaseNames[i]) {
-          is_running_on_chromeos_ = true;
-          break;
-        }
-      }
-    }
-  }
-
-  Time lsb_release_time_;
-  SysInfo::LsbReleaseMap lsb_release_map_;
-  int32_t major_version_;
-  int32_t minor_version_;
-  int32_t bugfix_version_;
-  bool is_running_on_chromeos_;
-};
-
-static LazyInstance<ChromeOSVersionInfo>::Leaky
-    g_chrome_os_version_info = LAZY_INSTANCE_INITIALIZER;
-
-ChromeOSVersionInfo& GetChromeOSVersionInfo() {
-  return g_chrome_os_version_info.Get();
-}
-
-}  // namespace
-
-// static
-void SysInfo::OperatingSystemVersionNumbers(int32_t* major_version,
-                                            int32_t* minor_version,
-                                            int32_t* bugfix_version) {
-  return GetChromeOSVersionInfo().GetVersionNumbers(
-      major_version, minor_version, bugfix_version);
-}
-
-// static
-const SysInfo::LsbReleaseMap& SysInfo::GetLsbReleaseMap() {
-  return GetChromeOSVersionInfo().lsb_release_map();
-}
-
-// static
-bool SysInfo::GetLsbReleaseValue(const std::string& key, std::string* value) {
-  return GetChromeOSVersionInfo().GetLsbReleaseValue(key, value);
-}
-
-// static
-std::string SysInfo::GetLsbReleaseBoard() {
-  const char kMachineInfoBoard[] = "CHROMEOS_RELEASE_BOARD";
-  std::string board;
-  if (!GetLsbReleaseValue(kMachineInfoBoard, &board))
-    board = "unknown";
-  return board;
-}
-
-// static
-std::string SysInfo::GetStrippedReleaseBoard() {
-  std::string board = GetLsbReleaseBoard();
-  const size_t index = board.find("-signed-");
-  if (index != std::string::npos)
-    board.resize(index);
-
-  return base::ToLowerASCII(board);
-}
-
-// static
-Time SysInfo::GetLsbReleaseTime() {
-  return GetChromeOSVersionInfo().lsb_release_time();
-}
-
-// static
-bool SysInfo::IsRunningOnChromeOS() {
-  return GetChromeOSVersionInfo().is_running_on_chromeos();
-}
-
-// static
-void SysInfo::SetChromeOSVersionInfoForTest(const std::string& lsb_release,
-                                            const Time& lsb_release_time) {
-  std::unique_ptr<Environment> env(Environment::Create());
-  env->SetVar(kLsbReleaseKey, lsb_release);
-  env->SetVar(kLsbReleaseTimeKey, NumberToString(lsb_release_time.ToDoubleT()));
-  g_chrome_os_version_info.Get().Parse();
-}
-
-}  // namespace base
diff --git a/base/sys_info_freebsd.cc b/base/sys_info_freebsd.cc
deleted file mode 100644
index 8591655..0000000
--- a/base/sys_info_freebsd.cc
+++ /dev/null
@@ -1,38 +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 "base/sys_info.h"
-
-#include <stddef.h>
-#include <stdint.h>
-#include <sys/sysctl.h>
-
-#include "base/logging.h"
-
-namespace base {
-
-int64_t SysInfo::AmountOfPhysicalMemoryImpl() {
-  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
-uint64_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 static_cast<uint64_t>(limit);
-}
-
-}  // namespace base
diff --git a/base/sys_info_internal.h b/base/sys_info_internal.h
deleted file mode 100644
index 2168e9f..0000000
--- a/base/sys_info_internal.h
+++ /dev/null
@@ -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 "base/macros.h"
-
-namespace base {
-
-namespace internal {
-
-template<typename T, T (*F)(void)>
-class LazySysInfoValue {
- public:
-  LazySysInfoValue()
-      : value_(F()) { }
-
-  ~LazySysInfoValue() = default;
-
-  T value() { return value_; }
-
- private:
-  const T value_;
-
-  DISALLOW_COPY_AND_ASSIGN(LazySysInfoValue);
-};
-
-}  // namespace internal
-
-}  // namespace base
-
-#endif  // BASE_SYS_INFO_INTERNAL_H_
diff --git a/base/sys_info_linux.cc b/base/sys_info_linux.cc
deleted file mode 100644
index f8fc1ae..0000000
--- a/base/sys_info_linux.cc
+++ /dev/null
@@ -1,94 +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 "base/sys_info.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <limits>
-
-#include "base/files/file_util.h"
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/numerics/safe_conversions.h"
-#include "base/process/process_metrics.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/sys_info_internal.h"
-#include "build_config.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);
-}
-
-base::LazyInstance<
-    base::internal::LazySysInfoValue<int64_t, AmountOfPhysicalMemory>>::Leaky
-    g_lazy_physical_memory = LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace
-
-namespace base {
-
-// static
-int64_t SysInfo::AmountOfPhysicalMemoryImpl() {
-  return g_lazy_physical_memory.Get().value();
-}
-
-// static
-int64_t SysInfo::AmountOfAvailablePhysicalMemoryImpl() {
-  SystemMemoryInfoKB info;
-  if (!GetSystemMemoryInfo(&info))
-    return 0;
-  return AmountOfAvailablePhysicalMemory(info);
-}
-
-// static
-int64_t SysInfo::AmountOfAvailablePhysicalMemory(
-    const SystemMemoryInfoKB& info) {
-  // See details here:
-  // https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
-  // The fallback logic (when there is no MemAvailable) would be more precise
-  // if we had info about zones watermarks (/proc/zoneinfo).
-  int64_t res_kb = info.available != 0
-                       ? info.available - info.active_file
-                       : info.free + info.reclaimable + info.inactive_file;
-  return res_kb * 1024;
-}
-
-// 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 base
diff --git a/base/sys_info_mac.mm b/base/sys_info_mac.mm
deleted file mode 100644
index 89bebb8..0000000
--- a/base/sys_info_mac.mm
+++ /dev/null
@@ -1,108 +0,0 @@
-// Copyright 2016 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/sys_info.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-#include <CoreServices/CoreServices.h>
-#import <Foundation/Foundation.h>
-#include <mach/mach_host.h>
-#include <mach/mach_init.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <sys/sysctl.h>
-#include <sys/types.h>
-
-#include "base/logging.h"
-#include "base/mac/mac_util.h"
-#include "base/mac/scoped_mach_port.h"
-#import "base/mac/sdk_forward_declarations.h"
-#include "base/macros.h"
-#include "base/process/process_metrics.h"
-#include "base/strings/stringprintf.h"
-
-namespace base {
-
-namespace {
-
-// Queries sysctlbyname() for the given key and returns the value from the
-// system or the empty string on failure.
-std::string GetSysctlValue(const char* key_name) {
-  char value[256];
-  size_t len = arraysize(value);
-  if (sysctlbyname(key_name, &value, &len, nullptr, 0) == 0) {
-    DCHECK_GE(len, 1u);
-    DCHECK_EQ('\0', value[len - 1]);
-    return std::string(value, len - 1);
-  }
-  return std::string();
-}
-
-}  // namespace
-
-// static
-std::string SysInfo::OperatingSystemName() {
-  return "Mac OS X";
-}
-
-// static
-std::string SysInfo::OperatingSystemVersion() {
-  int32_t major, minor, bugfix;
-  OperatingSystemVersionNumbers(&major, &minor, &bugfix);
-  return base::StringPrintf("%d.%d.%d", major, minor, bugfix);
-}
-
-// static
-void SysInfo::OperatingSystemVersionNumbers(int32_t* major_version,
-                                            int32_t* minor_version,
-                                            int32_t* bugfix_version) {
-  if (@available(macOS 10.10, *)) {
-    NSOperatingSystemVersion version =
-        [[NSProcessInfo processInfo] operatingSystemVersion];
-    *major_version = version.majorVersion;
-    *minor_version = version.minorVersion;
-    *bugfix_version = version.patchVersion;
-  } else {
-    NOTREACHED();
-  }
-}
-
-// static
-int64_t SysInfo::AmountOfPhysicalMemoryImpl() {
-  struct host_basic_info hostinfo;
-  mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
-  base::mac::ScopedMachSendRight host(mach_host_self());
-  int result = host_info(host.get(),
-                         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::AmountOfAvailablePhysicalMemoryImpl() {
-  SystemMemoryInfoKB info;
-  if (!GetSystemMemoryInfo(&info))
-    return 0;
-  // We should add inactive file-backed memory also but there is no such
-  // information from Mac OS unfortunately.
-  return static_cast<int64_t>(info.free + info.speculative) * 1024;
-}
-
-// static
-std::string SysInfo::CPUModelName() {
-  return GetSysctlValue("machdep.cpu.brand_string");
-}
-
-// static
-std::string SysInfo::HardwareModelName() {
-  return GetSysctlValue("hw.model");
-}
-
-}  // namespace base
diff --git a/base/sys_info_openbsd.cc b/base/sys_info_openbsd.cc
deleted file mode 100644
index 5a1ad56..0000000
--- a/base/sys_info_openbsd.cc
+++ /dev/null
@@ -1,80 +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 "base/sys_info.h"
-
-#include <stddef.h>
-#include <stdint.h>
-#include <sys/param.h>
-#include <sys/shm.h>
-#include <sys/sysctl.h>
-
-#include "base/logging.h"
-#include "base/macros.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 base {
-
-// 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::AmountOfPhysicalMemoryImpl() {
-  return AmountOfMemory(_SC_PHYS_PAGES);
-}
-
-// static
-int64_t SysInfo::AmountOfAvailablePhysicalMemoryImpl() {
-  // We should add inactive file-backed memory also but there is no such
-  // information from OpenBSD unfortunately.
-  return AmountOfMemory(_SC_AVPHYS_PAGES);
-}
-
-// static
-uint64_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 static_cast<uint64_t>(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 base
diff --git a/base/sys_info_posix.cc b/base/sys_info_posix.cc
deleted file mode 100644
index b3d18b9..0000000
--- a/base/sys_info_posix.cc
+++ /dev/null
@@ -1,240 +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 "base/sys_info.h"
-
-#include <errno.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-#include <sys/param.h>
-#include <sys/utsname.h>
-#include <unistd.h>
-
-#include "base/files/file_util.h"
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/sys_info_internal.h"
-#include "base/threading/thread_restrictions.h"
-#include "build_config.h"
-
-#if !defined(OS_FUCHSIA)
-#include <sys/resource.h>
-#endif
-
-#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
-
-#if defined(OS_LINUX)
-#include <linux/magic.h>
-#include <sys/vfs.h>
-#endif
-
-namespace {
-
-#if !defined(OS_OPENBSD) && !defined(OS_FUCHSIA)
-int NumberOfProcessors() {
-  // sysconf returns the number of "logical" (not "physical") processors on both
-  // Mac and Linux.  So we get the number of max available "logical" processors.
-  //
-  // Note that the number of "currently online" processors may be fewer than the
-  // returned value of NumberOfProcessors(). On some platforms, the kernel may
-  // make some processors offline intermittently, to save power when system
-  // loading is low.
-  //
-  // One common use case that needs to know the processor count is to create
-  // optimal number of threads for optimization. It should make plan according
-  // to the number of "max available" processors instead of "currently online"
-  // ones. The kernel should be smart enough to make all processors online when
-  // it has sufficient number of threads waiting to run.
-  long res = sysconf(_SC_NPROCESSORS_CONF);
-  if (res == -1) {
-    NOTREACHED();
-    return 1;
-  }
-
-  return static_cast<int>(res);
-}
-
-base::LazyInstance<
-    base::internal::LazySysInfoValue<int, NumberOfProcessors> >::Leaky
-    g_lazy_number_of_processors = LAZY_INSTANCE_INITIALIZER;
-#endif  // !defined(OS_OPENBSD) && !defined(OS_FUCHSIA)
-
-#if !defined(OS_FUCHSIA)
-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;
-}
-
-base::LazyInstance<
-    base::internal::LazySysInfoValue<int64_t, AmountOfVirtualMemory>>::Leaky
-    g_lazy_virtual_memory = LAZY_INSTANCE_INITIALIZER;
-#endif  // !defined(OS_FUCHSIA)
-
-#if defined(OS_LINUX)
-bool IsStatsZeroIfUnlimited(const base::FilePath& path) {
-  struct statfs stats;
-
-  if (HANDLE_EINTR(statfs(path.value().c_str(), &stats)) != 0)
-    return false;
-
-  switch (stats.f_type) {
-    case TMPFS_MAGIC:
-    case HUGETLBFS_MAGIC:
-    case RAMFS_MAGIC:
-      return true;
-  }
-  return false;
-}
-#endif
-
-bool GetDiskSpaceInfo(const base::FilePath& path,
-                      int64_t* available_bytes,
-                      int64_t* total_bytes) {
-  struct statvfs stats;
-  if (HANDLE_EINTR(statvfs(path.value().c_str(), &stats)) != 0)
-    return false;
-
-#if defined(OS_LINUX)
-  const bool zero_size_means_unlimited =
-      stats.f_blocks == 0 && IsStatsZeroIfUnlimited(path);
-#else
-  const bool zero_size_means_unlimited = false;
-#endif
-
-  if (available_bytes) {
-    *available_bytes =
-        zero_size_means_unlimited
-            ? std::numeric_limits<int64_t>::max()
-            : static_cast<int64_t>(stats.f_bavail) * stats.f_frsize;
-  }
-
-  if (total_bytes) {
-    *total_bytes = zero_size_means_unlimited
-                       ? std::numeric_limits<int64_t>::max()
-                       : static_cast<int64_t>(stats.f_blocks) * stats.f_frsize;
-  }
-  return true;
-}
-
-}  // namespace
-
-namespace base {
-
-#if !defined(OS_OPENBSD) && !defined(OS_FUCHSIA)
-int SysInfo::NumberOfProcessors() {
-  return g_lazy_number_of_processors.Get().value();
-}
-#endif
-
-#if !defined(OS_FUCHSIA)
-// static
-int64_t SysInfo::AmountOfVirtualMemory() {
-  return g_lazy_virtual_memory.Get().value();
-}
-#endif
-
-// static
-int64_t SysInfo::AmountOfFreeDiskSpace(const FilePath& path) {
-  AssertBlockingAllowed();
-
-  int64_t available;
-  if (!GetDiskSpaceInfo(path, &available, nullptr))
-    return -1;
-  return available;
-}
-
-// static
-int64_t SysInfo::AmountOfTotalDiskSpace(const FilePath& path) {
-  AssertBlockingAllowed();
-
-  int64_t total;
-  if (!GetDiskSpaceInfo(path, nullptr, &total))
-    return -1;
-  return total;
-}
-
-#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
-
-#if !defined(OS_MACOSX) && !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
-// static
-void SysInfo::OperatingSystemVersionNumbers(int32_t* major_version,
-                                            int32_t* minor_version,
-                                            int32_t* bugfix_version) {
-  struct utsname info;
-  if (uname(&info) < 0) {
-    NOTREACHED();
-    *major_version = 0;
-    *minor_version = 0;
-    *bugfix_version = 0;
-    return;
-  }
-  int num_read = sscanf(info.release, "%d.%d.%d", major_version, minor_version,
-                        bugfix_version);
-  if (num_read < 1)
-    *major_version = 0;
-  if (num_read < 2)
-    *minor_version = 0;
-  if (num_read < 3)
-    *bugfix_version = 0;
-}
-#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";
-  } else if (std::string(info.sysname) == "AIX") {
-    arch = "ppc64";
-  }
-  return arch;
-}
-
-// static
-size_t SysInfo::VMAllocationGranularity() {
-  return getpagesize();
-}
-
-}  // namespace base
diff --git a/base/sys_info_win.cc b/base/sys_info_win.cc
deleted file mode 100644
index 0945549..0000000
--- a/base/sys_info_win.cc
+++ /dev/null
@@ -1,163 +0,0 @@
-// Copyright 2015 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/sys_info.h"
-
-#include <windows.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include <limits>
-
-#include "base/files/file_path.h"
-#include "base/logging.h"
-#include "base/process/process_metrics.h"
-#include "base/strings/stringprintf.h"
-#include "base/threading/thread_restrictions.h"
-#include "base/win/windows_version.h"
-
-namespace {
-
-int64_t AmountOfMemory(DWORDLONG MEMORYSTATUSEX::*memory_field) {
-  MEMORYSTATUSEX memory_info;
-  memory_info.dwLength = sizeof(memory_info);
-  if (!GlobalMemoryStatusEx(&memory_info)) {
-    NOTREACHED();
-    return 0;
-  }
-
-  int64_t rv = static_cast<int64_t>(memory_info.*memory_field);
-  return rv < 0 ? std::numeric_limits<int64_t>::max() : rv;
-}
-
-bool GetDiskSpaceInfo(const base::FilePath& path,
-                      int64_t* available_bytes,
-                      int64_t* total_bytes) {
-  ULARGE_INTEGER available;
-  ULARGE_INTEGER total;
-  ULARGE_INTEGER free;
-  if (!GetDiskFreeSpaceExW(path.value().c_str(), &available, &total, &free))
-    return false;
-
-  if (available_bytes) {
-    *available_bytes = static_cast<int64_t>(available.QuadPart);
-    if (*available_bytes < 0)
-      *available_bytes = std::numeric_limits<int64_t>::max();
-  }
-  if (total_bytes) {
-    *total_bytes = static_cast<int64_t>(total.QuadPart);
-    if (*total_bytes < 0)
-      *total_bytes = std::numeric_limits<int64_t>::max();
-  }
-  return true;
-}
-
-}  // namespace
-
-namespace base {
-
-// static
-int SysInfo::NumberOfProcessors() {
-  return win::OSInfo::GetInstance()->processors();
-}
-
-// static
-int64_t SysInfo::AmountOfPhysicalMemoryImpl() {
-  return AmountOfMemory(&MEMORYSTATUSEX::ullTotalPhys);
-}
-
-// static
-int64_t SysInfo::AmountOfAvailablePhysicalMemoryImpl() {
-  SystemMemoryInfoKB info;
-  if (!GetSystemMemoryInfo(&info))
-    return 0;
-  return static_cast<int64_t>(info.avail_phys) * 1024;
-}
-
-// static
-int64_t SysInfo::AmountOfVirtualMemory() {
-  return AmountOfMemory(&MEMORYSTATUSEX::ullTotalVirtual);
-}
-
-// static
-int64_t SysInfo::AmountOfFreeDiskSpace(const FilePath& path) {
-  AssertBlockingAllowed();
-
-  int64_t available;
-  if (!GetDiskSpaceInfo(path, &available, nullptr))
-    return -1;
-  return available;
-}
-
-// static
-int64_t SysInfo::AmountOfTotalDiskSpace(const FilePath& path) {
-  AssertBlockingAllowed();
-
-  int64_t total;
-  if (!GetDiskSpaceInfo(path, nullptr, &total))
-    return -1;
-  return total;
-}
-
-std::string SysInfo::OperatingSystemName() {
-  return "Windows NT";
-}
-
-// static
-std::string SysInfo::OperatingSystemVersion() {
-  win::OSInfo* os_info = win::OSInfo::GetInstance();
-  win::OSInfo::VersionNumber version_number = os_info->version_number();
-  std::string version(StringPrintf("%d.%d.%d", version_number.major,
-                                   version_number.minor,
-                                   version_number.build));
-  win::OSInfo::ServicePack service_pack = os_info->service_pack();
-  if (service_pack.major != 0) {
-    version += StringPrintf(" SP%d", service_pack.major);
-    if (service_pack.minor != 0)
-      version += StringPrintf(".%d", service_pack.minor);
-  }
-  return version;
-}
-
-// TODO: Implement OperatingSystemVersionComplete, which would include
-// patchlevel/service pack number.
-// See chrome/browser/feedback/feedback_util.h, FeedbackUtil::SetOSVersion.
-
-// static
-std::string SysInfo::OperatingSystemArchitecture() {
-  win::OSInfo::WindowsArchitecture arch =
-      win::OSInfo::GetInstance()->architecture();
-  switch (arch) {
-    case win::OSInfo::X86_ARCHITECTURE:
-      return "x86";
-    case win::OSInfo::X64_ARCHITECTURE:
-      return "x86_64";
-    case win::OSInfo::IA64_ARCHITECTURE:
-      return "ia64";
-    default:
-      return "";
-  }
-}
-
-// static
-std::string SysInfo::CPUModelName() {
-  return win::OSInfo::GetInstance()->processor_model_name();
-}
-
-// static
-size_t SysInfo::VMAllocationGranularity() {
-  return win::OSInfo::GetInstance()->allocation_granularity();
-}
-
-// static
-void SysInfo::OperatingSystemVersionNumbers(int32_t* major_version,
-                                            int32_t* minor_version,
-                                            int32_t* bugfix_version) {
-  win::OSInfo* os_info = win::OSInfo::GetInstance();
-  *major_version = os_info->version_number().major;
-  *minor_version = os_info->version_number().minor;
-  *bugfix_version = 0;
-}
-
-}  // namespace base
diff --git a/base/task_runner.cc b/base/task_runner.cc
deleted file mode 100644
index aae9f9e..0000000
--- a/base/task_runner.cc
+++ /dev/null
@@ -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.
-
-#include "base/task_runner.h"
-
-#include <utility>
-
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/threading/post_task_and_reply_impl.h"
-
-namespace base {
-
-namespace {
-
-// TODO(akalin): There's only one other implementation of
-// PostTaskAndReplyImpl in WorkerPool.  Investigate whether it'll be
-// possible to merge the two.
-class PostTaskAndReplyTaskRunner : public internal::PostTaskAndReplyImpl {
- public:
-  explicit PostTaskAndReplyTaskRunner(TaskRunner* destination);
-
- private:
-  bool PostTask(const Location& from_here, OnceClosure task) override;
-
-  // Non-owning.
-  TaskRunner* destination_;
-};
-
-PostTaskAndReplyTaskRunner::PostTaskAndReplyTaskRunner(
-    TaskRunner* destination) : destination_(destination) {
-  DCHECK(destination_);
-}
-
-bool PostTaskAndReplyTaskRunner::PostTask(const Location& from_here,
-                                          OnceClosure task) {
-  return destination_->PostTask(from_here, std::move(task));
-}
-
-}  // namespace
-
-bool TaskRunner::PostTask(const Location& from_here, OnceClosure task) {
-  return PostDelayedTask(from_here, std::move(task), base::TimeDelta());
-}
-
-bool TaskRunner::PostTaskAndReply(const Location& from_here,
-                                  OnceClosure task,
-                                  OnceClosure reply) {
-  return PostTaskAndReplyTaskRunner(this).PostTaskAndReply(
-      from_here, std::move(task), std::move(reply));
-}
-
-TaskRunner::TaskRunner() = default;
-
-TaskRunner::~TaskRunner() = default;
-
-void TaskRunner::OnDestruct() const {
-  delete this;
-}
-
-void TaskRunnerTraits::Destruct(const TaskRunner* task_runner) {
-  task_runner->OnDestruct();
-}
-
-}  // namespace base
diff --git a/base/task_runner.h b/base/task_runner.h
deleted file mode 100644
index e4c6b41..0000000
--- a/base/task_runner.h
+++ /dev/null
@@ -1,158 +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_TASK_RUNNER_H_
-#define BASE_TASK_RUNNER_H_
-
-#include <stddef.h>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/location.h"
-#include "base/memory/ref_counted.h"
-#include "base/time/time.h"
-
-namespace base {
-
-struct TaskRunnerTraits;
-
-// A TaskRunner is an object that runs posted tasks (in the form of
-// Closure objects).  The TaskRunner interface provides a way of
-// decoupling task posting from the mechanics of how each task will be
-// run.  TaskRunner provides very weak guarantees as to how posted
-// tasks are run (or if they're run at all).  In particular, it only
-// guarantees:
-//
-//   - Posting a task will not run it synchronously.  That is, no
-//     Post*Task method will call task.Run() directly.
-//
-//   - Increasing the delay can only delay when the task gets run.
-//     That is, increasing the delay may not affect when the task gets
-//     run, or it could make it run later than it normally would, but
-//     it won't make it run earlier than it normally would.
-//
-// TaskRunner does not guarantee the order in which posted tasks are
-// run, whether tasks overlap, or whether they're run on a particular
-// thread.  Also it does not guarantee a memory model for shared data
-// between tasks.  (In other words, you should use your own
-// synchronization/locking primitives if you need to share data
-// between tasks.)
-//
-// Implementations of TaskRunner should be thread-safe in that all
-// methods must be safe to call on any thread.  Ownership semantics
-// for TaskRunners are in general not clear, which is why the
-// interface itself is RefCountedThreadSafe.
-//
-// Some theoretical implementations of TaskRunner:
-//
-//   - A TaskRunner that uses a thread pool to run posted tasks.
-//
-//   - A TaskRunner that, for each task, spawns a non-joinable thread
-//     to run that task and immediately quit.
-//
-//   - A TaskRunner that stores the list of posted tasks and has a
-//     method Run() that runs each runnable task in random order.
-class BASE_EXPORT TaskRunner
-    : public RefCountedThreadSafe<TaskRunner, TaskRunnerTraits> {
- public:
-  // Posts the given task to be run.  Returns true if the task may be
-  // run at some point in the future, and false if the task definitely
-  // will not be run.
-  //
-  // Equivalent to PostDelayedTask(from_here, task, 0).
-  bool PostTask(const Location& from_here, OnceClosure task);
-
-  // Like PostTask, but tries to run the posted task only after |delay_ms|
-  // has passed. Implementations should use a tick clock, rather than wall-
-  // clock time, to implement |delay|.
-  virtual bool PostDelayedTask(const Location& from_here,
-                               OnceClosure task,
-                               base::TimeDelta delay) = 0;
-
-  // Returns true iff tasks posted to this TaskRunner are sequenced
-  // with this call.
-  //
-  // In particular:
-  // - Returns true if this is a SequencedTaskRunner to which the
-  //   current task was posted.
-  // - Returns true if this is a SequencedTaskRunner bound to the
-  //   same sequence as the SequencedTaskRunner to which the current
-  //   task was posted.
-  // - Returns true if this is a SingleThreadTaskRunner bound to
-  //   the current thread.
-  // TODO(http://crbug.com/665062):
-  //   This API doesn't make sense for parallel TaskRunners.
-  //   Introduce alternate static APIs for documentation purposes of "this runs
-  //   in pool X", have RunsTasksInCurrentSequence() return false for parallel
-  //   TaskRunners, and ultimately move this method down to SequencedTaskRunner.
-  virtual bool RunsTasksInCurrentSequence() const = 0;
-
-  // Posts |task| on the current TaskRunner.  On completion, |reply|
-  // is posted to the thread that called PostTaskAndReply().  Both
-  // |task| and |reply| are guaranteed to be deleted on the thread
-  // from which PostTaskAndReply() is invoked.  This allows objects
-  // that must be deleted on the originating thread to be bound into
-  // the |task| and |reply| Closures.  In particular, it can be useful
-  // to use WeakPtr<> in the |reply| Closure so that the reply
-  // operation can be canceled. See the following pseudo-code:
-  //
-  // class DataBuffer : public RefCountedThreadSafe<DataBuffer> {
-  //  public:
-  //   // Called to add data into a buffer.
-  //   void AddData(void* buf, size_t length);
-  //   ...
-  // };
-  //
-  //
-  // class DataLoader : public SupportsWeakPtr<DataLoader> {
-  //  public:
-  //    void GetData() {
-  //      scoped_refptr<DataBuffer> buffer = new DataBuffer();
-  //      target_thread_.task_runner()->PostTaskAndReply(
-  //          FROM_HERE,
-  //          base::Bind(&DataBuffer::AddData, buffer),
-  //          base::Bind(&DataLoader::OnDataReceived, AsWeakPtr(), buffer));
-  //    }
-  //
-  //  private:
-  //    void OnDataReceived(scoped_refptr<DataBuffer> buffer) {
-  //      // Do something with buffer.
-  //    }
-  // };
-  //
-  //
-  // Things to notice:
-  //   * Results of |task| are shared with |reply| by binding a shared argument
-  //     (a DataBuffer instance).
-  //   * The DataLoader object has no special thread safety.
-  //   * The DataLoader object can be deleted while |task| is still running,
-  //     and the reply will cancel itself safely because it is bound to a
-  //     WeakPtr<>.
-  bool PostTaskAndReply(const Location& from_here,
-                        OnceClosure task,
-                        OnceClosure reply);
-
- protected:
-  friend struct TaskRunnerTraits;
-
-  // Only the Windows debug build seems to need this: see
-  // http://crbug.com/112250.
-  friend class RefCountedThreadSafe<TaskRunner, TaskRunnerTraits>;
-
-  TaskRunner();
-  virtual ~TaskRunner();
-
-  // Called when this object should be destroyed.  By default simply
-  // deletes |this|, but can be overridden to do something else, like
-  // delete on a certain thread.
-  virtual void OnDestruct() const;
-};
-
-struct BASE_EXPORT TaskRunnerTraits {
-  static void Destruct(const TaskRunner* task_runner);
-};
-
-}  // namespace base
-
-#endif  // BASE_TASK_RUNNER_H_
diff --git a/base/task_runner_util.h b/base/task_runner_util.h
deleted file mode 100644
index d79f5b8..0000000
--- a/base/task_runner_util.h
+++ /dev/null
@@ -1,67 +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_TASK_RUNNER_UTIL_H_
-#define BASE_TASK_RUNNER_UTIL_H_
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/callback.h"
-#include "base/logging.h"
-#include "base/post_task_and_reply_with_result_internal.h"
-#include "base/task_runner.h"
-
-namespace base {
-
-// When you have these methods
-//
-//   R DoWorkAndReturn();
-//   void Callback(const R& result);
-//
-// and want to call them in a PostTaskAndReply kind of fashion where the
-// result of DoWorkAndReturn is passed to the Callback, you can use
-// PostTaskAndReplyWithResult as in this example:
-//
-// PostTaskAndReplyWithResult(
-//     target_thread_.task_runner(),
-//     FROM_HERE,
-//     BindOnce(&DoWorkAndReturn),
-//     BindOnce(&Callback));
-template <typename TaskReturnType, typename ReplyArgType>
-bool PostTaskAndReplyWithResult(TaskRunner* task_runner,
-                                const Location& from_here,
-                                OnceCallback<TaskReturnType()> task,
-                                OnceCallback<void(ReplyArgType)> reply) {
-  DCHECK(task);
-  DCHECK(reply);
-  TaskReturnType* result = new TaskReturnType();
-  return task_runner->PostTaskAndReply(
-      from_here,
-      BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>, std::move(task),
-               result),
-      BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>,
-               std::move(reply), Owned(result)));
-}
-
-// Callback version of PostTaskAndReplyWithResult above.
-// Though RepeatingCallback is convertible to OnceCallback, we need this since
-// we cannot use template deduction and object conversion at once on the
-// overload resolution.
-// TODO(crbug.com/714018): Update all callers of the Callback version to use
-// OnceCallback.
-template <typename TaskReturnType, typename ReplyArgType>
-bool PostTaskAndReplyWithResult(TaskRunner* task_runner,
-                                const Location& from_here,
-                                Callback<TaskReturnType()> task,
-                                Callback<void(ReplyArgType)> reply) {
-  return PostTaskAndReplyWithResult(
-      task_runner, from_here, OnceCallback<TaskReturnType()>(std::move(task)),
-      OnceCallback<void(ReplyArgType)>(std::move(reply)));
-}
-
-}  // namespace base
-
-#endif  // BASE_TASK_RUNNER_UTIL_H_
diff --git a/base/task_scheduler/OWNERS b/base/task_scheduler/OWNERS
deleted file mode 100644
index 0f3ad5e..0000000
--- a/base/task_scheduler/OWNERS
+++ /dev/null
@@ -1,6 +0,0 @@
-fdoray@chromium.org
-gab@chromium.org
-robliao@chromium.org
-
-# TEAM: scheduler-dev@chromium.org
-# COMPONENT: Internals>TaskScheduler
diff --git a/base/task_scheduler/can_schedule_sequence_observer.h b/base/task_scheduler/can_schedule_sequence_observer.h
deleted file mode 100644
index f2b0551..0000000
--- a/base/task_scheduler/can_schedule_sequence_observer.h
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2017 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_TASK_SCHEDULER_CAN_SCHEDULE_SEQUENCE_OBSERVER_H_
-#define BASE_TASK_SCHEDULER_CAN_SCHEDULE_SEQUENCE_OBSERVER_H_
-
-#include "base/task_scheduler/sequence.h"
-
-namespace base {
-namespace internal {
-
-class CanScheduleSequenceObserver {
- public:
-  // Called when |sequence| can be scheduled. It is expected that
-  // TaskTracker::RunNextTask() will be called with |sequence| as argument after
-  // this is called.
-  virtual void OnCanScheduleSequence(scoped_refptr<Sequence> sequence) = 0;
-
- protected:
-  virtual ~CanScheduleSequenceObserver() = default;
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_CAN_SCHEDULE_SEQUENCE_OBSERVER_H_
diff --git a/base/task_scheduler/delayed_task_manager.cc b/base/task_scheduler/delayed_task_manager.cc
deleted file mode 100644
index 86a6721..0000000
--- a/base/task_scheduler/delayed_task_manager.cc
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2016 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/task_scheduler/delayed_task_manager.h"
-
-#include <algorithm>
-
-#include "base/bind.h"
-#include "base/logging.h"
-#include "base/task_runner.h"
-#include "base/task_scheduler/task.h"
-
-namespace base {
-namespace internal {
-
-DelayedTaskManager::DelayedTaskManager(
-    std::unique_ptr<const TickClock> tick_clock)
-    : tick_clock_(std::move(tick_clock)) {
-  DCHECK(tick_clock_);
-}
-
-DelayedTaskManager::~DelayedTaskManager() = default;
-
-void DelayedTaskManager::Start(
-    scoped_refptr<TaskRunner> service_thread_task_runner) {
-  DCHECK(service_thread_task_runner);
-
-  decltype(tasks_added_before_start_) tasks_added_before_start;
-
-  {
-    AutoSchedulerLock auto_lock(lock_);
-    DCHECK(!service_thread_task_runner_);
-    DCHECK(!started_.IsSet());
-    service_thread_task_runner_ = std::move(service_thread_task_runner);
-    tasks_added_before_start = std::move(tasks_added_before_start_);
-    // |service_thread_task_runner_| must not change after |started_| is set
-    // (cf. comment above |lock_| in header file).
-    started_.Set();
-  }
-
-  const TimeTicks now = tick_clock_->NowTicks();
-  for (auto& task_and_callback : tasks_added_before_start) {
-    const TimeDelta delay =
-        std::max(TimeDelta(), task_and_callback.first.delayed_run_time - now);
-    AddDelayedTaskNow(std::move(task_and_callback.first), delay,
-                      std::move(task_and_callback.second));
-  }
-}
-
-void DelayedTaskManager::AddDelayedTask(
-    Task task,
-    PostTaskNowCallback post_task_now_callback) {
-  DCHECK(task.task);
-
-  const TimeDelta delay = task.delay;
-  DCHECK(!delay.is_zero());
-
-  // Use CHECK instead of DCHECK to crash earlier. See http://crbug.com/711167
-  // for details.
-  CHECK(task.task);
-
-  // If |started_| is set, the DelayedTaskManager is in a stable state and
-  // AddDelayedTaskNow() can be called without synchronization. Otherwise, it is
-  // necessary to acquire |lock_| and recheck.
-  if (started_.IsSet()) {
-    AddDelayedTaskNow(std::move(task), delay,
-                      std::move(post_task_now_callback));
-  } else {
-    AutoSchedulerLock auto_lock(lock_);
-    if (started_.IsSet()) {
-      AddDelayedTaskNow(std::move(task), delay,
-                        std::move(post_task_now_callback));
-    } else {
-      tasks_added_before_start_.push_back(
-          {std::move(task), std::move(post_task_now_callback)});
-    }
-  }
-}
-
-void DelayedTaskManager::AddDelayedTaskNow(
-    Task task,
-    TimeDelta delay,
-    PostTaskNowCallback post_task_now_callback) {
-  DCHECK(task.task);
-  DCHECK(started_.IsSet());
-  // TODO(fdoray): Use |task->delayed_run_time| on the service thread
-  // MessageLoop rather than recomputing it from |delay|.
-  service_thread_task_runner_->PostDelayedTask(
-      FROM_HERE, BindOnce(std::move(post_task_now_callback), std::move(task)),
-      delay);
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/delayed_task_manager.h b/base/task_scheduler/delayed_task_manager.h
deleted file mode 100644
index c48aeb1..0000000
--- a/base/task_scheduler/delayed_task_manager.h
+++ /dev/null
@@ -1,80 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_DELAYED_TASK_MANAGER_H_
-#define BASE_TASK_SCHEDULER_DELAYED_TASK_MANAGER_H_
-
-#include <memory>
-#include <utility>
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/memory/ref_counted.h"
-#include "base/synchronization/atomic_flag.h"
-#include "base/task_scheduler/scheduler_lock.h"
-#include "base/time/default_tick_clock.h"
-#include "base/time/tick_clock.h"
-
-namespace base {
-
-class TaskRunner;
-
-namespace internal {
-
-struct Task;
-
-// The DelayedTaskManager forwards tasks to post task callbacks when they become
-// ripe for execution. Tasks are not forwarded before Start() is called. This
-// class is thread-safe.
-class BASE_EXPORT DelayedTaskManager {
- public:
-  // Posts |task| for execution immediately.
-  using PostTaskNowCallback = OnceCallback<void(Task task)>;
-
-  // |tick_clock| can be specified for testing.
-  DelayedTaskManager(std::unique_ptr<const TickClock> tick_clock =
-                         std::make_unique<DefaultTickClock>());
-  ~DelayedTaskManager();
-
-  // Starts the delayed task manager, allowing past and future tasks to be
-  // forwarded to their callbacks as they become ripe for execution.
-  // |service_thread_task_runner| posts tasks to the TaskScheduler service
-  // thread.
-  void Start(scoped_refptr<TaskRunner> service_thread_task_runner);
-
-  // Schedules a call to |post_task_now_callback| with |task| as argument when
-  // |task| is ripe for execution and Start() has been called.
-  void AddDelayedTask(Task task, PostTaskNowCallback post_task_now_callback);
-
- private:
-  // Schedules a call to |post_task_now_callback| with |task| as argument when
-  // |delay| expires. Start() must have been called before this.
-  void AddDelayedTaskNow(Task task,
-                         TimeDelta delay,
-                         PostTaskNowCallback post_task_now_callback);
-
-  const std::unique_ptr<const TickClock> tick_clock_;
-
-  AtomicFlag started_;
-
-  // Synchronizes access to all members below before |started_| is set. Once
-  // |started_| is set:
-  // - |service_thread_task_runner| doest not change, so it can be read without
-  //   holding the lock.
-  // - |tasks_added_before_start_| isn't accessed anymore.
-  SchedulerLock lock_;
-
-  scoped_refptr<TaskRunner> service_thread_task_runner_;
-  std::vector<std::pair<Task, PostTaskNowCallback>> tasks_added_before_start_;
-
-  DISALLOW_COPY_AND_ASSIGN(DelayedTaskManager);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_DELAYED_TASK_MANAGER_H_
diff --git a/base/task_scheduler/environment_config.cc b/base/task_scheduler/environment_config.cc
deleted file mode 100644
index 393b591..0000000
--- a/base/task_scheduler/environment_config.cc
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright 2017 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/task_scheduler/environment_config.h"
-
-namespace base {
-namespace internal {
-
-size_t GetEnvironmentIndexForTraits(const TaskTraits& traits) {
-  const bool is_background =
-      traits.priority() == base::TaskPriority::BACKGROUND;
-  if (traits.may_block() || traits.with_base_sync_primitives())
-    return is_background ? BACKGROUND_BLOCKING : FOREGROUND_BLOCKING;
-  return is_background ? BACKGROUND : FOREGROUND;
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/environment_config.h b/base/task_scheduler/environment_config.h
deleted file mode 100644
index 54f2ff3..0000000
--- a/base/task_scheduler/environment_config.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2017 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_TASK_SCHEDULER_ENVIRONMENT_CONFIG_H_
-#define BASE_TASK_SCHEDULER_ENVIRONMENT_CONFIG_H_
-
-#include <stddef.h>
-
-#include "base/base_export.h"
-#include "base/task_scheduler/task_traits.h"
-#include "base/threading/thread.h"
-
-namespace base {
-namespace internal {
-
-enum EnvironmentType {
-  BACKGROUND = 0,
-  BACKGROUND_BLOCKING,
-  FOREGROUND,
-  FOREGROUND_BLOCKING,
-  ENVIRONMENT_COUNT  // Always last.
-};
-
-// Order must match the EnvironmentType enum.
-constexpr struct {
-  // The threads and histograms of this environment will be labeled with
-  // the task scheduler name concatenated to this.
-  const char* name_suffix;
-
-  // Preferred priority for threads in this environment; the actual thread
-  // priority depends on shutdown state and platform capabilities.
-  ThreadPriority priority_hint;
-} kEnvironmentParams[] = {
-    {"Background", base::ThreadPriority::BACKGROUND},
-    {"BackgroundBlocking", base::ThreadPriority::BACKGROUND},
-    {"Foreground", base::ThreadPriority::NORMAL},
-    {"ForegroundBlocking", base::ThreadPriority::NORMAL},
-};
-
-size_t BASE_EXPORT GetEnvironmentIndexForTraits(const TaskTraits& traits);
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_ENVIRONMENT_CONFIG_H_
diff --git a/base/task_scheduler/initialization_util.cc b/base/task_scheduler/initialization_util.cc
deleted file mode 100644
index 7accd19..0000000
--- a/base/task_scheduler/initialization_util.cc
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright 2016 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/task_scheduler/initialization_util.h"
-
-#include <algorithm>
-
-#include "base/sys_info.h"
-
-namespace base {
-
-int RecommendedMaxNumberOfThreadsInPool(int min,
-                                        int max,
-                                        double cores_multiplier,
-                                        int offset) {
-  const int num_of_cores = SysInfo::NumberOfProcessors();
-  const int threads = std::ceil<int>(num_of_cores * cores_multiplier) + offset;
-  return std::min(max, std::max(min, threads));
-}
-
-}  // namespace base
diff --git a/base/task_scheduler/initialization_util.h b/base/task_scheduler/initialization_util.h
deleted file mode 100644
index c3bd9e7..0000000
--- a/base/task_scheduler/initialization_util.h
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_INITIALIZATION_UTIL_H_
-#define BASE_TASK_SCHEDULER_INITIALIZATION_UTIL_H_
-
-#include "base/base_export.h"
-
-namespace base {
-
-// Computes a value that may be used as the maximum number of threads in a
-// TaskScheduler pool. Developers may use other methods to choose this maximum.
-BASE_EXPORT int RecommendedMaxNumberOfThreadsInPool(int min,
-                                                    int max,
-                                                    double cores_multiplier,
-                                                    int offset);
-
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_INITIALIZATION_UTIL_H_
diff --git a/base/task_scheduler/lazy_task_runner.cc b/base/task_scheduler/lazy_task_runner.cc
deleted file mode 100644
index 218d02b..0000000
--- a/base/task_scheduler/lazy_task_runner.cc
+++ /dev/null
@@ -1,122 +0,0 @@
-// Copyright 2017 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/task_scheduler/lazy_task_runner.h"
-
-#include <utility>
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/task_scheduler/post_task.h"
-
-namespace base {
-namespace internal {
-
-namespace {
-ScopedLazyTaskRunnerListForTesting* g_scoped_lazy_task_runner_list_for_testing =
-    nullptr;
-}  // namespace
-
-template <typename TaskRunnerType, bool com_sta>
-void LazyTaskRunner<TaskRunnerType, com_sta>::Reset() {
-  subtle::AtomicWord state = subtle::Acquire_Load(&state_);
-
-  DCHECK_NE(state, kLazyInstanceStateCreating) << "Race: all threads should be "
-                                                  "unwound in unittests before "
-                                                  "resetting TaskRunners.";
-
-  // Return if no reference is held by this instance.
-  if (!state)
-    return;
-
-  // Release the reference acquired in Get().
-  SequencedTaskRunner* task_runner = reinterpret_cast<TaskRunnerType*>(state);
-  task_runner->Release();
-
-  // Clear the state.
-  subtle::NoBarrier_Store(&state_, 0);
-}
-
-template <>
-scoped_refptr<SequencedTaskRunner>
-LazyTaskRunner<SequencedTaskRunner, false>::Create() {
-  // It is invalid to specify a SingleThreadTaskRunnerThreadMode with a
-  // LazySequencedTaskRunner.
-  DCHECK_EQ(thread_mode_, SingleThreadTaskRunnerThreadMode::SHARED);
-
-  return CreateSequencedTaskRunnerWithTraits(traits_);
-}
-
-template <>
-scoped_refptr<SingleThreadTaskRunner>
-LazyTaskRunner<SingleThreadTaskRunner, false>::Create() {
-  return CreateSingleThreadTaskRunnerWithTraits(traits_, thread_mode_);
-}
-
-#if defined(OS_WIN)
-template <>
-scoped_refptr<SingleThreadTaskRunner>
-LazyTaskRunner<SingleThreadTaskRunner, true>::Create() {
-  return CreateCOMSTATaskRunnerWithTraits(traits_, thread_mode_);
-}
-#endif
-
-// static
-template <typename TaskRunnerType, bool com_sta>
-TaskRunnerType* LazyTaskRunner<TaskRunnerType, com_sta>::CreateRaw(
-    void* void_self) {
-  auto self =
-      reinterpret_cast<LazyTaskRunner<TaskRunnerType, com_sta>*>(void_self);
-
-  scoped_refptr<TaskRunnerType> task_runner = self->Create();
-
-  // Acquire a reference to the TaskRunner. The reference will either
-  // never be released or be released in Reset(). The reference is not
-  // managed by a scoped_refptr because adding a scoped_refptr member to
-  // LazyTaskRunner would prevent its static initialization.
-  task_runner->AddRef();
-
-  // Reset this instance when the current
-  // ScopedLazyTaskRunnerListForTesting is destroyed, if any.
-  if (g_scoped_lazy_task_runner_list_for_testing) {
-    g_scoped_lazy_task_runner_list_for_testing->AddCallback(BindOnce(
-        &LazyTaskRunner<TaskRunnerType, com_sta>::Reset, Unretained(self)));
-  }
-
-  return task_runner.get();
-}
-
-template <typename TaskRunnerType, bool com_sta>
-scoped_refptr<TaskRunnerType> LazyTaskRunner<TaskRunnerType, com_sta>::Get() {
-  return WrapRefCounted(subtle::GetOrCreateLazyPointer(
-      &state_, &LazyTaskRunner<TaskRunnerType, com_sta>::CreateRaw,
-      reinterpret_cast<void*>(this), nullptr, nullptr));
-}
-
-template class LazyTaskRunner<SequencedTaskRunner, false>;
-template class LazyTaskRunner<SingleThreadTaskRunner, false>;
-
-#if defined(OS_WIN)
-template class LazyTaskRunner<SingleThreadTaskRunner, true>;
-#endif
-
-ScopedLazyTaskRunnerListForTesting::ScopedLazyTaskRunnerListForTesting() {
-  DCHECK(!g_scoped_lazy_task_runner_list_for_testing);
-  g_scoped_lazy_task_runner_list_for_testing = this;
-}
-
-ScopedLazyTaskRunnerListForTesting::~ScopedLazyTaskRunnerListForTesting() {
-  internal::AutoSchedulerLock auto_lock(lock_);
-  for (auto& callback : callbacks_)
-    std::move(callback).Run();
-  g_scoped_lazy_task_runner_list_for_testing = nullptr;
-}
-
-void ScopedLazyTaskRunnerListForTesting::AddCallback(OnceClosure callback) {
-  internal::AutoSchedulerLock auto_lock(lock_);
-  callbacks_.push_back(std::move(callback));
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/lazy_task_runner.h b/base/task_scheduler/lazy_task_runner.h
deleted file mode 100644
index c0e0940..0000000
--- a/base/task_scheduler/lazy_task_runner.h
+++ /dev/null
@@ -1,218 +0,0 @@
-// Copyright 2017 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_TASK_SCHEDULER_LAZY_TASK_RUNNER_H_
-#define BASE_TASK_SCHEDULER_LAZY_TASK_RUNNER_H_
-
-#include <vector>
-
-#include "base/atomicops.h"
-#include "base/callback.h"
-#include "base/compiler_specific.h"
-#include "base/lazy_instance_helpers.h"
-#include "base/sequenced_task_runner.h"
-#include "base/single_thread_task_runner.h"
-#include "base/task_scheduler/scheduler_lock.h"
-#include "base/task_scheduler/single_thread_task_runner_thread_mode.h"
-#include "base/task_scheduler/task_traits.h"
-#include "build_config.h"
-
-// Lazy(Sequenced|SingleThread|COMSTA)TaskRunner lazily creates a TaskRunner.
-//
-// Lazy(Sequenced|SingleThread|COMSTA)TaskRunner is meant to be instantiated in
-// an anonymous namespace (no static initializer is generated) and used to post
-// tasks to the same sequence/thread from pieces of code that don't have a
-// better way of sharing a TaskRunner. It is important to use this class
-// instead of a self-managed global variable or LazyInstance so that the
-// TaskRunners do not outlive the scope of the ScopedTaskEnvironment in unit
-// tests (otherwise the next test in the same process will die in use-after-
-// frees).
-//
-// IMPORTANT: Only use this API as a last resort. Prefer storing a
-// (Sequenced|SingleThread)TaskRunner returned by
-// base::Create(Sequenced|SingleThread|COMSTA)TaskRunnerWithTraits() as a member
-// on an object accessible by all PostTask() call sites.
-//
-// Example usage 1:
-//
-// namespace {
-// base::LazySequencedTaskRunner g_sequenced_task_runner =
-//     LAZY_SEQUENCED_TASK_RUNNER_INITIALIZER(
-//         base::TaskTraits(base::MayBlock(),
-//                          base::TaskPriority::USER_VISIBLE));
-// }  // namespace
-//
-// void SequencedFunction() {
-//   // Different invocations of this function post to the same
-//   // MayBlock() SequencedTaskRunner.
-//   g_sequenced_task_runner.Get()->PostTask(FROM_HERE, base::BindOnce(...));
-// }
-//
-// Example usage 2:
-//
-// namespace {
-// base::LazySequencedTaskRunner g_sequenced_task_task_runner =
-//     LAZY_SEQUENCED_TASK_RUNNER_INITIALIZER({base::MayBlock()});
-// }  // namespace
-//
-// // Code from different files can access the SequencedTaskRunner via this
-// // function.
-// scoped_refptr<base::SequencedTaskRunner> GetTaskRunner() {
-//   return g_sequenced_task_runner.Get();
-// }
-
-namespace base {
-
-namespace internal {
-template <typename TaskRunnerType, bool com_sta>
-class BASE_EXPORT LazyTaskRunner;
-}  // namespace internal
-
-// Lazy SequencedTaskRunner.
-using LazySequencedTaskRunner =
-    internal::LazyTaskRunner<SequencedTaskRunner, false>;
-
-// Lazy SingleThreadTaskRunner.
-using LazySingleThreadTaskRunner =
-    internal::LazyTaskRunner<SingleThreadTaskRunner, false>;
-
-#if defined(OS_WIN)
-// Lazy COM-STA enabled SingleThreadTaskRunner.
-using LazyCOMSTATaskRunner =
-    internal::LazyTaskRunner<SingleThreadTaskRunner, true>;
-#endif
-
-// Helper macros to generate a variable name by concatenation.
-#define LAZY_TASK_RUNNER_CONCATENATE_INTERNAL2(a, b) a##b
-#define LAZY_TASK_RUNNER_CONCATENATE_INTERNAL(a, b) \
-  LAZY_TASK_RUNNER_CONCATENATE_INTERNAL2(a, b)
-
-// Use the macros below to initialize a LazyTaskRunner. These macros verify that
-// their arguments are constexpr, which is important to prevent the generation
-// of a static initializer.
-
-// |traits| are TaskTraits used when creating the SequencedTaskRunner.
-#define LAZY_SEQUENCED_TASK_RUNNER_INITIALIZER(traits)                 \
-  base::LazySequencedTaskRunner::CreateInternal(traits);               \
-  ALLOW_UNUSED_TYPE constexpr base::TaskTraits                         \
-      LAZY_TASK_RUNNER_CONCATENATE_INTERNAL(kVerifyTraitsAreConstexpr, \
-                                            __LINE__) = traits
-
-// |traits| are TaskTraits used when creating the SingleThreadTaskRunner.
-// |thread_mode| specifies whether the SingleThreadTaskRunner can share its
-// thread with other SingleThreadTaskRunners.
-#define LAZY_SINGLE_THREAD_TASK_RUNNER_INITIALIZER(traits, thread_mode)   \
-  base::LazySingleThreadTaskRunner::CreateInternal(traits, thread_mode);  \
-  ALLOW_UNUSED_TYPE constexpr base::TaskTraits                            \
-      LAZY_TASK_RUNNER_CONCATENATE_INTERNAL(kVerifyTraitsAreConstexpr,    \
-                                            __LINE__) = traits;           \
-  ALLOW_UNUSED_TYPE constexpr base::SingleThreadTaskRunnerThreadMode      \
-      LAZY_TASK_RUNNER_CONCATENATE_INTERNAL(kVerifyThreadModeIsConstexpr, \
-                                            __LINE__) = thread_mode
-
-// |traits| are TaskTraits used when creating the COM STA
-// SingleThreadTaskRunner. |thread_mode| specifies whether the COM STA
-// SingleThreadTaskRunner can share its thread with other
-// SingleThreadTaskRunners.
-#define LAZY_COM_STA_TASK_RUNNER_INITIALIZER(traits, thread_mode)         \
-  base::LazyCOMSTATaskRunner::CreateInternal(traits, thread_mode);        \
-  ALLOW_UNUSED_TYPE constexpr base::TaskTraits                            \
-      LAZY_TASK_RUNNER_CONCATENATE_INTERNAL(kVerifyTraitsAreConstexpr,    \
-                                            __LINE__) = traits;           \
-  ALLOW_UNUSED_TYPE constexpr base::SingleThreadTaskRunnerThreadMode      \
-      LAZY_TASK_RUNNER_CONCATENATE_INTERNAL(kVerifyThreadModeIsConstexpr, \
-                                            __LINE__) = thread_mode
-
-namespace internal {
-
-template <typename TaskRunnerType, bool com_sta>
-class BASE_EXPORT LazyTaskRunner {
- public:
-  // Use the macros above rather than a direct call to this.
-  //
-  // |traits| are TaskTraits to use to create the TaskRunner. If this
-  // LazyTaskRunner is specialized to create a SingleThreadTaskRunner,
-  // |thread_mode| specifies whether the SingleThreadTaskRunner can share its
-  // thread with other SingleThreadTaskRunner. Otherwise, it is unused.
-  static constexpr LazyTaskRunner CreateInternal(
-      const TaskTraits& traits,
-      SingleThreadTaskRunnerThreadMode thread_mode =
-          SingleThreadTaskRunnerThreadMode::SHARED) {
-    return LazyTaskRunner(traits, thread_mode);
-  }
-
-  // Returns the TaskRunner held by this instance. Creates it if it didn't
-  // already exist. Thread-safe.
-  scoped_refptr<TaskRunnerType> Get();
-
- private:
-  constexpr LazyTaskRunner(const TaskTraits& traits,
-                           SingleThreadTaskRunnerThreadMode thread_mode =
-                               SingleThreadTaskRunnerThreadMode::SHARED)
-      : traits_(traits), thread_mode_(thread_mode) {}
-
-  // Releases the TaskRunner held by this instance.
-  void Reset();
-
-  // Creates and returns a new TaskRunner.
-  scoped_refptr<TaskRunnerType> Create();
-
-  // Creates a new TaskRunner via Create(), adds an explicit ref to it, and
-  // returns it raw. Used as an adapter for lazy instance helpers. Static and
-  // takes |this| as an explicit param to match the void* signature of
-  // GetOrCreateLazyPointer().
-  static TaskRunnerType* CreateRaw(void* void_self);
-
-  // TaskTraits to create the TaskRunner.
-  const TaskTraits traits_;
-
-  // SingleThreadTaskRunnerThreadMode to create the TaskRunner.
-  const SingleThreadTaskRunnerThreadMode thread_mode_;
-
-  // Can have 3 states:
-  // - This instance does not hold a TaskRunner: 0
-  // - This instance is creating a TaskRunner: kLazyInstanceStateCreating
-  // - This instance holds a TaskRunner: Pointer to the TaskRunner.
-  // LazyInstance's internals are reused to handle transition between states.
-  subtle::AtomicWord state_ = 0;
-
-  // No DISALLOW_COPY_AND_ASSIGN since that prevents static initialization with
-  // Visual Studio (warning C4592: 'symbol will be dynamically initialized
-  // (implementation limitation))'.
-};
-
-// When a LazyTaskRunner becomes active (invokes Get()), it adds a callback to
-// the current ScopedLazyTaskRunnerListForTesting, if any. Callbacks run when
-// the ScopedLazyTaskRunnerListForTesting is destroyed. In a test process, a
-// ScopedLazyTaskRunnerListForTesting must be instantiated before any
-// LazyTaskRunner becomes active.
-class BASE_EXPORT ScopedLazyTaskRunnerListForTesting {
- public:
-  ScopedLazyTaskRunnerListForTesting();
-  ~ScopedLazyTaskRunnerListForTesting();
-
- private:
-  friend class LazyTaskRunner<SequencedTaskRunner, false>;
-  friend class LazyTaskRunner<SingleThreadTaskRunner, false>;
-
-#if defined(OS_WIN)
-  friend class LazyTaskRunner<SingleThreadTaskRunner, true>;
-#endif
-
-  // Add |callback| to the list of callbacks to run on destruction.
-  void AddCallback(OnceClosure callback);
-
-  // Synchronizes accesses to |callbacks_|.
-  SchedulerLock lock_;
-
-  // List of callbacks to run on destruction.
-  std::vector<OnceClosure> callbacks_;
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedLazyTaskRunnerListForTesting);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_LAZY_TASK_RUNNER_H_
diff --git a/base/task_scheduler/platform_native_worker_pool_win.cc b/base/task_scheduler/platform_native_worker_pool_win.cc
deleted file mode 100644
index ebad3a3..0000000
--- a/base/task_scheduler/platform_native_worker_pool_win.cc
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright 2017 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/task_scheduler/platform_native_worker_pool_win.h"
-
-#include "base/task_scheduler/task_tracker.h"
-
-namespace base {
-namespace internal {
-
-PlatformNativeWorkerPoolWin::PlatformNativeWorkerPoolWin(
-    TrackedRef<TaskTracker> task_tracker,
-    DelayedTaskManager* delayed_task_manager)
-    : SchedulerWorkerPool(task_tracker, delayed_task_manager) {}
-
-PlatformNativeWorkerPoolWin::~PlatformNativeWorkerPoolWin() {
-#if DCHECK_IS_ON()
-  // Verify join_for_testing has been called to ensure that there is no more
-  // outstanding work. Otherwise, work may try to de-reference an invalid
-  // pointer to this class.
-  DCHECK(join_for_testing_returned_.IsSet());
-#endif
-  ::DestroyThreadpoolEnvironment(&environment_);
-  ::CloseThreadpoolWork(work_);
-  ::CloseThreadpool(pool_);
-}
-
-void PlatformNativeWorkerPoolWin::Start() {
-  ::InitializeThreadpoolEnvironment(&environment_);
-
-  pool_ = ::CreateThreadpool(nullptr);
-  DCHECK(pool_) << "LastError: " << ::GetLastError();
-  ::SetThreadpoolThreadMinimum(pool_, 1);
-  ::SetThreadpoolThreadMaximum(pool_, 256);
-
-  work_ = ::CreateThreadpoolWork(&RunNextSequence, this, &environment_);
-  DCHECK(work_) << "LastError: " << GetLastError();
-  ::SetThreadpoolCallbackPool(&environment_, pool_);
-
-  size_t local_num_sequences_before_start;
-  {
-    auto transaction(priority_queue_.BeginTransaction());
-    DCHECK(!started_);
-    started_ = true;
-    local_num_sequences_before_start = transaction->Size();
-  }
-
-  // Schedule sequences added to |priority_queue_| before Start().
-  for (size_t i = 0; i < local_num_sequences_before_start; ++i)
-    ::SubmitThreadpoolWork(work_);
-}
-
-void PlatformNativeWorkerPoolWin::JoinForTesting() {
-  ::WaitForThreadpoolWorkCallbacks(work_, true);
-#if DCHECK_IS_ON()
-  DCHECK(!join_for_testing_returned_.IsSet());
-  join_for_testing_returned_.Set();
-#endif
-}
-
-// static
-void CALLBACK PlatformNativeWorkerPoolWin::RunNextSequence(
-    PTP_CALLBACK_INSTANCE,
-    void* scheduler_worker_pool_windows_impl,
-    PTP_WORK) {
-  auto* worker_pool = static_cast<PlatformNativeWorkerPoolWin*>(
-      scheduler_worker_pool_windows_impl);
-
-  worker_pool->BindToCurrentThread();
-
-  scoped_refptr<Sequence> sequence = worker_pool->GetWork();
-  DCHECK(sequence);
-
-  sequence = worker_pool->task_tracker_->RunAndPopNextTask(
-      std::move(sequence.get()), worker_pool);
-
-  // Re-enqueue sequence and then submit another task to the Windows thread
-  // pool.
-  if (sequence)
-    worker_pool->OnCanScheduleSequence(std::move(sequence));
-
-  worker_pool->UnbindFromCurrentThread();
-}
-
-scoped_refptr<Sequence> PlatformNativeWorkerPoolWin::GetWork() {
-  auto transaction(priority_queue_.BeginTransaction());
-
-  // The PQ should never be empty here as there's a 1:1 correspondence between
-  // a call to ScheduleSequence()/SubmitThreadpoolWork() and GetWork().
-  DCHECK(!transaction->IsEmpty());
-  return transaction->PopSequence();
-}
-
-void PlatformNativeWorkerPoolWin::OnCanScheduleSequence(
-    scoped_refptr<Sequence> sequence) {
-  const SequenceSortKey sequence_sort_key = sequence->GetSortKey();
-  auto transaction(priority_queue_.BeginTransaction());
-
-  transaction->Push(std::move(sequence), sequence_sort_key);
-  if (started_) {
-    // TODO(fdoray): Handle priorities by having different work objects and
-    // using ::SetThreadpoolCallbackPriority() and
-    // ::SetThreadpoolCallbackRunsLong().
-    ::SubmitThreadpoolWork(work_);
-  }
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/platform_native_worker_pool_win.h b/base/task_scheduler/platform_native_worker_pool_win.h
deleted file mode 100644
index be903b5..0000000
--- a/base/task_scheduler/platform_native_worker_pool_win.h
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright 2017 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_TASK_SCHEDULER_PLATFORM_NATIVE_WORKER_POOL_WIN_H
-#define BASE_TASK_SCHEDULER_PLATFORM_NATIVE_WORKER_POOL_WIN_H
-
-#include <windows.h>
-
-#include "base/base_export.h"
-#include "base/logging.h"
-#include "base/synchronization/atomic_flag.h"
-#include "base/task_scheduler/priority_queue.h"
-#include "base/task_scheduler/scheduler_worker_pool.h"
-
-namespace base {
-namespace internal {
-
-// A SchedulerWorkerPool implementation backed by the Windows Thread Pool API.
-//
-// Windows Thread Pool API official documentation:
-// https://msdn.microsoft.com/en-us/library/windows/desktop/ms686766(v=vs.85).aspx
-//
-// Blog posts on the Windows Thread Pool API:
-// https://msdn.microsoft.com/magazine/hh335066.aspx
-// https://msdn.microsoft.com/magazine/hh394144.aspx
-// https://msdn.microsoft.com/magazine/hh456398.aspx
-// https://msdn.microsoft.com/magazine/hh547107.aspx
-// https://msdn.microsoft.com/magazine/hh580731.aspx
-class BASE_EXPORT PlatformNativeWorkerPoolWin : public SchedulerWorkerPool {
- public:
-  PlatformNativeWorkerPoolWin(TrackedRef<TaskTracker> task_tracker,
-                              DelayedTaskManager* delayed_task_manager);
-
-  // Destroying a PlatformNativeWorkerPoolWin is not allowed in
-  // production; it is always leaked. In tests, it can only be destroyed after
-  // JoinForTesting() has returned.
-  ~PlatformNativeWorkerPoolWin() override;
-
-  // Starts the worker pool and allows tasks to begin running.
-  void Start();
-
-  // SchedulerWorkerPool:
-  void JoinForTesting() override;
-
- private:
-  // Callback that gets run by |pool_|. It runs a task off the next sequence on
-  // the |priority_queue_|.
-  static void CALLBACK RunNextSequence(PTP_CALLBACK_INSTANCE,
-                                       void* scheduler_worker_pool_windows_impl,
-                                       PTP_WORK);
-
-  // SchedulerWorkerPool:
-  void OnCanScheduleSequence(scoped_refptr<Sequence> sequence) override;
-
-  // Returns the top Sequence off the |priority_queue_|. Returns nullptr
-  // if the |priority_queue_| is empty.
-  scoped_refptr<Sequence> GetWork();
-
-  // Thread pool object that |work_| gets executed on.
-  PTP_POOL pool_ = nullptr;
-
-  // Callback environment. |pool_| is associated with |environment_| so that
-  // work objects using this environment run on |pool_|.
-  TP_CALLBACK_ENVIRON environment_ = {};
-
-  // Work object that executes RunNextSequence. It has a pointer to the current
-  // |PlatformNativeWorkerPoolWin| and a pointer to |environment_| bound to
-  // it.
-  PTP_WORK work_ = nullptr;
-
-  // PriorityQueue from which all threads of this worker pool get work.
-  PriorityQueue priority_queue_;
-
-  // Indicates whether the pool has been started yet. This is only accessed
-  // under |priority_queue_|'s lock.
-  bool started_ = false;
-
-#if DCHECK_IS_ON()
-  // Set once JoinForTesting() has returned.
-  AtomicFlag join_for_testing_returned_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(PlatformNativeWorkerPoolWin);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_PLATFORM_NATIVE_WORKER_POOL_WIN_H
diff --git a/base/task_scheduler/post_task.cc b/base/task_scheduler/post_task.cc
deleted file mode 100644
index 15210a5..0000000
--- a/base/task_scheduler/post_task.cc
+++ /dev/null
@@ -1,132 +0,0 @@
-// Copyright 2016 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/task_scheduler/post_task.h"
-
-#include <utility>
-
-#include "base/logging.h"
-#include "base/task_scheduler/scoped_set_task_priority_for_current_thread.h"
-#include "base/task_scheduler/task_scheduler.h"
-#include "base/threading/post_task_and_reply_impl.h"
-
-namespace base {
-
-namespace {
-
-class PostTaskAndReplyWithTraitsTaskRunner
-    : public internal::PostTaskAndReplyImpl {
- public:
-  explicit PostTaskAndReplyWithTraitsTaskRunner(const TaskTraits& traits)
-      : traits_(traits) {}
-
- private:
-  bool PostTask(const Location& from_here, OnceClosure task) override {
-    PostTaskWithTraits(from_here, traits_, std::move(task));
-    return true;
-  }
-
-  const TaskTraits traits_;
-};
-
-// Returns TaskTraits based on |traits|. If TaskPriority hasn't been set
-// explicitly in |traits|, the returned TaskTraits have the current
-// TaskPriority.
-TaskTraits GetTaskTraitsWithExplicitPriority(const TaskTraits& traits) {
-  if (traits.priority_set_explicitly())
-    return traits;
-  return TaskTraits::Override(traits,
-                              {internal::GetTaskPriorityForCurrentThread()});
-}
-
-}  // namespace
-
-void PostTask(const Location& from_here, OnceClosure task) {
-  PostDelayedTask(from_here, std::move(task), TimeDelta());
-}
-
-void PostDelayedTask(const Location& from_here,
-                     OnceClosure task,
-                     TimeDelta delay) {
-  PostDelayedTaskWithTraits(from_here, TaskTraits(), std::move(task), delay);
-}
-
-void PostTaskAndReply(const Location& from_here,
-                      OnceClosure task,
-                      OnceClosure reply) {
-  PostTaskWithTraitsAndReply(from_here, TaskTraits(), std::move(task),
-                             std::move(reply));
-}
-
-void PostTaskWithTraits(const Location& from_here,
-                        const TaskTraits& traits,
-                        OnceClosure task) {
-  PostDelayedTaskWithTraits(from_here, traits, std::move(task), TimeDelta());
-}
-
-void PostDelayedTaskWithTraits(const Location& from_here,
-                               const TaskTraits& traits,
-                               OnceClosure task,
-                               TimeDelta delay) {
-  DCHECK(TaskScheduler::GetInstance())
-      << "Ref. Prerequisite section of post_task.h.\n\n"
-         "Hint: if this is in a unit test, you're likely merely missing a "
-         "base::test::ScopedTaskEnvironment member in your fixture.\n";
-  TaskScheduler::GetInstance()->PostDelayedTaskWithTraits(
-      from_here, GetTaskTraitsWithExplicitPriority(traits), std::move(task),
-      std::move(delay));
-}
-
-void PostTaskWithTraitsAndReply(const Location& from_here,
-                                const TaskTraits& traits,
-                                OnceClosure task,
-                                OnceClosure reply) {
-  PostTaskAndReplyWithTraitsTaskRunner(traits).PostTaskAndReply(
-      from_here, std::move(task), std::move(reply));
-}
-
-scoped_refptr<TaskRunner> CreateTaskRunnerWithTraits(const TaskTraits& traits) {
-  DCHECK(TaskScheduler::GetInstance())
-      << "Ref. Prerequisite section of post_task.h.\n\n"
-         "Hint: if this is in a unit test, you're likely merely missing a "
-         "base::test::ScopedTaskEnvironment member in your fixture.\n";
-  return TaskScheduler::GetInstance()->CreateTaskRunnerWithTraits(
-      GetTaskTraitsWithExplicitPriority(traits));
-}
-
-scoped_refptr<SequencedTaskRunner> CreateSequencedTaskRunnerWithTraits(
-    const TaskTraits& traits) {
-  DCHECK(TaskScheduler::GetInstance())
-      << "Ref. Prerequisite section of post_task.h.\n\n"
-         "Hint: if this is in a unit test, you're likely merely missing a "
-         "base::test::ScopedTaskEnvironment member in your fixture.\n";
-  return TaskScheduler::GetInstance()->CreateSequencedTaskRunnerWithTraits(
-      GetTaskTraitsWithExplicitPriority(traits));
-}
-
-scoped_refptr<SingleThreadTaskRunner> CreateSingleThreadTaskRunnerWithTraits(
-    const TaskTraits& traits,
-    SingleThreadTaskRunnerThreadMode thread_mode) {
-  DCHECK(TaskScheduler::GetInstance())
-      << "Ref. Prerequisite section of post_task.h.\n\n"
-         "Hint: if this is in a unit test, you're likely merely missing a "
-         "base::test::ScopedTaskEnvironment member in your fixture.\n";
-  return TaskScheduler::GetInstance()->CreateSingleThreadTaskRunnerWithTraits(
-      GetTaskTraitsWithExplicitPriority(traits), thread_mode);
-}
-
-#if defined(OS_WIN)
-scoped_refptr<SingleThreadTaskRunner> CreateCOMSTATaskRunnerWithTraits(
-    const TaskTraits& traits,
-    SingleThreadTaskRunnerThreadMode thread_mode) {
-  DCHECK(TaskScheduler::GetInstance())
-      << "Ref. Prerequisite section of post_task.h.\n\n"
-         "Hint: if this is in a unit test, you're likely merely missing a "
-         "base::test::ScopedTaskEnvironment member in your fixture.\n";
-  return TaskScheduler::GetInstance()->CreateCOMSTATaskRunnerWithTraits(
-      GetTaskTraitsWithExplicitPriority(traits), thread_mode);
-}
-#endif  // defined(OS_WIN)
-
-}  // namespace base
diff --git a/base/task_scheduler/post_task.h b/base/task_scheduler/post_task.h
deleted file mode 100644
index 042c1a0..0000000
--- a/base/task_scheduler/post_task.h
+++ /dev/null
@@ -1,225 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_POST_TASK_H_
-#define BASE_TASK_SCHEDULER_POST_TASK_H_
-
-#include <utility>
-
-#include "base/base_export.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/location.h"
-#include "base/memory/ref_counted.h"
-#include "base/post_task_and_reply_with_result_internal.h"
-#include "base/sequenced_task_runner.h"
-#include "base/single_thread_task_runner.h"
-#include "base/task_runner.h"
-#include "base/task_scheduler/single_thread_task_runner_thread_mode.h"
-#include "base/task_scheduler/task_traits.h"
-#include "base/time/time.h"
-#include "build_config.h"
-
-namespace base {
-
-// This is the preferred interface to post tasks to the TaskScheduler.
-//
-// To post a simple one-off task with default traits:
-//     PostTask(FROM_HERE, Bind(...));
-//
-// To post a high priority one-off task to respond to a user interaction:
-//     PostTaskWithTraits(
-//         FROM_HERE,
-//         {TaskPriority::USER_BLOCKING},
-//         Bind(...));
-//
-// To post tasks that must run in sequence with default traits:
-//     scoped_refptr<SequencedTaskRunner> task_runner =
-//         CreateSequencedTaskRunnerWithTraits(TaskTraits());
-//     task_runner.PostTask(FROM_HERE, Bind(...));
-//     task_runner.PostTask(FROM_HERE, Bind(...));
-//
-// To post tasks that may block, must run in sequence and can be skipped on
-// shutdown:
-//     scoped_refptr<SequencedTaskRunner> task_runner =
-//         CreateSequencedTaskRunnerWithTraits(
-//             {MayBlock(), TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
-//     task_runner.PostTask(FROM_HERE, Bind(...));
-//     task_runner.PostTask(FROM_HERE, Bind(...));
-//
-// The default traits apply to tasks that:
-//     (1) don't block (ref. MayBlock() and WithBaseSyncPrimitives()),
-//     (2) prefer inheriting the current priority to specifying their own, and
-//     (3) can either block shutdown or be skipped on shutdown
-//         (TaskScheduler implementation is free to choose a fitting default).
-// Explicit traits must be specified for tasks for which these loose
-// requirements are not sufficient.
-//
-// Tasks posted through functions below will run on threads owned by the
-// registered TaskScheduler (i.e. not on the main thread). Tasks posted through
-// functions below with a delay may be coalesced (i.e. delays may be adjusted to
-// reduce the number of wakeups and hence power consumption).
-//
-// Prerequisite: A TaskScheduler must have been registered for the current
-// process via TaskScheduler::SetInstance() before the functions below are
-// valid. This is typically done during the initialization phase in each
-// process. If your code is not running in that phase, you most likely don't
-// have to worry about this. You will encounter DCHECKs or nullptr dereferences
-// if this is violated. For tests, prefer base::test::ScopedTaskEnvironment.
-
-// Posts |task| to the TaskScheduler. Calling this is equivalent to calling
-// PostTaskWithTraits with plain TaskTraits.
-BASE_EXPORT void PostTask(const Location& from_here, OnceClosure task);
-
-// Posts |task| to the TaskScheduler. |task| will not run before |delay|
-// expires. Calling this is equivalent to calling PostDelayedTaskWithTraits with
-// plain TaskTraits.
-//
-// Use PostDelayedTaskWithTraits to specify a BACKGROUND priority if the task
-// doesn't have to run as soon as |delay| expires.
-BASE_EXPORT void PostDelayedTask(const Location& from_here,
-                                 OnceClosure task,
-                                 TimeDelta delay);
-
-// Posts |task| to the TaskScheduler and posts |reply| on the caller's execution
-// context (i.e. same sequence or thread and same TaskTraits if applicable) when
-// |task| completes. Calling this is equivalent to calling
-// PostTaskWithTraitsAndReply with plain TaskTraits. Can only be called when
-// SequencedTaskRunnerHandle::IsSet().
-BASE_EXPORT void PostTaskAndReply(const Location& from_here,
-                                  OnceClosure task,
-                                  OnceClosure reply);
-
-// Posts |task| to the TaskScheduler and posts |reply| with the return value of
-// |task| as argument on the caller's execution context (i.e. same sequence or
-// thread and same TaskTraits if applicable) when |task| completes. Calling this
-// is equivalent to calling PostTaskWithTraitsAndReplyWithResult with plain
-// TaskTraits. Can only be called when SequencedTaskRunnerHandle::IsSet().
-template <typename TaskReturnType, typename ReplyArgType>
-void PostTaskAndReplyWithResult(const Location& from_here,
-                                OnceCallback<TaskReturnType()> task,
-                                OnceCallback<void(ReplyArgType)> reply) {
-  PostTaskWithTraitsAndReplyWithResult(from_here, TaskTraits(), std::move(task),
-                                       std::move(reply));
-}
-
-// Callback version of PostTaskAndReplyWithResult above.
-// Though RepeatingCallback is convertible to OnceCallback, we need this since
-// we can not use template deduction and object conversion at once on the
-// overload resolution.
-// TODO(tzik): Update all callers of the Callback version to use OnceCallback.
-template <typename TaskReturnType, typename ReplyArgType>
-void PostTaskAndReplyWithResult(const Location& from_here,
-                                Callback<TaskReturnType()> task,
-                                Callback<void(ReplyArgType)> reply) {
-  PostTaskAndReplyWithResult(
-      from_here, OnceCallback<TaskReturnType()>(std::move(task)),
-      OnceCallback<void(ReplyArgType)>(std::move(reply)));
-}
-
-// Posts |task| with specific |traits| to the TaskScheduler.
-BASE_EXPORT void PostTaskWithTraits(const Location& from_here,
-                                    const TaskTraits& traits,
-                                    OnceClosure task);
-
-// Posts |task| with specific |traits| to the TaskScheduler. |task| will not run
-// before |delay| expires.
-//
-// Specify a BACKGROUND priority via |traits| if the task doesn't have to run as
-// soon as |delay| expires.
-BASE_EXPORT void PostDelayedTaskWithTraits(const Location& from_here,
-                                           const TaskTraits& traits,
-                                           OnceClosure task,
-                                           TimeDelta delay);
-
-// Posts |task| with specific |traits| to the TaskScheduler and posts |reply| on
-// the caller's execution context (i.e. same sequence or thread and same
-// TaskTraits if applicable) when |task| completes. Can only be called when
-// SequencedTaskRunnerHandle::IsSet().
-BASE_EXPORT void PostTaskWithTraitsAndReply(const Location& from_here,
-                                            const TaskTraits& traits,
-                                            OnceClosure task,
-                                            OnceClosure reply);
-
-// Posts |task| with specific |traits| to the TaskScheduler and posts |reply|
-// with the return value of |task| as argument on the caller's execution context
-// (i.e. same sequence or thread and same TaskTraits if applicable) when |task|
-// completes. Can only be called when SequencedTaskRunnerHandle::IsSet().
-template <typename TaskReturnType, typename ReplyArgType>
-void PostTaskWithTraitsAndReplyWithResult(
-    const Location& from_here,
-    const TaskTraits& traits,
-    OnceCallback<TaskReturnType()> task,
-    OnceCallback<void(ReplyArgType)> reply) {
-  TaskReturnType* result = new TaskReturnType();
-  return PostTaskWithTraitsAndReply(
-      from_here, traits,
-      BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>, std::move(task),
-               result),
-      BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>,
-               std::move(reply), Owned(result)));
-}
-
-// Callback version of PostTaskWithTraitsAndReplyWithResult above.
-// Though RepeatingCallback is convertible to OnceCallback, we need this since
-// we can not use template deduction and object conversion at once on the
-// overload resolution.
-// TODO(tzik): Update all callers of the Callback version to use OnceCallback.
-template <typename TaskReturnType, typename ReplyArgType>
-void PostTaskWithTraitsAndReplyWithResult(const Location& from_here,
-                                          const TaskTraits& traits,
-                                          Callback<TaskReturnType()> task,
-                                          Callback<void(ReplyArgType)> reply) {
-  PostTaskWithTraitsAndReplyWithResult(
-      from_here, traits, OnceCallback<TaskReturnType()>(std::move(task)),
-      OnceCallback<void(ReplyArgType)>(std::move(reply)));
-}
-
-// Returns a TaskRunner whose PostTask invocations result in scheduling tasks
-// using |traits|. Tasks may run in any order and in parallel.
-BASE_EXPORT scoped_refptr<TaskRunner> CreateTaskRunnerWithTraits(
-    const TaskTraits& traits);
-
-// Returns a SequencedTaskRunner whose PostTask invocations result in scheduling
-// tasks using |traits|. Tasks run one at a time in posting order.
-BASE_EXPORT scoped_refptr<SequencedTaskRunner>
-CreateSequencedTaskRunnerWithTraits(const TaskTraits& traits);
-
-// Returns a SingleThreadTaskRunner whose PostTask invocations result in
-// scheduling tasks using |traits| on a thread determined by |thread_mode|. See
-// base/task_scheduler/single_thread_task_runner_thread_mode.h for |thread_mode|
-// details. Tasks run on a single thread in posting order.
-//
-// If all you need is to make sure that tasks don't run concurrently (e.g.
-// because they access a data structure which is not thread-safe), use
-// CreateSequencedTaskRunnerWithTraits(). Only use this if you rely on a thread-
-// affine API (it might be safer to assume thread-affinity when dealing with
-// under-documented third-party APIs, e.g. other OS') or share data across tasks
-// using thread-local storage.
-BASE_EXPORT scoped_refptr<SingleThreadTaskRunner>
-CreateSingleThreadTaskRunnerWithTraits(
-    const TaskTraits& traits,
-    SingleThreadTaskRunnerThreadMode thread_mode =
-        SingleThreadTaskRunnerThreadMode::SHARED);
-
-#if defined(OS_WIN)
-// Returns a SingleThreadTaskRunner whose PostTask invocations result in
-// scheduling tasks using |traits| in a COM Single-Threaded Apartment on a
-// thread determined by |thread_mode|. See
-// base/task_scheduler/single_thread_task_runner_thread_mode.h for |thread_mode|
-// details. Tasks run in the same Single-Threaded Apartment in posting order for
-// the returned SingleThreadTaskRunner. There is not necessarily a one-to-one
-// correspondence between SingleThreadTaskRunners and Single-Threaded
-// Apartments. The implementation is free to share apartments or create new
-// apartments as necessary. In either case, care should be taken to make sure
-// COM pointers are not smuggled across apartments.
-BASE_EXPORT scoped_refptr<SingleThreadTaskRunner>
-CreateCOMSTATaskRunnerWithTraits(const TaskTraits& traits,
-                                 SingleThreadTaskRunnerThreadMode thread_mode =
-                                     SingleThreadTaskRunnerThreadMode::SHARED);
-#endif  // defined(OS_WIN)
-
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_POST_TASK_H_
diff --git a/base/task_scheduler/priority_queue.cc b/base/task_scheduler/priority_queue.cc
deleted file mode 100644
index 59e9d3f..0000000
--- a/base/task_scheduler/priority_queue.cc
+++ /dev/null
@@ -1,109 +0,0 @@
-// Copyright 2016 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/task_scheduler/priority_queue.h"
-
-#include <utility>
-
-#include "base/logging.h"
-#include "base/memory/ptr_util.h"
-
-namespace base {
-namespace internal {
-
-// A class combining a Sequence and the SequenceSortKey that determines its
-// position in a PriorityQueue. Instances are only mutable via take_sequence()
-// which can only be called once and renders its instance invalid after the
-// call.
-class PriorityQueue::SequenceAndSortKey {
- public:
-  SequenceAndSortKey(scoped_refptr<Sequence> sequence,
-                     const SequenceSortKey& sort_key)
-      : sequence_(std::move(sequence)), sort_key_(sort_key) {
-    DCHECK(sequence_);
-  }
-
-  // Note: while |sequence_| should always be non-null post-move (i.e. we
-  // shouldn't be moving an invalid SequenceAndSortKey around), there can't be a
-  // DCHECK(sequence_) on moves as the Windows STL moves elements on pop instead
-  // of overwriting them: resulting in the move of a SequenceAndSortKey with a
-  // null |sequence_| in Transaction::Pop()'s implementation.
-  SequenceAndSortKey(SequenceAndSortKey&& other) = default;
-  SequenceAndSortKey& operator=(SequenceAndSortKey&& other) = default;
-
-  // Extracts |sequence_| from this object. This object is invalid after this
-  // call.
-  scoped_refptr<Sequence> take_sequence() {
-    DCHECK(sequence_);
-    return std::move(sequence_);
-  }
-
-  // Compares this SequenceAndSortKey to |other| based on their respective
-  // |sort_key_|.
-  bool operator<(const SequenceAndSortKey& other) const {
-    return sort_key_ < other.sort_key_;
-  }
-  bool operator>(const SequenceAndSortKey& other) const {
-    return other < *this;
-  }
-
-  const SequenceSortKey& sort_key() const { return sort_key_; }
-
- private:
-  scoped_refptr<Sequence> sequence_;
-  SequenceSortKey sort_key_;
-
-  DISALLOW_COPY_AND_ASSIGN(SequenceAndSortKey);
-};
-
-PriorityQueue::Transaction::Transaction(PriorityQueue* outer_queue)
-    : auto_lock_(outer_queue->container_lock_), outer_queue_(outer_queue) {
-}
-
-PriorityQueue::Transaction::~Transaction() = default;
-
-void PriorityQueue::Transaction::Push(
-    scoped_refptr<Sequence> sequence,
-    const SequenceSortKey& sequence_sort_key) {
-  outer_queue_->container_.emplace(std::move(sequence), sequence_sort_key);
-}
-
-const SequenceSortKey& PriorityQueue::Transaction::PeekSortKey() const {
-  DCHECK(!IsEmpty());
-  return outer_queue_->container_.top().sort_key();
-}
-
-scoped_refptr<Sequence> PriorityQueue::Transaction::PopSequence() {
-  DCHECK(!IsEmpty());
-
-  // The const_cast on top() is okay since the SequenceAndSortKey is
-  // transactionally being popped from |container_| right after and taking its
-  // Sequence does not alter its sort order (a requirement for the Windows STL's
-  // consistency debug-checks for std::priority_queue::top()).
-  scoped_refptr<Sequence> sequence =
-      const_cast<PriorityQueue::SequenceAndSortKey&>(
-          outer_queue_->container_.top())
-          .take_sequence();
-  outer_queue_->container_.pop();
-  return sequence;
-}
-
-bool PriorityQueue::Transaction::IsEmpty() const {
-  return outer_queue_->container_.empty();
-}
-
-size_t PriorityQueue::Transaction::Size() const {
-  return outer_queue_->container_.size();
-}
-
-PriorityQueue::PriorityQueue() = default;
-
-PriorityQueue::~PriorityQueue() = default;
-
-std::unique_ptr<PriorityQueue::Transaction> PriorityQueue::BeginTransaction() {
-  return WrapUnique(new Transaction(this));
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/priority_queue.h b/base/task_scheduler/priority_queue.h
deleted file mode 100644
index d882364..0000000
--- a/base/task_scheduler/priority_queue.h
+++ /dev/null
@@ -1,104 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_PRIORITY_QUEUE_H_
-#define BASE_TASK_SCHEDULER_PRIORITY_QUEUE_H_
-
-#include <memory>
-#include <queue>
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/task_scheduler/scheduler_lock.h"
-#include "base/task_scheduler/sequence.h"
-#include "base/task_scheduler/sequence_sort_key.h"
-
-namespace base {
-namespace internal {
-
-// A PriorityQueue holds Sequences of Tasks. This class is thread-safe.
-class BASE_EXPORT PriorityQueue {
- public:
-  // A Transaction can perform multiple operations atomically on a
-  // PriorityQueue. While a Transaction is alive, it is guaranteed that nothing
-  // else will access the PriorityQueue.
-  //
-  // A Worker needs to be able to Peek sequences from both its PriorityQueues
-  // (single-threaded and shared) and then Pop the sequence with the highest
-  // priority. If the Peek and the Pop are done through the same Transaction, it
-  // is guaranteed that the PriorityQueue hasn't changed between the 2
-  // operations.
-  class BASE_EXPORT Transaction {
-   public:
-    ~Transaction();
-
-    // Inserts |sequence| in the PriorityQueue with |sequence_sort_key|.
-    // Note: |sequence_sort_key| is required as a parameter instead of being
-    // extracted from |sequence| in Push() to avoid this Transaction having a
-    // lock interdependency with |sequence|.
-    void Push(scoped_refptr<Sequence> sequence,
-              const SequenceSortKey& sequence_sort_key);
-
-    // Returns a reference to the SequenceSortKey representing the priority of
-    // the highest pending task in this PriorityQueue. The reference becomes
-    // invalid the next time that this PriorityQueue is modified.
-    // Cannot be called on an empty PriorityQueue.
-    const SequenceSortKey& PeekSortKey() const;
-
-    // Removes and returns the highest priority Sequence in this PriorityQueue.
-    // Cannot be called on an empty PriorityQueue.
-    scoped_refptr<Sequence> PopSequence();
-
-    // Returns true if the PriorityQueue is empty.
-    bool IsEmpty() const;
-
-    // Returns the number of Sequences in the PriorityQueue.
-    size_t Size() const;
-
-   private:
-    friend class PriorityQueue;
-
-    explicit Transaction(PriorityQueue* outer_queue);
-
-    // Holds the lock of |outer_queue_| for the lifetime of this Transaction.
-    AutoSchedulerLock auto_lock_;
-
-    PriorityQueue* const outer_queue_;
-
-    DISALLOW_COPY_AND_ASSIGN(Transaction);
-  };
-
-  PriorityQueue();
-
-  ~PriorityQueue();
-
-  // Begins a Transaction. This method cannot be called on a thread which has an
-  // active Transaction unless the last Transaction created on the thread was
-  // for the allowed predecessor specified in the constructor of this
-  // PriorityQueue.
-  std::unique_ptr<Transaction> BeginTransaction();
-
-  const SchedulerLock* container_lock() const { return &container_lock_; }
-
- private:
-  // A class combining a Sequence and the SequenceSortKey that determines its
-  // position in a PriorityQueue.
-  class SequenceAndSortKey;
-
-  using ContainerType = std::priority_queue<SequenceAndSortKey>;
-
-  // Synchronizes access to |container_|.
-  SchedulerLock container_lock_;
-
-  ContainerType container_;
-
-  DISALLOW_COPY_AND_ASSIGN(PriorityQueue);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_PRIORITY_QUEUE_H_
diff --git a/base/task_scheduler/scheduler_lock.h b/base/task_scheduler/scheduler_lock.h
deleted file mode 100644
index c969eb1..0000000
--- a/base/task_scheduler/scheduler_lock.h
+++ /dev/null
@@ -1,88 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_SCHEDULER_LOCK_H
-#define BASE_TASK_SCHEDULER_SCHEDULER_LOCK_H
-
-#include <memory>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/synchronization/condition_variable.h"
-#include "base/synchronization/lock.h"
-#include "base/task_scheduler/scheduler_lock_impl.h"
-
-namespace base {
-namespace internal {
-
-// SchedulerLock should be used anywhere a lock would be used in the scheduler.
-// When DCHECK_IS_ON(), lock checking occurs. Otherwise, SchedulerLock is
-// equivalent to base::Lock.
-//
-// The shape of SchedulerLock is as follows:
-// SchedulerLock()
-//     Default constructor, no predecessor lock.
-//     DCHECKs
-//         On Acquisition if any scheduler lock is acquired on this thread.
-//
-// SchedulerLock(const SchedulerLock* predecessor)
-//     Constructor that specifies an allowed predecessor for that lock.
-//     DCHECKs
-//         On Construction if |predecessor| forms a predecessor lock cycle.
-//         On Acquisition if the previous lock acquired on the thread is not
-//             |predecessor|. Okay if there was no previous lock acquired.
-//
-// void Acquire()
-//     Acquires the lock.
-//
-// void Release()
-//     Releases the lock.
-//
-// void AssertAcquired().
-//     DCHECKs if the lock is not acquired.
-//
-// std::unique_ptr<ConditionVariable> CreateConditionVariable()
-//     Creates a condition variable using this as a lock.
-
-#if DCHECK_IS_ON()
-class SchedulerLock : public SchedulerLockImpl {
- public:
-  SchedulerLock() = default;
-  explicit SchedulerLock(const SchedulerLock* predecessor)
-      : SchedulerLockImpl(predecessor) {}
-};
-#else  // DCHECK_IS_ON()
-class SchedulerLock : public Lock {
- public:
-  SchedulerLock() = default;
-  explicit SchedulerLock(const SchedulerLock*) {}
-
-  std::unique_ptr<ConditionVariable> CreateConditionVariable() {
-    return std::unique_ptr<ConditionVariable>(new ConditionVariable(this));
-  }
-};
-#endif  // DCHECK_IS_ON()
-
-// Provides the same functionality as base::AutoLock for SchedulerLock.
-class AutoSchedulerLock {
- public:
-  explicit AutoSchedulerLock(SchedulerLock& lock) : lock_(lock) {
-    lock_.Acquire();
-  }
-
-  ~AutoSchedulerLock() {
-    lock_.AssertAcquired();
-    lock_.Release();
-  }
-
- private:
-  SchedulerLock& lock_;
-
-  DISALLOW_COPY_AND_ASSIGN(AutoSchedulerLock);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SCHEDULER_LOCK_H
diff --git a/base/task_scheduler/scheduler_lock_impl.cc b/base/task_scheduler/scheduler_lock_impl.cc
deleted file mode 100644
index d60f259..0000000
--- a/base/task_scheduler/scheduler_lock_impl.cc
+++ /dev/null
@@ -1,156 +0,0 @@
-// Copyright 2016 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/task_scheduler/scheduler_lock_impl.h"
-
-#include <algorithm>
-#include <unordered_map>
-#include <vector>
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/synchronization/condition_variable.h"
-#include "base/threading/platform_thread.h"
-#include "base/threading/thread_local_storage.h"
-
-namespace base {
-namespace internal {
-
-namespace {
-
-class SafeAcquisitionTracker {
- public:
-  SafeAcquisitionTracker() : tls_acquired_locks_(&OnTLSDestroy) {}
-
-  void RegisterLock(
-      const SchedulerLockImpl* const lock,
-      const SchedulerLockImpl* const predecessor) {
-    DCHECK_NE(lock, predecessor) << "Reentrant locks are unsupported.";
-    AutoLock auto_lock(allowed_predecessor_map_lock_);
-    allowed_predecessor_map_[lock] = predecessor;
-    AssertSafePredecessor(lock);
-  }
-
-  void UnregisterLock(const SchedulerLockImpl* const lock) {
-    AutoLock auto_lock(allowed_predecessor_map_lock_);
-    allowed_predecessor_map_.erase(lock);
-  }
-
-  void RecordAcquisition(const SchedulerLockImpl* const lock) {
-    AssertSafeAcquire(lock);
-    GetAcquiredLocksOnCurrentThread()->push_back(lock);
-  }
-
-  void RecordRelease(const SchedulerLockImpl* const lock) {
-    LockVector* acquired_locks = GetAcquiredLocksOnCurrentThread();
-    const auto iter_at_lock =
-        std::find(acquired_locks->begin(), acquired_locks->end(), lock);
-    DCHECK(iter_at_lock != acquired_locks->end());
-    acquired_locks->erase(iter_at_lock);
-  }
-
- private:
-  using LockVector = std::vector<const SchedulerLockImpl*>;
-  using PredecessorMap = std::unordered_map<
-      const SchedulerLockImpl*, const SchedulerLockImpl*>;
-
-  // This asserts that the lock is safe to acquire. This means that this should
-  // be run before actually recording the acquisition.
-  void AssertSafeAcquire(const SchedulerLockImpl* const lock) {
-    const LockVector* acquired_locks = GetAcquiredLocksOnCurrentThread();
-
-    // If the thread currently holds no locks, this is inherently safe.
-    if (acquired_locks->empty())
-      return;
-
-    // Otherwise, make sure that the previous lock acquired is an allowed
-    // predecessor.
-    AutoLock auto_lock(allowed_predecessor_map_lock_);
-    // Using at() is exception-safe here as |lock| was registered already.
-    const SchedulerLockImpl* allowed_predecessor =
-        allowed_predecessor_map_.at(lock);
-    DCHECK_EQ(acquired_locks->back(), allowed_predecessor);
-  }
-
-  // Asserts that |lock|'s registered predecessor is safe. Because
-  // SchedulerLocks are registered at construction time and any predecessor
-  // specified on a SchedulerLock must already exist, the first registered
-  // SchedulerLock in a potential chain must have a null predecessor and is thus
-  // cycle-free. Any subsequent SchedulerLock with a predecessor must come from
-  // the set of registered SchedulerLocks. Since the registered SchedulerLocks
-  // only contain cycle-free SchedulerLocks, this subsequent SchedulerLock is
-  // itself cycle-free and may be safely added to the registered SchedulerLock
-  // set.
-  void AssertSafePredecessor(const SchedulerLockImpl* lock) const {
-    allowed_predecessor_map_lock_.AssertAcquired();
-    // Using at() is exception-safe here as |lock| was registered already.
-    const SchedulerLockImpl* predecessor = allowed_predecessor_map_.at(lock);
-    if (predecessor) {
-      DCHECK(allowed_predecessor_map_.find(predecessor) !=
-             allowed_predecessor_map_.end())
-          << "SchedulerLock was registered before its predecessor. "
-          << "Potential cycle detected";
-    }
-  }
-
-  LockVector* GetAcquiredLocksOnCurrentThread() {
-    if (!tls_acquired_locks_.Get())
-      tls_acquired_locks_.Set(new LockVector);
-
-    return reinterpret_cast<LockVector*>(tls_acquired_locks_.Get());
-  }
-
-  static void OnTLSDestroy(void* value) {
-    delete reinterpret_cast<LockVector*>(value);
-  }
-
-  // Synchronizes access to |allowed_predecessor_map_|.
-  Lock allowed_predecessor_map_lock_;
-
-  // A map of allowed predecessors.
-  PredecessorMap allowed_predecessor_map_;
-
-  // A thread-local slot holding a vector of locks currently acquired on the
-  // current thread.
-  ThreadLocalStorage::Slot tls_acquired_locks_;
-
-  DISALLOW_COPY_AND_ASSIGN(SafeAcquisitionTracker);
-};
-
-LazyInstance<SafeAcquisitionTracker>::Leaky g_safe_acquisition_tracker =
-    LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace
-
-SchedulerLockImpl::SchedulerLockImpl() : SchedulerLockImpl(nullptr) {}
-
-SchedulerLockImpl::SchedulerLockImpl(const SchedulerLockImpl* predecessor) {
-  g_safe_acquisition_tracker.Get().RegisterLock(this, predecessor);
-}
-
-SchedulerLockImpl::~SchedulerLockImpl() {
-  g_safe_acquisition_tracker.Get().UnregisterLock(this);
-}
-
-void SchedulerLockImpl::Acquire() {
-  lock_.Acquire();
-  g_safe_acquisition_tracker.Get().RecordAcquisition(this);
-}
-
-void SchedulerLockImpl::Release() {
-  lock_.Release();
-  g_safe_acquisition_tracker.Get().RecordRelease(this);
-}
-
-void SchedulerLockImpl::AssertAcquired() const {
-  lock_.AssertAcquired();
-}
-
-std::unique_ptr<ConditionVariable>
-SchedulerLockImpl::CreateConditionVariable() {
-  return std::unique_ptr<ConditionVariable>(new ConditionVariable(&lock_));
-}
-
-}  // namespace internal
-}  // base
diff --git a/base/task_scheduler/scheduler_lock_impl.h b/base/task_scheduler/scheduler_lock_impl.h
deleted file mode 100644
index 65699bb..0000000
--- a/base/task_scheduler/scheduler_lock_impl.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_SCHEDULER_LOCK_IMPL_H
-#define BASE_TASK_SCHEDULER_SCHEDULER_LOCK_IMPL_H
-
-#include <memory>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/synchronization/lock.h"
-
-namespace base {
-
-class ConditionVariable;
-
-namespace internal {
-
-// A regular lock with simple deadlock correctness checking.
-// This lock tracks all of the available locks to make sure that any locks are
-// acquired in an expected order.
-// See scheduler_lock.h for details.
-class BASE_EXPORT SchedulerLockImpl {
- public:
-  SchedulerLockImpl();
-  explicit SchedulerLockImpl(const SchedulerLockImpl* predecessor);
-  ~SchedulerLockImpl();
-
-  void Acquire();
-  void Release();
-
-  void AssertAcquired() const;
-
-  std::unique_ptr<ConditionVariable> CreateConditionVariable();
-
- private:
-  Lock lock_;
-
-  DISALLOW_COPY_AND_ASSIGN(SchedulerLockImpl);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SCHEDULER_LOCK_IMPL_H
diff --git a/base/task_scheduler/scheduler_single_thread_task_runner_manager.cc b/base/task_scheduler/scheduler_single_thread_task_runner_manager.cc
deleted file mode 100644
index 5928f41..0000000
--- a/base/task_scheduler/scheduler_single_thread_task_runner_manager.cc
+++ /dev/null
@@ -1,652 +0,0 @@
-// Copyright 2017 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/task_scheduler/scheduler_single_thread_task_runner_manager.h"
-
-#include <algorithm>
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/memory/ptr_util.h"
-#include "base/single_thread_task_runner.h"
-#include "base/strings/stringprintf.h"
-#include "base/synchronization/atomic_flag.h"
-#include "base/task_scheduler/delayed_task_manager.h"
-#include "base/task_scheduler/scheduler_worker.h"
-#include "base/task_scheduler/sequence.h"
-#include "base/task_scheduler/task.h"
-#include "base/task_scheduler/task_tracker.h"
-#include "base/task_scheduler/task_traits.h"
-#include "base/threading/platform_thread.h"
-#include "base/time/time.h"
-
-#if defined(OS_WIN)
-#include <windows.h>
-
-#include "base/win/scoped_com_initializer.h"
-#endif  // defined(OS_WIN)
-
-namespace base {
-namespace internal {
-
-namespace {
-
-// Boolean indicating whether there's a SchedulerSingleThreadTaskRunnerManager
-// instance alive in this process. This variable should only be set when the
-// SchedulerSingleThreadTaskRunnerManager instance is brought up (on the main
-// thread; before any tasks are posted) and decremented when the instance is
-// brought down (i.e., only when unit tests tear down the task environment and
-// never in production). This makes the variable const while worker threads are
-// up and as such it doesn't need to be atomic. It is used to tell when a task
-// is posted from the main thread after the task environment was brought down in
-// unit tests so that SchedulerSingleThreadTaskRunnerManager bound TaskRunners
-// can return false on PostTask, letting such callers know they should complete
-// necessary work synchronously. Note: |!g_manager_is_alive| is generally
-// equivalent to |!TaskScheduler::GetInstance()| but has the advantage of being
-// valid in task_scheduler unit tests that don't instantiate a full
-// TaskScheduler.
-bool g_manager_is_alive = false;
-
-// Allows for checking the PlatformThread::CurrentRef() against a set
-// PlatformThreadRef atomically without using locks.
-class AtomicThreadRefChecker {
- public:
-  AtomicThreadRefChecker() = default;
-  ~AtomicThreadRefChecker() = default;
-
-  void Set() {
-    thread_ref_ = PlatformThread::CurrentRef();
-    is_set_.Set();
-  }
-
-  bool IsCurrentThreadSameAsSetThread() {
-    return is_set_.IsSet() && thread_ref_ == PlatformThread::CurrentRef();
-  }
-
- private:
-  AtomicFlag is_set_;
-  PlatformThreadRef thread_ref_;
-
-  DISALLOW_COPY_AND_ASSIGN(AtomicThreadRefChecker);
-};
-
-class SchedulerWorkerDelegate : public SchedulerWorker::Delegate {
- public:
-  SchedulerWorkerDelegate(const std::string& thread_name,
-                          SchedulerWorker::ThreadLabel thread_label)
-      : thread_name_(thread_name), thread_label_(thread_label) {}
-
-  void set_worker(SchedulerWorker* worker) {
-    DCHECK(!worker_);
-    worker_ = worker;
-  }
-
-  // SchedulerWorker::Delegate:
-  void OnCanScheduleSequence(scoped_refptr<Sequence> sequence) override {
-    DCHECK(worker_);
-    ReEnqueueSequence(std::move(sequence));
-    worker_->WakeUp();
-  }
-
-  SchedulerWorker::ThreadLabel GetThreadLabel() const final {
-    return thread_label_;
-  }
-
-  void OnMainEntry(const SchedulerWorker* /* worker */) override {
-    thread_ref_checker_.Set();
-    PlatformThread::SetName(thread_name_);
-  }
-
-  scoped_refptr<Sequence> GetWork(SchedulerWorker* worker) override {
-    AutoSchedulerLock auto_lock(sequence_lock_);
-    bool has_work = has_work_;
-    has_work_ = false;
-    return has_work ? sequence_ : nullptr;
-  }
-
-  void DidRunTask() override {}
-
-  void ReEnqueueSequence(scoped_refptr<Sequence> sequence) override {
-    AutoSchedulerLock auto_lock(sequence_lock_);
-    // We've shut down, so no-op this work request. Any sequence cleanup will
-    // occur in the caller's context.
-    if (!sequence_)
-      return;
-
-    DCHECK_EQ(sequence, sequence_);
-    DCHECK(!has_work_);
-    has_work_ = true;
-  }
-
-  TimeDelta GetSleepTimeout() override { return TimeDelta::Max(); }
-
-  bool RunsTasksInCurrentSequence() {
-    // We check the thread ref instead of the sequence for the benefit of COM
-    // callbacks which may execute without a sequence context.
-    return thread_ref_checker_.IsCurrentThreadSameAsSetThread();
-  }
-
-  void OnMainExit(SchedulerWorker* /* worker */) override {
-    // Move |sequence_| to |local_sequence| so that if we have the last
-    // reference to the sequence we don't destroy it (and its tasks) within
-    // |sequence_lock_|.
-    scoped_refptr<Sequence> local_sequence;
-    {
-      AutoSchedulerLock auto_lock(sequence_lock_);
-      // To reclaim skipped tasks on shutdown, we null out the sequence to allow
-      // the tasks to destroy themselves.
-      local_sequence = std::move(sequence_);
-    }
-  }
-
-  // SchedulerWorkerDelegate:
-
-  // Consumers should release their sequence reference as soon as possible to
-  // ensure timely cleanup for general shutdown.
-  scoped_refptr<Sequence> sequence() {
-    AutoSchedulerLock auto_lock(sequence_lock_);
-    return sequence_;
-  }
-
- private:
-  const std::string thread_name_;
-  const SchedulerWorker::ThreadLabel thread_label_;
-
-  // The SchedulerWorker that has |this| as a delegate. Must be set before
-  // starting or posting a task to the SchedulerWorker, because it's used in
-  // OnMainEntry() and OnCanScheduleSequence() (called when a sequence held up
-  // by WillScheduleSequence() in PostTaskNow() can be scheduled).
-  SchedulerWorker* worker_ = nullptr;
-
-  // Synchronizes access to |sequence_| and |has_work_|.
-  SchedulerLock sequence_lock_;
-  scoped_refptr<Sequence> sequence_ = new Sequence;
-  bool has_work_ = false;
-
-  AtomicThreadRefChecker thread_ref_checker_;
-
-  DISALLOW_COPY_AND_ASSIGN(SchedulerWorkerDelegate);
-};
-
-#if defined(OS_WIN)
-
-class SchedulerWorkerCOMDelegate : public SchedulerWorkerDelegate {
- public:
-  SchedulerWorkerCOMDelegate(const std::string& thread_name,
-                             SchedulerWorker::ThreadLabel thread_label,
-                             TrackedRef<TaskTracker> task_tracker)
-      : SchedulerWorkerDelegate(thread_name, thread_label),
-        task_tracker_(std::move(task_tracker)) {}
-
-  ~SchedulerWorkerCOMDelegate() override { DCHECK(!scoped_com_initializer_); }
-
-  // SchedulerWorker::Delegate:
-  void OnMainEntry(const SchedulerWorker* worker) override {
-    SchedulerWorkerDelegate::OnMainEntry(worker);
-
-    scoped_com_initializer_ = std::make_unique<win::ScopedCOMInitializer>();
-  }
-
-  scoped_refptr<Sequence> GetWork(SchedulerWorker* worker) override {
-    // This scheme below allows us to cover the following scenarios:
-    // * Only SchedulerWorkerDelegate::GetWork() has work:
-    //   Always return the sequence from GetWork().
-    // * Only the Windows Message Queue has work:
-    //   Always return the sequence from GetWorkFromWindowsMessageQueue();
-    // * Both SchedulerWorkerDelegate::GetWork() and the Windows Message Queue
-    //   have work:
-    //   Process sequences from each source round-robin style.
-    scoped_refptr<Sequence> sequence;
-    if (get_work_first_) {
-      sequence = SchedulerWorkerDelegate::GetWork(worker);
-      if (sequence)
-        get_work_first_ = false;
-    }
-
-    if (!sequence) {
-      sequence = GetWorkFromWindowsMessageQueue();
-      if (sequence)
-        get_work_first_ = true;
-    }
-
-    if (!sequence && !get_work_first_) {
-      // This case is important if we checked the Windows Message Queue first
-      // and found there was no work. We don't want to return null immediately
-      // as that could cause the thread to go to sleep while work is waiting via
-      // SchedulerWorkerDelegate::GetWork().
-      sequence = SchedulerWorkerDelegate::GetWork(worker);
-    }
-    return sequence;
-  }
-
-  void OnMainExit(SchedulerWorker* /* worker */) override {
-    scoped_com_initializer_.reset();
-  }
-
-  void WaitForWork(WaitableEvent* wake_up_event) override {
-    DCHECK(wake_up_event);
-    const TimeDelta sleep_time = GetSleepTimeout();
-    const DWORD milliseconds_wait =
-        sleep_time.is_max() ? INFINITE : sleep_time.InMilliseconds();
-    const HANDLE wake_up_event_handle = wake_up_event->handle();
-    MsgWaitForMultipleObjectsEx(1, &wake_up_event_handle, milliseconds_wait,
-                                QS_ALLINPUT, 0);
-  }
-
- private:
-  scoped_refptr<Sequence> GetWorkFromWindowsMessageQueue() {
-    MSG msg;
-    if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE) != FALSE) {
-      Task pump_message_task(FROM_HERE,
-                             Bind(
-                                 [](MSG msg) {
-                                   TranslateMessage(&msg);
-                                   DispatchMessage(&msg);
-                                 },
-                                 std::move(msg)),
-                             TaskTraits(MayBlock()), TimeDelta());
-      if (task_tracker_->WillPostTask(pump_message_task)) {
-        bool was_empty =
-            message_pump_sequence_->PushTask(std::move(pump_message_task));
-        DCHECK(was_empty) << "GetWorkFromWindowsMessageQueue() does not expect "
-                             "queueing of pump tasks.";
-        return message_pump_sequence_;
-      }
-    }
-    return nullptr;
-  }
-
-  bool get_work_first_ = true;
-  const scoped_refptr<Sequence> message_pump_sequence_ = new Sequence;
-  const TrackedRef<TaskTracker> task_tracker_;
-  std::unique_ptr<win::ScopedCOMInitializer> scoped_com_initializer_;
-
-  DISALLOW_COPY_AND_ASSIGN(SchedulerWorkerCOMDelegate);
-};
-
-#endif  // defined(OS_WIN)
-
-}  // namespace
-
-class SchedulerSingleThreadTaskRunnerManager::SchedulerSingleThreadTaskRunner
-    : public SingleThreadTaskRunner {
- public:
-  // Constructs a SchedulerSingleThreadTaskRunner that indirectly controls the
-  // lifetime of a dedicated |worker| for |traits|.
-  SchedulerSingleThreadTaskRunner(
-      SchedulerSingleThreadTaskRunnerManager* const outer,
-      const TaskTraits& traits,
-      SchedulerWorker* worker,
-      SingleThreadTaskRunnerThreadMode thread_mode)
-      : outer_(outer),
-        traits_(traits),
-        worker_(worker),
-        thread_mode_(thread_mode) {
-    DCHECK(outer_);
-    DCHECK(worker_);
-  }
-
-  // SingleThreadTaskRunner:
-  bool PostDelayedTask(const Location& from_here,
-                       OnceClosure closure,
-                       TimeDelta delay) override {
-    if (!g_manager_is_alive)
-      return false;
-
-    Task task(from_here, std::move(closure), traits_, delay);
-    task.single_thread_task_runner_ref = this;
-
-    if (!outer_->task_tracker_->WillPostTask(task))
-      return false;
-
-    if (task.delayed_run_time.is_null()) {
-      PostTaskNow(std::move(task));
-    } else {
-      outer_->delayed_task_manager_->AddDelayedTask(
-          std::move(task),
-          BindOnce(&SchedulerSingleThreadTaskRunner::PostTaskNow,
-                   Unretained(this)));
-    }
-    return true;
-  }
-
-  bool PostNonNestableDelayedTask(const Location& from_here,
-                                  OnceClosure closure,
-                                  TimeDelta delay) override {
-    // Tasks are never nested within the task scheduler.
-    return PostDelayedTask(from_here, std::move(closure), delay);
-  }
-
-  bool RunsTasksInCurrentSequence() const override {
-    if (!g_manager_is_alive)
-      return false;
-    return GetDelegate()->RunsTasksInCurrentSequence();
-  }
-
- private:
-  ~SchedulerSingleThreadTaskRunner() override {
-    // Only unregister if this is a DEDICATED SingleThreadTaskRunner. SHARED
-    // task runner SchedulerWorkers are managed separately as they are reused.
-    // |g_manager_is_alive| avoids a use-after-free should this
-    // SchedulerSingleThreadTaskRunner outlive its manager. It is safe to access
-    // |g_manager_is_alive| without synchronization primitives as it is const
-    // for the lifetime of the manager and ~SchedulerSingleThreadTaskRunner()
-    // either happens prior to the end of JoinForTesting() (which happens-before
-    // manager's destruction) or on main thread after the task environment's
-    // entire destruction (which happens-after the manager's destruction). Yes,
-    // there's a theoretical use case where the last ref to this
-    // SchedulerSingleThreadTaskRunner is handed to a thread not controlled by
-    // task_scheduler and that this ends up causing
-    // ~SchedulerSingleThreadTaskRunner() to race with
-    // ~SchedulerSingleThreadTaskRunnerManager() but this is intentionally not
-    // supported (and it doesn't matter in production where we leak the task
-    // environment for such reasons). TSan should catch this weird paradigm
-    // should anyone elect to use it in a unit test and the error would point
-    // here.
-    if (g_manager_is_alive &&
-        thread_mode_ == SingleThreadTaskRunnerThreadMode::DEDICATED) {
-      outer_->UnregisterSchedulerWorker(worker_);
-    }
-  }
-
-  void PostTaskNow(Task task) {
-    scoped_refptr<Sequence> sequence = GetDelegate()->sequence();
-    // If |sequence| is null, then the thread is effectively gone (either
-    // shutdown or joined).
-    if (!sequence)
-      return;
-
-    const bool sequence_was_empty = sequence->PushTask(std::move(task));
-    if (sequence_was_empty) {
-      sequence = outer_->task_tracker_->WillScheduleSequence(
-          std::move(sequence), GetDelegate());
-      if (sequence) {
-        GetDelegate()->ReEnqueueSequence(std::move(sequence));
-        worker_->WakeUp();
-      }
-    }
-  }
-
-  SchedulerWorkerDelegate* GetDelegate() const {
-    return static_cast<SchedulerWorkerDelegate*>(worker_->delegate());
-  }
-
-  SchedulerSingleThreadTaskRunnerManager* const outer_;
-  const TaskTraits traits_;
-  SchedulerWorker* const worker_;
-  const SingleThreadTaskRunnerThreadMode thread_mode_;
-
-  DISALLOW_COPY_AND_ASSIGN(SchedulerSingleThreadTaskRunner);
-};
-
-SchedulerSingleThreadTaskRunnerManager::SchedulerSingleThreadTaskRunnerManager(
-    TrackedRef<TaskTracker> task_tracker,
-    DelayedTaskManager* delayed_task_manager)
-    : task_tracker_(std::move(task_tracker)),
-      delayed_task_manager_(delayed_task_manager) {
-  DCHECK(task_tracker_);
-  DCHECK(delayed_task_manager_);
-#if defined(OS_WIN)
-  static_assert(arraysize(shared_com_scheduler_workers_) ==
-                    arraysize(shared_scheduler_workers_),
-                "The size of |shared_com_scheduler_workers_| must match "
-                "|shared_scheduler_workers_|");
-  static_assert(arraysize(shared_com_scheduler_workers_[0]) ==
-                    arraysize(shared_scheduler_workers_[0]),
-                "The size of |shared_com_scheduler_workers_| must match "
-                "|shared_scheduler_workers_|");
-#endif  // defined(OS_WIN)
-  DCHECK(!g_manager_is_alive);
-  g_manager_is_alive = true;
-}
-
-SchedulerSingleThreadTaskRunnerManager::
-    ~SchedulerSingleThreadTaskRunnerManager() {
-  DCHECK(g_manager_is_alive);
-  g_manager_is_alive = false;
-}
-
-void SchedulerSingleThreadTaskRunnerManager::Start(
-    SchedulerWorkerObserver* scheduler_worker_observer) {
-  DCHECK(!scheduler_worker_observer_);
-  scheduler_worker_observer_ = scheduler_worker_observer;
-
-  decltype(workers_) workers_to_start;
-  {
-    AutoSchedulerLock auto_lock(lock_);
-    started_ = true;
-    workers_to_start = workers_;
-  }
-
-  // Start workers that were created before this method was called. Other
-  // workers are started as they are created.
-  for (scoped_refptr<SchedulerWorker> worker : workers_to_start) {
-    worker->Start(scheduler_worker_observer_);
-    worker->WakeUp();
-  }
-}
-
-scoped_refptr<SingleThreadTaskRunner>
-SchedulerSingleThreadTaskRunnerManager::CreateSingleThreadTaskRunnerWithTraits(
-    const TaskTraits& traits,
-    SingleThreadTaskRunnerThreadMode thread_mode) {
-  return CreateTaskRunnerWithTraitsImpl<SchedulerWorkerDelegate>(traits,
-                                                                 thread_mode);
-}
-
-#if defined(OS_WIN)
-scoped_refptr<SingleThreadTaskRunner>
-SchedulerSingleThreadTaskRunnerManager::CreateCOMSTATaskRunnerWithTraits(
-    const TaskTraits& traits,
-    SingleThreadTaskRunnerThreadMode thread_mode) {
-  return CreateTaskRunnerWithTraitsImpl<SchedulerWorkerCOMDelegate>(
-      traits, thread_mode);
-}
-#endif  // defined(OS_WIN)
-
-// static
-SchedulerSingleThreadTaskRunnerManager::ContinueOnShutdown
-SchedulerSingleThreadTaskRunnerManager::TraitsToContinueOnShutdown(
-    const TaskTraits& traits) {
-  if (traits.shutdown_behavior() == TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN)
-    return IS_CONTINUE_ON_SHUTDOWN;
-  return IS_NOT_CONTINUE_ON_SHUTDOWN;
-}
-
-template <typename DelegateType>
-scoped_refptr<
-    SchedulerSingleThreadTaskRunnerManager::SchedulerSingleThreadTaskRunner>
-SchedulerSingleThreadTaskRunnerManager::CreateTaskRunnerWithTraitsImpl(
-    const TaskTraits& traits,
-    SingleThreadTaskRunnerThreadMode thread_mode) {
-  DCHECK(thread_mode != SingleThreadTaskRunnerThreadMode::SHARED ||
-         !traits.with_base_sync_primitives())
-      << "Using WithBaseSyncPrimitives() on a shared SingleThreadTaskRunner "
-         "may cause deadlocks. Either reevaluate your usage (e.g. use "
-         "SequencedTaskRunner) or use "
-         "SingleThreadTaskRunnerThreadMode::DEDICATED.";
-  // To simplify the code, |dedicated_worker| is a local only variable that
-  // allows the code to treat both the DEDICATED and SHARED cases similarly for
-  // SingleThreadTaskRunnerThreadMode. In DEDICATED, the scoped_refptr is backed
-  // by a local variable and in SHARED, the scoped_refptr is backed by a member
-  // variable.
-  SchedulerWorker* dedicated_worker = nullptr;
-  SchedulerWorker*& worker =
-      thread_mode == SingleThreadTaskRunnerThreadMode::DEDICATED
-          ? dedicated_worker
-          : GetSharedSchedulerWorkerForTraits<DelegateType>(traits);
-  bool new_worker = false;
-  bool started;
-  {
-    AutoSchedulerLock auto_lock(lock_);
-    if (!worker) {
-      const auto& environment_params =
-          kEnvironmentParams[GetEnvironmentIndexForTraits(traits)];
-      std::string worker_name;
-      if (thread_mode == SingleThreadTaskRunnerThreadMode::SHARED)
-        worker_name += "Shared";
-      worker_name += environment_params.name_suffix;
-      worker = CreateAndRegisterSchedulerWorker<DelegateType>(
-          worker_name, thread_mode, environment_params.priority_hint);
-      new_worker = true;
-    }
-    started = started_;
-  }
-
-  if (new_worker && started)
-    worker->Start(scheduler_worker_observer_);
-
-  return MakeRefCounted<SchedulerSingleThreadTaskRunner>(this, traits, worker,
-                                                         thread_mode);
-}
-
-void SchedulerSingleThreadTaskRunnerManager::JoinForTesting() {
-  decltype(workers_) local_workers;
-  {
-    AutoSchedulerLock auto_lock(lock_);
-    local_workers = std::move(workers_);
-  }
-
-  for (const auto& worker : local_workers)
-    worker->JoinForTesting();
-
-  {
-    AutoSchedulerLock auto_lock(lock_);
-    DCHECK(workers_.empty())
-        << "New worker(s) unexpectedly registered during join.";
-    workers_ = std::move(local_workers);
-  }
-
-  // Release shared SchedulerWorkers at the end so they get joined above. If
-  // this call happens before the joins, the SchedulerWorkers are effectively
-  // detached and may outlive the SchedulerSingleThreadTaskRunnerManager.
-  ReleaseSharedSchedulerWorkers();
-}
-
-template <>
-std::unique_ptr<SchedulerWorkerDelegate>
-SchedulerSingleThreadTaskRunnerManager::CreateSchedulerWorkerDelegate<
-    SchedulerWorkerDelegate>(const std::string& name,
-                             int id,
-                             SingleThreadTaskRunnerThreadMode thread_mode) {
-  return std::make_unique<SchedulerWorkerDelegate>(
-      StringPrintf("TaskSchedulerSingleThread%s%d", name.c_str(), id),
-      thread_mode == SingleThreadTaskRunnerThreadMode::DEDICATED
-          ? SchedulerWorker::ThreadLabel::DEDICATED
-          : SchedulerWorker::ThreadLabel::SHARED);
-}
-
-#if defined(OS_WIN)
-template <>
-std::unique_ptr<SchedulerWorkerDelegate>
-SchedulerSingleThreadTaskRunnerManager::CreateSchedulerWorkerDelegate<
-    SchedulerWorkerCOMDelegate>(const std::string& name,
-                                int id,
-                                SingleThreadTaskRunnerThreadMode thread_mode) {
-  return std::make_unique<SchedulerWorkerCOMDelegate>(
-      StringPrintf("TaskSchedulerSingleThreadCOMSTA%s%d", name.c_str(), id),
-      thread_mode == SingleThreadTaskRunnerThreadMode::DEDICATED
-          ? SchedulerWorker::ThreadLabel::DEDICATED_COM
-          : SchedulerWorker::ThreadLabel::SHARED_COM,
-      task_tracker_);
-}
-#endif  // defined(OS_WIN)
-
-template <typename DelegateType>
-SchedulerWorker*
-SchedulerSingleThreadTaskRunnerManager::CreateAndRegisterSchedulerWorker(
-    const std::string& name,
-    SingleThreadTaskRunnerThreadMode thread_mode,
-    ThreadPriority priority_hint) {
-  lock_.AssertAcquired();
-  int id = next_worker_id_++;
-  std::unique_ptr<SchedulerWorkerDelegate> delegate =
-      CreateSchedulerWorkerDelegate<DelegateType>(name, id, thread_mode);
-  SchedulerWorkerDelegate* delegate_raw = delegate.get();
-  scoped_refptr<SchedulerWorker> worker = MakeRefCounted<SchedulerWorker>(
-      priority_hint, std::move(delegate), task_tracker_);
-  delegate_raw->set_worker(worker.get());
-  workers_.emplace_back(std::move(worker));
-  return workers_.back().get();
-}
-
-template <>
-SchedulerWorker*&
-SchedulerSingleThreadTaskRunnerManager::GetSharedSchedulerWorkerForTraits<
-    SchedulerWorkerDelegate>(const TaskTraits& traits) {
-  return shared_scheduler_workers_[GetEnvironmentIndexForTraits(traits)]
-                                  [TraitsToContinueOnShutdown(traits)];
-}
-
-#if defined(OS_WIN)
-template <>
-SchedulerWorker*&
-SchedulerSingleThreadTaskRunnerManager::GetSharedSchedulerWorkerForTraits<
-    SchedulerWorkerCOMDelegate>(const TaskTraits& traits) {
-  return shared_com_scheduler_workers_[GetEnvironmentIndexForTraits(traits)]
-                                      [TraitsToContinueOnShutdown(traits)];
-}
-#endif  // defined(OS_WIN)
-
-void SchedulerSingleThreadTaskRunnerManager::UnregisterSchedulerWorker(
-    SchedulerWorker* worker) {
-  // Cleanup uses a SchedulerLock, so call Cleanup() after releasing
-  // |lock_|.
-  scoped_refptr<SchedulerWorker> worker_to_destroy;
-  {
-    AutoSchedulerLock auto_lock(lock_);
-
-    // Skip when joining (the join logic takes care of the rest).
-    if (workers_.empty())
-      return;
-
-    auto worker_iter =
-        std::find_if(workers_.begin(), workers_.end(),
-                     [worker](const scoped_refptr<SchedulerWorker>& candidate) {
-                       return candidate.get() == worker;
-                     });
-    DCHECK(worker_iter != workers_.end());
-    worker_to_destroy = std::move(*worker_iter);
-    workers_.erase(worker_iter);
-  }
-  worker_to_destroy->Cleanup();
-}
-
-void SchedulerSingleThreadTaskRunnerManager::ReleaseSharedSchedulerWorkers() {
-  decltype(shared_scheduler_workers_) local_shared_scheduler_workers;
-#if defined(OS_WIN)
-  decltype(shared_com_scheduler_workers_) local_shared_com_scheduler_workers;
-#endif
-  {
-    AutoSchedulerLock auto_lock(lock_);
-    for (size_t i = 0; i < arraysize(shared_scheduler_workers_); ++i) {
-      for (size_t j = 0; j < arraysize(shared_scheduler_workers_[i]); ++j) {
-        local_shared_scheduler_workers[i][j] = shared_scheduler_workers_[i][j];
-        shared_scheduler_workers_[i][j] = nullptr;
-#if defined(OS_WIN)
-        local_shared_com_scheduler_workers[i][j] =
-            shared_com_scheduler_workers_[i][j];
-        shared_com_scheduler_workers_[i][j] = nullptr;
-#endif
-    }
-    }
-  }
-
-  for (size_t i = 0; i < arraysize(local_shared_scheduler_workers); ++i) {
-    for (size_t j = 0; j < arraysize(local_shared_scheduler_workers[i]); ++j) {
-      if (local_shared_scheduler_workers[i][j])
-        UnregisterSchedulerWorker(local_shared_scheduler_workers[i][j]);
-#if defined(OS_WIN)
-      if (local_shared_com_scheduler_workers[i][j])
-        UnregisterSchedulerWorker(local_shared_com_scheduler_workers[i][j]);
-#endif
-  }
-  }
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/scheduler_single_thread_task_runner_manager.h b/base/task_scheduler/scheduler_single_thread_task_runner_manager.h
deleted file mode 100644
index 5c5bb6c..0000000
--- a/base/task_scheduler/scheduler_single_thread_task_runner_manager.h
+++ /dev/null
@@ -1,155 +0,0 @@
-// Copyright 2017 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_TASK_SCHEDULER_SCHEDULER_SINGLE_THREAD_TASK_RUNNER_MANAGER_H_
-#define BASE_TASK_SCHEDULER_SCHEDULER_SINGLE_THREAD_TASK_RUNNER_MANAGER_H_
-
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/task_scheduler/environment_config.h"
-#include "base/task_scheduler/scheduler_lock.h"
-#include "base/task_scheduler/single_thread_task_runner_thread_mode.h"
-#include "base/task_scheduler/tracked_ref.h"
-#include "base/threading/platform_thread.h"
-#include "build_config.h"
-
-namespace base {
-
-class TaskTraits;
-class SchedulerWorkerObserver;
-class SingleThreadTaskRunner;
-
-namespace internal {
-
-class DelayedTaskManager;
-class SchedulerWorker;
-class TaskTracker;
-
-namespace {
-
-class SchedulerWorkerDelegate;
-
-}  // namespace
-
-// Manages a pool of threads which are each associated with one or more
-// SingleThreadTaskRunners.
-//
-// SingleThreadTaskRunners using SingleThreadTaskRunnerThreadMode::SHARED are
-// backed by shared SchedulerWorkers for each COM+task environment combination.
-// These workers are lazily instantiated and then only reclaimed during
-// JoinForTesting()
-//
-// No threads are created (and hence no tasks can run) before Start() is called.
-//
-// This class is thread-safe.
-class BASE_EXPORT SchedulerSingleThreadTaskRunnerManager final {
- public:
-  SchedulerSingleThreadTaskRunnerManager(
-      TrackedRef<TaskTracker> task_tracker,
-      DelayedTaskManager* delayed_task_manager);
-  ~SchedulerSingleThreadTaskRunnerManager();
-
-  // Starts threads for existing SingleThreadTaskRunners and allows threads to
-  // be started when SingleThreadTaskRunners are created in the future. If
-  // specified, |scheduler_worker_observer| will be notified when a worker
-  // enters and exits its main function. It must not be destroyed before
-  // JoinForTesting() has returned (must never be destroyed in production).
-  void Start(SchedulerWorkerObserver* scheduler_worker_observer = nullptr);
-
-  // Creates a SingleThreadTaskRunner which runs tasks with |traits| on a thread
-  // named "TaskSchedulerSingleThread[Shared]" +
-  // kEnvironmentParams[GetEnvironmentIndexForTraits(traits)].name_suffix +
-  // index.
-  scoped_refptr<SingleThreadTaskRunner> CreateSingleThreadTaskRunnerWithTraits(
-      const TaskTraits& traits,
-      SingleThreadTaskRunnerThreadMode thread_mode);
-
-#if defined(OS_WIN)
-  // Creates a SingleThreadTaskRunner which runs tasks with |traits| on a COM
-  // STA thread named "TaskSchedulerSingleThreadCOMSTA[Shared]" +
-  // kEnvironmentParams[GetEnvironmentIndexForTraits(traits)].name_suffix +
-  // index.
-  scoped_refptr<SingleThreadTaskRunner> CreateCOMSTATaskRunnerWithTraits(
-      const TaskTraits& traits,
-      SingleThreadTaskRunnerThreadMode thread_mode);
-#endif  // defined(OS_WIN)
-
-  void JoinForTesting();
-
- private:
-  class SchedulerSingleThreadTaskRunner;
-
-  enum ContinueOnShutdown {
-    IS_CONTINUE_ON_SHUTDOWN,
-    IS_NOT_CONTINUE_ON_SHUTDOWN,
-    CONTINUE_ON_SHUTDOWN_COUNT,
-  };
-
-  static ContinueOnShutdown TraitsToContinueOnShutdown(
-      const TaskTraits& traits);
-
-  template <typename DelegateType>
-  scoped_refptr<SchedulerSingleThreadTaskRunner> CreateTaskRunnerWithTraitsImpl(
-      const TaskTraits& traits,
-      SingleThreadTaskRunnerThreadMode thread_mode);
-
-  template <typename DelegateType>
-  std::unique_ptr<SchedulerWorkerDelegate> CreateSchedulerWorkerDelegate(
-      const std::string& name,
-      int id,
-      SingleThreadTaskRunnerThreadMode thread_mode);
-
-  template <typename DelegateType>
-  SchedulerWorker* CreateAndRegisterSchedulerWorker(
-      const std::string& name,
-      SingleThreadTaskRunnerThreadMode thread_mode,
-      ThreadPriority priority_hint);
-
-  template <typename DelegateType>
-  SchedulerWorker*& GetSharedSchedulerWorkerForTraits(const TaskTraits& traits);
-
-  void UnregisterSchedulerWorker(SchedulerWorker* worker);
-
-  void ReleaseSharedSchedulerWorkers();
-
-  const TrackedRef<TaskTracker> task_tracker_;
-  DelayedTaskManager* const delayed_task_manager_;
-
-  // Optional observer notified when a worker enters and exits its main
-  // function. Set in Start() and never modified afterwards.
-  SchedulerWorkerObserver* scheduler_worker_observer_ = nullptr;
-
-  // Synchronizes access to all members below.
-  SchedulerLock lock_;
-  std::vector<scoped_refptr<SchedulerWorker>> workers_;
-  int next_worker_id_ = 0;
-
-  // Workers for SingleThreadTaskRunnerThreadMode::SHARED tasks. It is
-  // important to have separate threads for CONTINUE_ON_SHUTDOWN and non-
-  // CONTINUE_ON_SHUTDOWN to avoid being in a situation where a
-  // CONTINUE_ON_SHUTDOWN task effectively blocks shutdown by preventing a
-  // BLOCK_SHUTDOWN task to be scheduled. https://crbug.com/829786
-  SchedulerWorker* shared_scheduler_workers_[ENVIRONMENT_COUNT]
-                                            [CONTINUE_ON_SHUTDOWN_COUNT] = {};
-#if defined(OS_WIN)
-  SchedulerWorker* shared_com_scheduler_workers_[ENVIRONMENT_COUNT]
-                                                [CONTINUE_ON_SHUTDOWN_COUNT] =
-                                                    {};
-#endif  // defined(OS_WIN)
-
-  // Set to true when Start() is called.
-  bool started_ = false;
-
-  DISALLOW_COPY_AND_ASSIGN(SchedulerSingleThreadTaskRunnerManager);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SCHEDULER_SINGLE_THREAD_TASK_RUNNER_MANAGER_H_
diff --git a/base/task_scheduler/scheduler_worker.cc b/base/task_scheduler/scheduler_worker.cc
deleted file mode 100644
index 32042e4..0000000
--- a/base/task_scheduler/scheduler_worker.cc
+++ /dev/null
@@ -1,334 +0,0 @@
-// Copyright 2016 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/task_scheduler/scheduler_worker.h"
-
-#include <stddef.h>
-
-#include <utility>
-
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/task_scheduler/scheduler_worker_observer.h"
-#include "base/task_scheduler/task_tracker.h"
-
-#if defined(OS_MACOSX)
-#include "base/mac/scoped_nsautorelease_pool.h"
-#elif defined(OS_WIN)
-#include "base/win/com_init_check_hook.h"
-#include "base/win/scoped_com_initializer.h"
-#endif
-
-namespace base {
-namespace internal {
-
-void SchedulerWorker::Delegate::WaitForWork(WaitableEvent* wake_up_event) {
-  DCHECK(wake_up_event);
-  const TimeDelta sleep_time = GetSleepTimeout();
-  if (sleep_time.is_max()) {
-    // Calling TimedWait with TimeDelta::Max is not recommended per
-    // http://crbug.com/465948.
-    wake_up_event->Wait();
-  } else {
-    wake_up_event->TimedWait(sleep_time);
-  }
-}
-
-SchedulerWorker::SchedulerWorker(
-    ThreadPriority priority_hint,
-    std::unique_ptr<Delegate> delegate,
-    TrackedRef<TaskTracker> task_tracker,
-    const SchedulerLock* predecessor_lock,
-    SchedulerBackwardCompatibility backward_compatibility)
-    : thread_lock_(predecessor_lock),
-      delegate_(std::move(delegate)),
-      task_tracker_(std::move(task_tracker)),
-      priority_hint_(priority_hint),
-      current_thread_priority_(GetDesiredThreadPriority())
-#if defined(OS_WIN) && !defined(COM_INIT_CHECK_HOOK_ENABLED)
-      ,
-      backward_compatibility_(backward_compatibility)
-#endif
-{
-  DCHECK(delegate_);
-  DCHECK(task_tracker_);
-}
-
-bool SchedulerWorker::Start(
-    SchedulerWorkerObserver* scheduler_worker_observer) {
-  AutoSchedulerLock auto_lock(thread_lock_);
-  DCHECK(thread_handle_.is_null());
-
-  if (should_exit_.IsSet())
-    return true;
-
-  DCHECK(!scheduler_worker_observer_);
-  scheduler_worker_observer_ = scheduler_worker_observer;
-
-  self_ = this;
-
-  constexpr size_t kDefaultStackSize = 0;
-  PlatformThread::CreateWithPriority(kDefaultStackSize, this, &thread_handle_,
-                                     current_thread_priority_);
-
-  if (thread_handle_.is_null()) {
-    self_ = nullptr;
-    return false;
-  }
-
-  return true;
-}
-
-void SchedulerWorker::WakeUp() {
-  // Calling WakeUp() after Cleanup() or Join() is wrong because the
-  // SchedulerWorker cannot run more tasks.
-  DCHECK(!join_called_for_testing_.IsSet());
-  DCHECK(!should_exit_.IsSet());
-  wake_up_event_.Signal();
-}
-
-void SchedulerWorker::JoinForTesting() {
-  DCHECK(!join_called_for_testing_.IsSet());
-  join_called_for_testing_.Set();
-  wake_up_event_.Signal();
-
-  PlatformThreadHandle thread_handle;
-
-  {
-    AutoSchedulerLock auto_lock(thread_lock_);
-    DCHECK(!thread_handle_.is_null());
-    thread_handle = thread_handle_;
-    // Reset |thread_handle_| so it isn't joined by the destructor.
-    thread_handle_ = PlatformThreadHandle();
-  }
-
-  PlatformThread::Join(thread_handle);
-}
-
-bool SchedulerWorker::ThreadAliveForTesting() const {
-  AutoSchedulerLock auto_lock(thread_lock_);
-  return !thread_handle_.is_null();
-}
-
-SchedulerWorker::~SchedulerWorker() {
-  AutoSchedulerLock auto_lock(thread_lock_);
-
-  // If |thread_handle_| wasn't joined, detach it.
-  if (!thread_handle_.is_null()) {
-    DCHECK(!join_called_for_testing_.IsSet());
-    PlatformThread::Detach(thread_handle_);
-  }
-}
-
-void SchedulerWorker::Cleanup() {
-  DCHECK(!should_exit_.IsSet());
-  should_exit_.Set();
-  wake_up_event_.Signal();
-}
-
-bool SchedulerWorker::ShouldExit() const {
-  // The ordering of the checks is important below. This SchedulerWorker may be
-  // released and outlive |task_tracker_| in unit tests. However, when the
-  // SchedulerWorker is released, |should_exit_| will be set, so check that
-  // first.
-  return should_exit_.IsSet() || join_called_for_testing_.IsSet() ||
-         task_tracker_->IsShutdownComplete();
-}
-
-ThreadPriority SchedulerWorker::GetDesiredThreadPriority() const {
-  // All threads have a NORMAL priority when Lock doesn't handle multiple thread
-  // priorities.
-  if (!Lock::HandlesMultipleThreadPriorities())
-    return ThreadPriority::NORMAL;
-
-  // To avoid shutdown hangs, disallow a priority below NORMAL during shutdown.
-  // If thread priority cannot be increased, never allow a priority below
-  // NORMAL.
-  if (static_cast<int>(priority_hint_) <
-          static_cast<int>(ThreadPriority::NORMAL) &&
-      (task_tracker_->HasShutdownStarted() ||
-       !PlatformThread::CanIncreaseCurrentThreadPriority())) {
-    return ThreadPriority::NORMAL;
-  }
-
-  return priority_hint_;
-}
-
-void SchedulerWorker::UpdateThreadPriority(
-    ThreadPriority desired_thread_priority) {
-  if (desired_thread_priority == current_thread_priority_)
-    return;
-
-  PlatformThread::SetCurrentThreadPriority(desired_thread_priority);
-  current_thread_priority_ = desired_thread_priority;
-}
-
-void SchedulerWorker::ThreadMain() {
-  if (priority_hint_ == ThreadPriority::BACKGROUND) {
-    switch (delegate_->GetThreadLabel()) {
-      case ThreadLabel::POOLED:
-        RunBackgroundPooledWorker();
-        return;
-      case ThreadLabel::SHARED:
-        RunBackgroundSharedWorker();
-        return;
-      case ThreadLabel::DEDICATED:
-        RunBackgroundDedicatedWorker();
-        return;
-#if defined(OS_WIN)
-      case ThreadLabel::SHARED_COM:
-        RunBackgroundSharedCOMWorker();
-        return;
-      case ThreadLabel::DEDICATED_COM:
-        RunBackgroundDedicatedCOMWorker();
-        return;
-#endif  // defined(OS_WIN)
-    }
-  }
-
-  switch (delegate_->GetThreadLabel()) {
-    case ThreadLabel::POOLED:
-      RunPooledWorker();
-      return;
-    case ThreadLabel::SHARED:
-      RunSharedWorker();
-      return;
-    case ThreadLabel::DEDICATED:
-      RunDedicatedWorker();
-      return;
-#if defined(OS_WIN)
-    case ThreadLabel::SHARED_COM:
-      RunSharedCOMWorker();
-      return;
-    case ThreadLabel::DEDICATED_COM:
-      RunDedicatedCOMWorker();
-      return;
-#endif  // defined(OS_WIN)
-  }
-}
-
-NOINLINE void SchedulerWorker::RunPooledWorker() {
-  const int line_number = __LINE__;
-  RunWorker();
-}
-
-NOINLINE void SchedulerWorker::RunBackgroundPooledWorker() {
-  const int line_number = __LINE__;
-  RunWorker();
-}
-
-NOINLINE void SchedulerWorker::RunSharedWorker() {
-  const int line_number = __LINE__;
-  RunWorker();
-}
-
-NOINLINE void SchedulerWorker::RunBackgroundSharedWorker() {
-  const int line_number = __LINE__;
-  RunWorker();
-}
-
-NOINLINE void SchedulerWorker::RunDedicatedWorker() {
-  const int line_number = __LINE__;
-  RunWorker();
-}
-
-NOINLINE void SchedulerWorker::RunBackgroundDedicatedWorker() {
-  const int line_number = __LINE__;
-  RunWorker();
-}
-
-#if defined(OS_WIN)
-NOINLINE void SchedulerWorker::RunSharedCOMWorker() {
-  const int line_number = __LINE__;
-  RunWorker();
-}
-
-NOINLINE void SchedulerWorker::RunBackgroundSharedCOMWorker() {
-  const int line_number = __LINE__;
-  RunWorker();
-}
-
-NOINLINE void SchedulerWorker::RunDedicatedCOMWorker() {
-  const int line_number = __LINE__;
-  RunWorker();
-}
-
-NOINLINE void SchedulerWorker::RunBackgroundDedicatedCOMWorker() {
-  const int line_number = __LINE__;
-  RunWorker();
-}
-#endif  // defined(OS_WIN)
-
-void SchedulerWorker::RunWorker() {
-  DCHECK_EQ(self_, this);
-
-  if (scheduler_worker_observer_)
-    scheduler_worker_observer_->OnSchedulerWorkerMainEntry();
-
-  delegate_->OnMainEntry(this);
-
-  // A SchedulerWorker starts out waiting for work.
-  {
-    delegate_->WaitForWork(&wake_up_event_);
-  }
-
-// When defined(COM_INIT_CHECK_HOOK_ENABLED), ignore
-// SchedulerBackwardCompatibility::INIT_COM_STA to find incorrect uses of
-// COM that should be running in a COM STA Task Runner.
-#if defined(OS_WIN) && !defined(COM_INIT_CHECK_HOOK_ENABLED)
-  std::unique_ptr<win::ScopedCOMInitializer> com_initializer;
-  if (backward_compatibility_ == SchedulerBackwardCompatibility::INIT_COM_STA)
-    com_initializer = std::make_unique<win::ScopedCOMInitializer>();
-#endif
-
-  while (!ShouldExit()) {
-#if defined(OS_MACOSX)
-    mac::ScopedNSAutoreleasePool autorelease_pool;
-#endif
-
-    UpdateThreadPriority(GetDesiredThreadPriority());
-
-    // Get the sequence containing the next task to execute.
-    scoped_refptr<Sequence> sequence = delegate_->GetWork(this);
-    if (!sequence) {
-      // Exit immediately if GetWork() resulted in detaching this worker.
-      if (ShouldExit())
-        break;
-
-      delegate_->WaitForWork(&wake_up_event_);
-      continue;
-    }
-
-    sequence =
-        task_tracker_->RunAndPopNextTask(std::move(sequence), delegate_.get());
-
-    delegate_->DidRunTask();
-
-    // Re-enqueue |sequence| if allowed by RunNextTask().
-    if (sequence)
-      delegate_->ReEnqueueSequence(std::move(sequence));
-
-    // Calling WakeUp() guarantees that this SchedulerWorker will run Tasks from
-    // Sequences returned by the GetWork() method of |delegate_| until it
-    // returns nullptr. Resetting |wake_up_event_| here doesn't break this
-    // invariant and avoids a useless loop iteration before going to sleep if
-    // WakeUp() is called while this SchedulerWorker is awake.
-    wake_up_event_.Reset();
-  }
-
-  // Important: It is unsafe to access unowned state (e.g. |task_tracker_|)
-  // after invoking OnMainExit().
-
-  delegate_->OnMainExit(this);
-
-  if (scheduler_worker_observer_)
-    scheduler_worker_observer_->OnSchedulerWorkerMainExit();
-
-  // Release the self-reference to |this|. This can result in deleting |this|
-  // and as such no more member accesses should be made after this point.
-  self_ = nullptr;
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/scheduler_worker.h b/base/task_scheduler/scheduler_worker.h
deleted file mode 100644
index 002db45..0000000
--- a/base/task_scheduler/scheduler_worker.h
+++ /dev/null
@@ -1,250 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_SCHEDULER_WORKER_H_
-#define BASE_TASK_SCHEDULER_SCHEDULER_WORKER_H_
-
-#include <memory>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/synchronization/atomic_flag.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/task_scheduler/can_schedule_sequence_observer.h"
-#include "base/task_scheduler/scheduler_lock.h"
-#include "base/task_scheduler/scheduler_worker_params.h"
-#include "base/task_scheduler/sequence.h"
-#include "base/task_scheduler/tracked_ref.h"
-#include "base/threading/platform_thread.h"
-#include "base/time/time.h"
-#include "build_config.h"
-
-#if defined(OS_WIN)
-#include "base/win/com_init_check_hook.h"
-#endif
-
-namespace base {
-
-class SchedulerWorkerObserver;
-
-namespace internal {
-
-class TaskTracker;
-
-// A worker that manages a single thread to run Tasks from Sequences returned
-// by a delegate.
-//
-// A SchedulerWorker starts out sleeping. It is woken up by a call to WakeUp().
-// After a wake-up, a SchedulerWorker runs Tasks from Sequences returned by the
-// GetWork() method of its delegate as long as it doesn't return nullptr. It
-// also periodically checks with its TaskTracker whether shutdown has completed
-// and exits when it has.
-//
-// This class is thread-safe.
-class BASE_EXPORT SchedulerWorker
-    : public RefCountedThreadSafe<SchedulerWorker>,
-      public PlatformThread::Delegate {
- public:
-  // Labels this SchedulerWorker's association. This doesn't affect any logic
-  // but will add a stack frame labeling this thread for ease of stack trace
-  // identification.
-  enum class ThreadLabel {
-    POOLED,
-    SHARED,
-    DEDICATED,
-#if defined(OS_WIN)
-    SHARED_COM,
-    DEDICATED_COM,
-#endif  // defined(OS_WIN)
-  };
-
-  // Delegate interface for SchedulerWorker. All methods except
-  // OnCanScheduleSequence() (inherited from CanScheduleSequenceObserver) are
-  // called from the thread managed by the SchedulerWorker instance.
-  class BASE_EXPORT Delegate : public CanScheduleSequenceObserver {
-   public:
-    ~Delegate() override = default;
-
-    // Returns the ThreadLabel the Delegate wants its SchedulerWorkers' stacks
-    // to be labeled with.
-    virtual ThreadLabel GetThreadLabel() const = 0;
-
-    // Called by |worker|'s thread when it enters its main function.
-    virtual void OnMainEntry(const SchedulerWorker* worker) = 0;
-
-    // Called by |worker|'s thread to get a Sequence from which to run a Task.
-    virtual scoped_refptr<Sequence> GetWork(SchedulerWorker* worker) = 0;
-
-    // Called by the SchedulerWorker after it ran a task.
-    virtual void DidRunTask() = 0;
-
-    // Called when |sequence| isn't empty after the SchedulerWorker pops a Task
-    // from it. |sequence| is the last Sequence returned by GetWork().
-    //
-    // TODO(fdoray): Rename to RescheduleSequence() to match TaskTracker
-    // terminology.
-    virtual void ReEnqueueSequence(scoped_refptr<Sequence> sequence) = 0;
-
-    // Called to determine how long to sleep before the next call to GetWork().
-    // GetWork() may be called before this timeout expires if the worker's
-    // WakeUp() method is called.
-    virtual TimeDelta GetSleepTimeout() = 0;
-
-    // Called by the SchedulerWorker's thread to wait for work. Override this
-    // method if the thread in question needs special handling to go to sleep.
-    // |wake_up_event| is a manually resettable event and is signaled on
-    // SchedulerWorker::WakeUp()
-    virtual void WaitForWork(WaitableEvent* wake_up_event);
-
-    // Called by |worker|'s thread right before the main function exits. The
-    // Delegate is free to release any associated resources in this call. It is
-    // guaranteed that SchedulerWorker won't access the Delegate or the
-    // TaskTracker after calling OnMainExit() on the Delegate.
-    virtual void OnMainExit(SchedulerWorker* worker) {}
-  };
-
-  // Creates a SchedulerWorker that runs Tasks from Sequences returned by
-  // |delegate|. No actual thread will be created for this SchedulerWorker
-  // before Start() is called. |priority_hint| is the preferred thread priority;
-  // the actual thread priority depends on shutdown state and platform
-  // capabilities. |task_tracker| is used to handle shutdown behavior of Tasks.
-  // |predecessor_lock| is a lock that is allowed to be held when calling
-  // methods on this SchedulerWorker. |backward_compatibility| indicates
-  // whether backward compatibility is enabled. Either JoinForTesting() or
-  // Cleanup() must be called before releasing the last external reference.
-  SchedulerWorker(ThreadPriority priority_hint,
-                  std::unique_ptr<Delegate> delegate,
-                  TrackedRef<TaskTracker> task_tracker,
-                  const SchedulerLock* predecessor_lock = nullptr,
-                  SchedulerBackwardCompatibility backward_compatibility =
-                      SchedulerBackwardCompatibility::DISABLED);
-
-  // Creates a thread to back the SchedulerWorker. The thread will be in a wait
-  // state pending a WakeUp() call. No thread will be created if Cleanup() was
-  // called. If specified, |scheduler_worker_observer| will be notified when the
-  // worker enters and exits its main function. It must not be destroyed before
-  // JoinForTesting() has returned (must never be destroyed in production).
-  // Returns true on success.
-  bool Start(SchedulerWorkerObserver* scheduler_worker_observer = nullptr);
-
-  // Wakes up this SchedulerWorker if it wasn't already awake. After this is
-  // called, this SchedulerWorker will run Tasks from Sequences returned by the
-  // GetWork() method of its delegate until it returns nullptr. No-op if Start()
-  // wasn't called. DCHECKs if called after Start() has failed or after
-  // Cleanup() has been called.
-  void WakeUp();
-
-  SchedulerWorker::Delegate* delegate() { return delegate_.get(); }
-
-  // Joins this SchedulerWorker. If a Task is already running, it will be
-  // allowed to complete its execution. This can only be called once.
-  //
-  // Note: A thread that detaches before JoinForTesting() is called may still be
-  // running after JoinForTesting() returns. However, it can't run tasks after
-  // JoinForTesting() returns.
-  void JoinForTesting();
-
-  // Returns true if the worker is alive.
-  bool ThreadAliveForTesting() const;
-
-  // Makes a request to cleanup the worker. This may be called from any thread.
-  // The caller is expected to release its reference to this object after
-  // calling Cleanup(). Further method calls after Cleanup() returns are
-  // undefined.
-  //
-  // Expected Usage:
-  //   scoped_refptr<SchedulerWorker> worker_ = /* Existing Worker */
-  //   worker_->Cleanup();
-  //   worker_ = nullptr;
-  void Cleanup();
-
- private:
-  friend class RefCountedThreadSafe<SchedulerWorker>;
-  class Thread;
-
-  ~SchedulerWorker() override;
-
-  bool ShouldExit() const;
-
-  // Returns the thread priority to use based on the priority hint, current
-  // shutdown state, and platform capabilities.
-  ThreadPriority GetDesiredThreadPriority() const;
-
-  // Changes the thread priority to |desired_thread_priority|. Must be called on
-  // the thread managed by |this|.
-  void UpdateThreadPriority(ThreadPriority desired_thread_priority);
-
-  // PlatformThread::Delegate:
-  void ThreadMain() override;
-
-  // Dummy frames to act as "RunLabeledWorker()" (see RunMain() below). Their
-  // impl is aliased to prevent compiler/linker from optimizing them out.
-  void RunPooledWorker();
-  void RunBackgroundPooledWorker();
-  void RunSharedWorker();
-  void RunBackgroundSharedWorker();
-  void RunDedicatedWorker();
-  void RunBackgroundDedicatedWorker();
-#if defined(OS_WIN)
-  void RunSharedCOMWorker();
-  void RunBackgroundSharedCOMWorker();
-  void RunDedicatedCOMWorker();
-  void RunBackgroundDedicatedCOMWorker();
-#endif  // defined(OS_WIN)
-
-  // The real main, invoked through :
-  //     ThreadMain() -> RunLabeledWorker() -> RunWorker().
-  // "RunLabeledWorker()" is a dummy frame based on ThreadLabel+ThreadPriority
-  // and used to easily identify threads in stack traces.
-  void RunWorker();
-
-  // Self-reference to prevent destruction of |this| while the thread is alive.
-  // Set in Start() before creating the thread. Reset in ThreadMain() before the
-  // thread exits. No lock required because the first access occurs before the
-  // thread is created and the second access occurs on the thread.
-  scoped_refptr<SchedulerWorker> self_;
-
-  // Synchronizes access to |thread_handle_|.
-  mutable SchedulerLock thread_lock_;
-
-  // Handle for the thread managed by |this|.
-  PlatformThreadHandle thread_handle_;
-
-  // Event to wake up the thread managed by |this|.
-  WaitableEvent wake_up_event_{WaitableEvent::ResetPolicy::AUTOMATIC,
-                               WaitableEvent::InitialState::NOT_SIGNALED};
-
-  // Whether the thread should exit. Set by Cleanup().
-  AtomicFlag should_exit_;
-
-  const std::unique_ptr<Delegate> delegate_;
-  const TrackedRef<TaskTracker> task_tracker_;
-
-  // Optional observer notified when a worker enters and exits its main
-  // function. Set in Start() and never modified afterwards.
-  SchedulerWorkerObserver* scheduler_worker_observer_ = nullptr;
-
-  // Desired thread priority.
-  const ThreadPriority priority_hint_;
-
-  // Actual thread priority. Can be different than |priority_hint_| depending on
-  // system capabilities and shutdown state. No lock required because all post-
-  // construction accesses occur on the thread.
-  ThreadPriority current_thread_priority_;
-
-#if defined(OS_WIN) && !defined(COM_INIT_CHECK_HOOK_ENABLED)
-  const SchedulerBackwardCompatibility backward_compatibility_;
-#endif
-
-  // Set once JoinForTesting() has been called.
-  AtomicFlag join_called_for_testing_;
-
-  DISALLOW_COPY_AND_ASSIGN(SchedulerWorker);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SCHEDULER_WORKER_H_
diff --git a/base/task_scheduler/scheduler_worker_observer.h b/base/task_scheduler/scheduler_worker_observer.h
deleted file mode 100644
index 5e6fc8f..0000000
--- a/base/task_scheduler/scheduler_worker_observer.h
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2018 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_TASK_SCHEDULER_SCHEDULER_WORKER_OBSERVER_H_
-#define BASE_TASK_SCHEDULER_SCHEDULER_WORKER_OBSERVER_H_
-
-namespace base {
-
-// Interface to observe entry and exit of the main function of a TaskScheduler
-// worker.
-class SchedulerWorkerObserver {
- public:
-  virtual ~SchedulerWorkerObserver() = default;
-
-  // Invoked at the beginning of the main function of a TaskScheduler worker,
-  // before any task runs.
-  virtual void OnSchedulerWorkerMainEntry() = 0;
-
-  // Invoked at the end of the main function of a TaskScheduler worker, when it
-  // can no longer run tasks.
-  virtual void OnSchedulerWorkerMainExit() = 0;
-};
-
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SCHEDULER_WORKER_OBSERVER_H_
diff --git a/base/task_scheduler/scheduler_worker_params.h b/base/task_scheduler/scheduler_worker_params.h
deleted file mode 100644
index ea753ff..0000000
--- a/base/task_scheduler/scheduler_worker_params.h
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright 2017 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_TASK_SCHEDULER_SCHEDULER_WORKER_PARAMS_H_
-#define BASE_TASK_SCHEDULER_SCHEDULER_WORKER_PARAMS_H_
-
-namespace base {
-
-enum class SchedulerBackwardCompatibility {
-  // No backward compatibility.
-  DISABLED,
-
-  // On Windows, initialize COM STA to mimic SequencedWorkerPool and
-  // BrowserThreadImpl. Behaves like DISABLED on other platforms.
-  // TODO(fdoray): Get rid of this and force tasks that care about a
-  // CoInitialized environment to request one explicitly (via an upcoming
-  // execution mode).
-  INIT_COM_STA,
-};
-
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SCHEDULER_WORKER_PARAMS_H_
diff --git a/base/task_scheduler/scheduler_worker_pool.cc b/base/task_scheduler/scheduler_worker_pool.cc
deleted file mode 100644
index 1a5c35d..0000000
--- a/base/task_scheduler/scheduler_worker_pool.cc
+++ /dev/null
@@ -1,219 +0,0 @@
-// Copyright 2017 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/task_scheduler/scheduler_worker_pool.h"
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/lazy_instance.h"
-#include "base/task_scheduler/delayed_task_manager.h"
-#include "base/task_scheduler/task_tracker.h"
-#include "base/threading/thread_local.h"
-
-namespace base {
-namespace internal {
-
-namespace {
-
-// The number of SchedulerWorkerPool that are alive in this process. This
-// variable should only be incremented when the SchedulerWorkerPool instances
-// are brought up (on the main thread; before any tasks are posted) and
-// decremented when the same instances are brought down (i.e., only when unit
-// tests tear down the task environment and never in production). This makes the
-// variable const while worker threads are up and as such it doesn't need to be
-// atomic. It is used to tell when a task is posted from the main thread after
-// the task environment was brought down in unit tests so that
-// SchedulerWorkerPool bound TaskRunners can return false on PostTask, letting
-// such callers know they should complete necessary work synchronously. Note:
-// |!g_active_pools_count| is generally equivalent to
-// |!TaskScheduler::GetInstance()| but has the advantage of being valid in
-// task_scheduler unit tests that don't instantiate a full TaskScheduler.
-int g_active_pools_count = 0;
-
-// SchedulerWorkerPool that owns the current thread, if any.
-LazyInstance<ThreadLocalPointer<const SchedulerWorkerPool>>::Leaky
-    tls_current_worker_pool = LAZY_INSTANCE_INITIALIZER;
-
-const SchedulerWorkerPool* GetCurrentWorkerPool() {
-  return tls_current_worker_pool.Get().Get();
-}
-
-}  // namespace
-
-// A task runner that runs tasks in parallel.
-class SchedulerParallelTaskRunner : public TaskRunner {
- public:
-  // Constructs a SchedulerParallelTaskRunner which can be used to post tasks so
-  // long as |worker_pool| is alive.
-  // TODO(robliao): Find a concrete way to manage |worker_pool|'s memory.
-  SchedulerParallelTaskRunner(const TaskTraits& traits,
-                              SchedulerWorkerPool* worker_pool)
-      : traits_(traits), worker_pool_(worker_pool) {
-    DCHECK(worker_pool_);
-  }
-
-  // TaskRunner:
-  bool PostDelayedTask(const Location& from_here,
-                       OnceClosure closure,
-                       TimeDelta delay) override {
-    if (!g_active_pools_count)
-      return false;
-
-    // Post the task as part of a one-off single-task Sequence.
-    return worker_pool_->PostTaskWithSequence(
-        Task(from_here, std::move(closure), traits_, delay),
-        MakeRefCounted<Sequence>());
-  }
-
-  bool RunsTasksInCurrentSequence() const override {
-    return GetCurrentWorkerPool() == worker_pool_;
-  }
-
- private:
-  ~SchedulerParallelTaskRunner() override = default;
-
-  const TaskTraits traits_;
-  SchedulerWorkerPool* const worker_pool_;
-
-  DISALLOW_COPY_AND_ASSIGN(SchedulerParallelTaskRunner);
-};
-
-// A task runner that runs tasks in sequence.
-class SchedulerSequencedTaskRunner : public SequencedTaskRunner {
- public:
-  // Constructs a SchedulerSequencedTaskRunner which can be used to post tasks
-  // so long as |worker_pool| is alive.
-  // TODO(robliao): Find a concrete way to manage |worker_pool|'s memory.
-  SchedulerSequencedTaskRunner(const TaskTraits& traits,
-                               SchedulerWorkerPool* worker_pool)
-      : traits_(traits), worker_pool_(worker_pool) {
-    DCHECK(worker_pool_);
-  }
-
-  // SequencedTaskRunner:
-  bool PostDelayedTask(const Location& from_here,
-                       OnceClosure closure,
-                       TimeDelta delay) override {
-    if (!g_active_pools_count)
-      return false;
-
-    Task task(from_here, std::move(closure), traits_, delay);
-    task.sequenced_task_runner_ref = this;
-
-    // Post the task as part of |sequence_|.
-    return worker_pool_->PostTaskWithSequence(std::move(task), sequence_);
-  }
-
-  bool PostNonNestableDelayedTask(const Location& from_here,
-                                  OnceClosure closure,
-                                  base::TimeDelta delay) override {
-    // Tasks are never nested within the task scheduler.
-    return PostDelayedTask(from_here, std::move(closure), delay);
-  }
-
-  bool RunsTasksInCurrentSequence() const override {
-    return sequence_->token() == SequenceToken::GetForCurrentThread();
-  }
-
- private:
-  ~SchedulerSequencedTaskRunner() override = default;
-
-  // Sequence for all Tasks posted through this TaskRunner.
-  const scoped_refptr<Sequence> sequence_ = MakeRefCounted<Sequence>();
-
-  const TaskTraits traits_;
-  SchedulerWorkerPool* const worker_pool_;
-
-  DISALLOW_COPY_AND_ASSIGN(SchedulerSequencedTaskRunner);
-};
-
-scoped_refptr<TaskRunner> SchedulerWorkerPool::CreateTaskRunnerWithTraits(
-    const TaskTraits& traits) {
-  return MakeRefCounted<SchedulerParallelTaskRunner>(traits, this);
-}
-
-scoped_refptr<SequencedTaskRunner>
-SchedulerWorkerPool::CreateSequencedTaskRunnerWithTraits(
-    const TaskTraits& traits) {
-  return MakeRefCounted<SchedulerSequencedTaskRunner>(traits, this);
-}
-
-bool SchedulerWorkerPool::PostTaskWithSequence(
-    Task task,
-    scoped_refptr<Sequence> sequence) {
-  DCHECK(task.task);
-  DCHECK(sequence);
-
-  if (!task_tracker_->WillPostTask(task))
-    return false;
-
-  if (task.delayed_run_time.is_null()) {
-    PostTaskWithSequenceNow(std::move(task), std::move(sequence));
-  } else {
-    // Use CHECK instead of DCHECK to crash earlier. See http://crbug.com/711167
-    // for details.
-    CHECK(task.task);
-    delayed_task_manager_->AddDelayedTask(
-        std::move(task), BindOnce(
-                             [](scoped_refptr<Sequence> sequence,
-                                SchedulerWorkerPool* worker_pool, Task task) {
-                               worker_pool->PostTaskWithSequenceNow(
-                                   std::move(task), std::move(sequence));
-                             },
-                             std::move(sequence), Unretained(this)));
-  }
-
-  return true;
-}
-
-SchedulerWorkerPool::SchedulerWorkerPool(
-    TrackedRef<TaskTracker> task_tracker,
-    DelayedTaskManager* delayed_task_manager)
-    : task_tracker_(std::move(task_tracker)),
-      delayed_task_manager_(delayed_task_manager) {
-  DCHECK(task_tracker_);
-  DCHECK(delayed_task_manager_);
-  ++g_active_pools_count;
-}
-
-SchedulerWorkerPool::~SchedulerWorkerPool() {
-  --g_active_pools_count;
-  DCHECK_GE(g_active_pools_count, 0);
-}
-
-void SchedulerWorkerPool::BindToCurrentThread() {
-  DCHECK(!GetCurrentWorkerPool());
-  tls_current_worker_pool.Get().Set(this);
-}
-
-void SchedulerWorkerPool::UnbindFromCurrentThread() {
-  DCHECK(GetCurrentWorkerPool());
-  tls_current_worker_pool.Get().Set(nullptr);
-}
-
-void SchedulerWorkerPool::PostTaskWithSequenceNow(
-    Task task,
-    scoped_refptr<Sequence> sequence) {
-  DCHECK(task.task);
-  DCHECK(sequence);
-
-  // Confirm that |task| is ready to run (its delayed run time is either null or
-  // in the past).
-  DCHECK_LE(task.delayed_run_time, TimeTicks::Now());
-
-  const bool sequence_was_empty = sequence->PushTask(std::move(task));
-  if (sequence_was_empty) {
-    // Try to schedule |sequence| if it was empty before |task| was inserted
-    // into it. Otherwise, one of these must be true:
-    // - |sequence| is already scheduled, or,
-    // - The pool is running a Task from |sequence|. The pool is expected to
-    //   reschedule |sequence| once it's done running the Task.
-    sequence = task_tracker_->WillScheduleSequence(std::move(sequence), this);
-    if (sequence)
-      OnCanScheduleSequence(std::move(sequence));
-  }
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/scheduler_worker_pool.h b/base/task_scheduler/scheduler_worker_pool.h
deleted file mode 100644
index de5329e..0000000
--- a/base/task_scheduler/scheduler_worker_pool.h
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_SCHEDULER_WORKER_POOL_H_
-#define BASE_TASK_SCHEDULER_SCHEDULER_WORKER_POOL_H_
-
-#include "base/base_export.h"
-#include "base/memory/ref_counted.h"
-#include "base/sequenced_task_runner.h"
-#include "base/task_runner.h"
-#include "base/task_scheduler/can_schedule_sequence_observer.h"
-#include "base/task_scheduler/sequence.h"
-#include "base/task_scheduler/task.h"
-#include "base/task_scheduler/task_traits.h"
-#include "base/task_scheduler/tracked_ref.h"
-
-namespace base {
-namespace internal {
-
-class DelayedTaskManager;
-class TaskTracker;
-
-// Interface for a worker pool.
-class BASE_EXPORT SchedulerWorkerPool : public CanScheduleSequenceObserver {
- public:
-  ~SchedulerWorkerPool() override;
-
-  // Returns a TaskRunner whose PostTask invocations result in scheduling tasks
-  // in this SchedulerWorkerPool using |traits|. Tasks may run in any order and
-  // in parallel.
-  scoped_refptr<TaskRunner> CreateTaskRunnerWithTraits(
-      const TaskTraits& traits);
-
-  // Returns a SequencedTaskRunner whose PostTask invocations result in
-  // scheduling tasks in this SchedulerWorkerPool using |traits|. Tasks run one
-  // at a time in posting order.
-  scoped_refptr<SequencedTaskRunner> CreateSequencedTaskRunnerWithTraits(
-      const TaskTraits& traits);
-
-  // Posts |task| to be executed by this SchedulerWorkerPool as part of
-  // |sequence|. |task| won't be executed before its delayed run time, if any.
-  // Returns true if |task| is posted.
-  bool PostTaskWithSequence(Task task, scoped_refptr<Sequence> sequence);
-
-  // Registers the worker pool in TLS.
-  void BindToCurrentThread();
-
-  // Resets the worker pool in TLS.
-  void UnbindFromCurrentThread();
-
-  // Prevents new tasks from starting to run and waits for currently running
-  // tasks to complete their execution. It is guaranteed that no thread will do
-  // work on behalf of this SchedulerWorkerPool after this returns. It is
-  // invalid to post a task once this is called. TaskTracker::Flush() can be
-  // called before this to complete existing tasks, which might otherwise post a
-  // task during JoinForTesting(). This can only be called once.
-  virtual void JoinForTesting() = 0;
-
- protected:
-  SchedulerWorkerPool(TrackedRef<TaskTracker> task_tracker,
-                      DelayedTaskManager* delayed_task_manager);
-
-  // Posts |task| to be executed by this SchedulerWorkerPool as part of
-  // |sequence|. This must only be called after |task| has gone through
-  // PostTaskWithSequence() and after |task|'s delayed run time.
-  void PostTaskWithSequenceNow(Task task, scoped_refptr<Sequence> sequence);
-
-  const TrackedRef<TaskTracker> task_tracker_;
-  DelayedTaskManager* const delayed_task_manager_;
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(SchedulerWorkerPool);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SCHEDULER_WORKER_POOL_H_
diff --git a/base/task_scheduler/scheduler_worker_pool_impl.cc b/base/task_scheduler/scheduler_worker_pool_impl.cc
deleted file mode 100644
index 9e7e892..0000000
--- a/base/task_scheduler/scheduler_worker_pool_impl.cc
+++ /dev/null
@@ -1,918 +0,0 @@
-// Copyright 2016 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/task_scheduler/scheduler_worker_pool_impl.h"
-
-#include <stddef.h>
-
-#include <algorithm>
-#include <utility>
-
-#include "base/atomicops.h"
-#include "base/auto_reset.h"
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/compiler_specific.h"
-#include "base/location.h"
-#include "base/memory/ptr_util.h"
-#include "base/sequence_token.h"
-#include "base/strings/string_util.h"
-#include "base/strings/stringprintf.h"
-#include "base/task_scheduler/scheduler_worker_pool_params.h"
-#include "base/task_scheduler/task_tracker.h"
-#include "base/task_scheduler/task_traits.h"
-#include "base/threading/platform_thread.h"
-#include "base/threading/scoped_blocking_call.h"
-#include "base/threading/thread_checker.h"
-#include "base/threading/thread_restrictions.h"
-
-#if defined(OS_WIN)
-#include "base/win/scoped_com_initializer.h"
-#include "base/win/scoped_windows_thread_environment.h"
-#include "base/win/windows_version.h"
-#endif  // defined(OS_WIN)
-
-namespace base {
-namespace internal {
-
-constexpr TimeDelta SchedulerWorkerPoolImpl::kBlockedWorkersPollPeriod;
-
-namespace {
-
-constexpr size_t kMaxNumberOfWorkers = 256;
-
-// Only used in DCHECKs.
-bool ContainsWorker(const std::vector<scoped_refptr<SchedulerWorker>>& workers,
-                    const SchedulerWorker* worker) {
-  auto it = std::find_if(workers.begin(), workers.end(),
-                         [worker](const scoped_refptr<SchedulerWorker>& i) {
-                           return i.get() == worker;
-                         });
-  return it != workers.end();
-}
-
-}  // namespace
-
-class SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl
-    : public SchedulerWorker::Delegate,
-      public BlockingObserver {
- public:
-  // |outer| owns the worker for which this delegate is constructed.
-  SchedulerWorkerDelegateImpl(TrackedRef<SchedulerWorkerPoolImpl> outer);
-  ~SchedulerWorkerDelegateImpl() override;
-
-  // SchedulerWorker::Delegate:
-  void OnCanScheduleSequence(scoped_refptr<Sequence> sequence) override;
-  SchedulerWorker::ThreadLabel GetThreadLabel() const override;
-  void OnMainEntry(const SchedulerWorker* worker) override;
-  scoped_refptr<Sequence> GetWork(SchedulerWorker* worker) override;
-  void DidRunTask() override;
-  void ReEnqueueSequence(scoped_refptr<Sequence> sequence) override;
-  TimeDelta GetSleepTimeout() override;
-  void OnMainExit(SchedulerWorker* worker) override;
-
-  // Sets |is_on_idle_workers_stack_| to be true and DCHECKS that |worker|
-  // is indeed on the idle workers stack.
-  void SetIsOnIdleWorkersStackLockRequired(SchedulerWorker* worker);
-
-  // Sets |is_on_idle_workers_stack_| to be false and DCHECKS that |worker|
-  // isn't on the idle workers stack.
-  void UnSetIsOnIdleWorkersStackLockRequired(SchedulerWorker* worker);
-
-// DCHECKs that |worker| is on the idle workers stack and
-// |is_on_idle_workers_stack_| is true.
-#if DCHECK_IS_ON()
-  void AssertIsOnIdleWorkersStackLockRequired(SchedulerWorker* worker) const;
-#else
-  void AssertIsOnIdleWorkersStackLockRequired(SchedulerWorker* worker) const {}
-#endif
-
-  // BlockingObserver:
-  void BlockingStarted(BlockingType blocking_type) override;
-  void BlockingTypeUpgraded() override;
-  void BlockingEnded() override;
-
-  void MayBlockEntered();
-  void WillBlockEntered();
-
-  // Returns true iff this worker has been within a MAY_BLOCK ScopedBlockingCall
-  // for more than |outer_->MayBlockThreshold()|. The worker capacity must be
-  // incremented if this returns true.
-  bool MustIncrementWorkerCapacityLockRequired();
-
- private:
-  // Returns true if |worker| is allowed to cleanup and remove itself from the
-  // pool. Called from GetWork() when no work is available.
-  bool CanCleanupLockRequired(const SchedulerWorker* worker) const;
-
-  // Calls cleanup on |worker| and removes it from the pool. Called from
-  // GetWork() when no work is available and CanCleanupLockRequired() returns
-  // true.
-  void CleanupLockRequired(SchedulerWorker* worker);
-
-  // Called in GetWork() when a worker becomes idle.
-  void OnWorkerBecomesIdleLockRequired(SchedulerWorker* worker);
-
-  const TrackedRef<SchedulerWorkerPoolImpl> outer_;
-
-  // Time of the last detach.
-  TimeTicks last_detach_time_;
-
-  // Number of tasks executed since the last time the
-  // TaskScheduler.NumTasksBetweenWaits histogram was recorded.
-  size_t num_tasks_since_last_wait_ = 0;
-
-  // Number of tasks executed since the last time the
-  // TaskScheduler.NumTasksBeforeDetach histogram was recorded.
-  size_t num_tasks_since_last_detach_ = 0;
-
-  // Whether the worker holding this delegate is on the idle worker's stack.
-  // Access synchronized by |outer_->lock_|.
-  bool is_on_idle_workers_stack_ = true;
-
-  // Whether |outer_->worker_capacity_| was incremented due to a
-  // ScopedBlockingCall on the thread. Access synchronized by |outer_->lock_|.
-  bool incremented_worker_capacity_since_blocked_ = false;
-
-  // Time when MayBlockScopeEntered() was last called. Reset when
-  // BlockingScopeExited() is called. Access synchronized by |outer_->lock_|.
-  TimeTicks may_block_start_time_;
-
-  // Whether this worker is currently running a task (i.e. GetWork() has
-  // returned a non-empty sequence and DidRunTask() hasn't been called yet).
-  bool is_running_task_ = false;
-
-  // Verifies that specific calls are always made from the worker thread.
-  THREAD_CHECKER(worker_thread_checker_);
-
-  DISALLOW_COPY_AND_ASSIGN(SchedulerWorkerDelegateImpl);
-};
-
-SchedulerWorkerPoolImpl::SchedulerWorkerPoolImpl(
-    StringPiece histogram_label,
-    StringPiece pool_label,
-    ThreadPriority priority_hint,
-    TrackedRef<TaskTracker> task_tracker,
-    DelayedTaskManager* delayed_task_manager)
-    : SchedulerWorkerPool(std::move(task_tracker), delayed_task_manager),
-      pool_label_(pool_label.as_string()),
-      priority_hint_(priority_hint),
-      lock_(shared_priority_queue_.container_lock()),
-      idle_workers_stack_cv_for_testing_(lock_.CreateConditionVariable()),
-      tracked_ref_factory_(this) {
-  DCHECK(!histogram_label.empty());
-  DCHECK(!pool_label_.empty());
-}
-
-void SchedulerWorkerPoolImpl::Start(
-    const SchedulerWorkerPoolParams& params,
-    scoped_refptr<TaskRunner> service_thread_task_runner,
-    SchedulerWorkerObserver* scheduler_worker_observer,
-    WorkerEnvironment worker_environment) {
-  AutoSchedulerLock auto_lock(lock_);
-
-  DCHECK(workers_.empty());
-
-  worker_capacity_ = params.max_threads();
-  initial_worker_capacity_ = worker_capacity_;
-  DCHECK_LE(initial_worker_capacity_, kMaxNumberOfWorkers);
-  suggested_reclaim_time_ = params.suggested_reclaim_time();
-  backward_compatibility_ = params.backward_compatibility();
-  worker_environment_ = worker_environment;
-
-  service_thread_task_runner_ = std::move(service_thread_task_runner);
-
-  DCHECK(!scheduler_worker_observer_);
-  scheduler_worker_observer_ = scheduler_worker_observer;
-
-  // The initial number of workers is |num_wake_ups_before_start_| + 1 to try to
-  // keep one at least one standby thread at all times (capacity permitting).
-  const int num_initial_workers = std::min(num_wake_ups_before_start_ + 1,
-                                           static_cast<int>(worker_capacity_));
-  workers_.reserve(num_initial_workers);
-
-  for (int index = 0; index < num_initial_workers; ++index) {
-    SchedulerWorker* worker =
-        CreateRegisterAndStartSchedulerWorkerLockRequired();
-
-    // CHECK that the first worker can be started (assume that failure means
-    // that threads can't be created on this machine).
-    CHECK(worker || index > 0);
-
-    if (worker) {
-      SchedulerWorkerDelegateImpl* delegate =
-          static_cast<SchedulerWorkerDelegateImpl*>(worker->delegate());
-      if (index < num_wake_ups_before_start_) {
-        delegate->UnSetIsOnIdleWorkersStackLockRequired(worker);
-        worker->WakeUp();
-      } else {
-        idle_workers_stack_.Push(worker);
-        delegate->AssertIsOnIdleWorkersStackLockRequired(worker);
-      }
-    }
-  }
-}
-
-SchedulerWorkerPoolImpl::~SchedulerWorkerPoolImpl() {
-  // SchedulerWorkerPool should only ever be deleted:
-  //  1) In tests, after JoinForTesting().
-  //  2) In production, iff initialization failed.
-  // In both cases |workers_| should be empty.
-  DCHECK(workers_.empty());
-}
-
-void SchedulerWorkerPoolImpl::OnCanScheduleSequence(
-    scoped_refptr<Sequence> sequence) {
-  const auto sequence_sort_key = sequence->GetSortKey();
-  shared_priority_queue_.BeginTransaction()->Push(std::move(sequence),
-                                                  sequence_sort_key);
-
-  WakeUpOneWorker();
-}
-
-int SchedulerWorkerPoolImpl::GetMaxConcurrentNonBlockedTasksDeprecated() const {
-#if DCHECK_IS_ON()
-  AutoSchedulerLock auto_lock(lock_);
-  DCHECK_NE(initial_worker_capacity_, 0U)
-      << "GetMaxConcurrentTasksDeprecated() should only be called after the "
-      << "worker pool has started.";
-#endif
-  return initial_worker_capacity_;
-}
-
-void SchedulerWorkerPoolImpl::WaitForWorkersIdleForTesting(size_t n) {
-  AutoSchedulerLock auto_lock(lock_);
-
-  DCHECK_EQ(0U, num_workers_cleaned_up_for_testing_)
-      << "Workers detached prior to waiting for a specific number of idle "
-         "workers. Doing the wait under such conditions is flaky.";
-
-  WaitForWorkersIdleLockRequiredForTesting(n);
-}
-
-void SchedulerWorkerPoolImpl::WaitForAllWorkersIdleForTesting() {
-  AutoSchedulerLock auto_lock(lock_);
-  WaitForWorkersIdleLockRequiredForTesting(workers_.size());
-}
-
-void SchedulerWorkerPoolImpl::WaitForWorkersCleanedUpForTesting(size_t n) {
-  AutoSchedulerLock auto_lock(lock_);
-
-  DCHECK_EQ(0U, num_workers_cleaned_up_for_testing_)
-      << "Called WaitForWorkersCleanedUpForTesting() after some workers had "
-         "already cleaned up on their own.";
-
-  DCHECK(!num_workers_cleaned_up_for_testing_cv_)
-      << "Called WaitForWorkersCleanedUpForTesting() multiple times in the "
-         "same test.";
-
-  num_workers_cleaned_up_for_testing_cv_ = lock_.CreateConditionVariable();
-
-  while (num_workers_cleaned_up_for_testing_ < n)
-    num_workers_cleaned_up_for_testing_cv_->Wait();
-}
-
-void SchedulerWorkerPoolImpl::JoinForTesting() {
-#if DCHECK_IS_ON()
-  join_for_testing_started_.Set();
-#endif
-
-  decltype(workers_) workers_copy;
-  {
-    AutoSchedulerLock auto_lock(lock_);
-
-    DCHECK_GT(workers_.size(), size_t(0)) << "Joined an unstarted worker pool.";
-
-    // Ensure SchedulerWorkers in |workers_| do not attempt to cleanup while
-    // being joined.
-    worker_cleanup_disallowed_for_testing_ = true;
-
-    // Make a copy of the SchedulerWorkers so that we can call
-    // SchedulerWorker::JoinForTesting() without holding |lock_| since
-    // SchedulerWorkers may need to access |workers_|.
-    workers_copy = workers_;
-  }
-  for (const auto& worker : workers_copy)
-    worker->JoinForTesting();
-
-  AutoSchedulerLock auto_lock(lock_);
-  DCHECK(workers_ == workers_copy);
-  // Release |workers_| to clear their TrackedRef against |this|.
-  workers_.clear();
-}
-
-size_t SchedulerWorkerPoolImpl::NumberOfWorkersForTesting() const {
-  AutoSchedulerLock auto_lock(lock_);
-  return workers_.size();
-}
-
-size_t SchedulerWorkerPoolImpl::GetWorkerCapacityForTesting() const {
-  AutoSchedulerLock auto_lock(lock_);
-  return worker_capacity_;
-}
-
-size_t SchedulerWorkerPoolImpl::NumberOfIdleWorkersForTesting() const {
-  AutoSchedulerLock auto_lock(lock_);
-  return idle_workers_stack_.Size();
-}
-
-void SchedulerWorkerPoolImpl::MaximizeMayBlockThresholdForTesting() {
-  maximum_blocked_threshold_for_testing_.Set();
-}
-
-SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::
-    SchedulerWorkerDelegateImpl(TrackedRef<SchedulerWorkerPoolImpl> outer)
-    : outer_(std::move(outer)) {
-  // Bound in OnMainEntry().
-  DETACH_FROM_THREAD(worker_thread_checker_);
-}
-
-// OnMainExit() handles the thread-affine cleanup; SchedulerWorkerDelegateImpl
-// can thereafter safely be deleted from any thread.
-SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::
-    ~SchedulerWorkerDelegateImpl() = default;
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::
-    OnCanScheduleSequence(scoped_refptr<Sequence> sequence) {
-  outer_->OnCanScheduleSequence(std::move(sequence));
-}
-
-SchedulerWorker::ThreadLabel
-SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::GetThreadLabel() const {
-  return SchedulerWorker::ThreadLabel::POOLED;
-}
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::OnMainEntry(
-    const SchedulerWorker* worker) {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-
-  {
-#if DCHECK_IS_ON()
-    AutoSchedulerLock auto_lock(outer_->lock_);
-    DCHECK(ContainsWorker(outer_->workers_, worker));
-#endif
-  }
-
-  DCHECK_EQ(num_tasks_since_last_wait_, 0U);
-
-  PlatformThread::SetName(
-      StringPrintf("TaskScheduler%sWorker", outer_->pool_label_.c_str()));
-
-  outer_->BindToCurrentThread();
-  SetBlockingObserverForCurrentThread(this);
-}
-
-scoped_refptr<Sequence>
-SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::GetWork(
-    SchedulerWorker* worker) {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-
-  DCHECK(!is_running_task_);
-  {
-    AutoSchedulerLock auto_lock(outer_->lock_);
-
-    DCHECK(ContainsWorker(outer_->workers_, worker));
-
-    // Calling GetWork() when |is_on_idle_workers_stack_| is true indicates
-    // that we must've reached GetWork() because of the WaitableEvent timing
-    // out. In which case, we return no work and possibly cleanup the worker.
-    DCHECK_EQ(is_on_idle_workers_stack_,
-              outer_->idle_workers_stack_.Contains(worker));
-    if (is_on_idle_workers_stack_) {
-      if (CanCleanupLockRequired(worker))
-        CleanupLockRequired(worker);
-      return nullptr;
-    }
-
-    // Excess workers should not get work, until they are no longer excess (i.e.
-    // worker capacity increases or another worker cleans up). This ensures that
-    // if we have excess workers in the pool, they get a chance to no longer be
-    // excess before being cleaned up.
-    if (outer_->NumberOfExcessWorkersLockRequired() >
-        outer_->idle_workers_stack_.Size()) {
-      OnWorkerBecomesIdleLockRequired(worker);
-      return nullptr;
-    }
-  }
-  scoped_refptr<Sequence> sequence;
-  {
-    std::unique_ptr<PriorityQueue::Transaction> shared_transaction(
-        outer_->shared_priority_queue_.BeginTransaction());
-
-    if (shared_transaction->IsEmpty()) {
-      // |shared_transaction| is kept alive while |worker| is added to
-      // |idle_workers_stack_| to avoid this race:
-      // 1. This thread creates a Transaction, finds |shared_priority_queue_|
-      //    empty and ends the Transaction.
-      // 2. Other thread creates a Transaction, inserts a Sequence into
-      //    |shared_priority_queue_| and ends the Transaction. This can't happen
-      //    if the Transaction of step 1 is still active because because there
-      //    can only be one active Transaction per PriorityQueue at a time.
-      // 3. Other thread calls WakeUpOneWorker(). No thread is woken up because
-      //    |idle_workers_stack_| is empty.
-      // 4. This thread adds itself to |idle_workers_stack_| and goes to sleep.
-      //    No thread runs the Sequence inserted in step 2.
-      AutoSchedulerLock auto_lock(outer_->lock_);
-
-      OnWorkerBecomesIdleLockRequired(worker);
-      return nullptr;
-    }
-    sequence = shared_transaction->PopSequence();
-  }
-  DCHECK(sequence);
-#if DCHECK_IS_ON()
-  {
-    AutoSchedulerLock auto_lock(outer_->lock_);
-    DCHECK(!outer_->idle_workers_stack_.Contains(worker));
-  }
-#endif
-
-  is_running_task_ = true;
-  return sequence;
-}
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::DidRunTask() {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-
-  DCHECK(may_block_start_time_.is_null());
-  DCHECK(!incremented_worker_capacity_since_blocked_);
-  DCHECK(is_running_task_);
-  is_running_task_ = false;
-
-  ++num_tasks_since_last_wait_;
-  ++num_tasks_since_last_detach_;
-}
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::
-    ReEnqueueSequence(scoped_refptr<Sequence> sequence) {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-
-  const SequenceSortKey sequence_sort_key = sequence->GetSortKey();
-  outer_->shared_priority_queue_.BeginTransaction()->Push(std::move(sequence),
-                                                          sequence_sort_key);
-  // This worker will soon call GetWork(). Therefore, there is no need to wake
-  // up a worker to run the sequence that was just inserted into
-  // |outer_->shared_priority_queue_|.
-}
-
-TimeDelta SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::
-    GetSleepTimeout() {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-  return outer_->suggested_reclaim_time_;
-}
-
-bool SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::
-    CanCleanupLockRequired(const SchedulerWorker* worker) const {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-
-  return worker != outer_->PeekAtIdleWorkersStackLockRequired() &&
-         LIKELY(!outer_->worker_cleanup_disallowed_for_testing_);
-}
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::CleanupLockRequired(
-    SchedulerWorker* worker) {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-
-  outer_->lock_.AssertAcquired();
-  outer_->cleanup_timestamps_.push(TimeTicks::Now());
-  worker->Cleanup();
-  outer_->RemoveFromIdleWorkersStackLockRequired(worker);
-
-  // Remove the worker from |workers_|.
-  auto worker_iter =
-      std::find(outer_->workers_.begin(), outer_->workers_.end(), worker);
-  DCHECK(worker_iter != outer_->workers_.end());
-  outer_->workers_.erase(worker_iter);
-
-  ++outer_->num_workers_cleaned_up_for_testing_;
-  if (outer_->num_workers_cleaned_up_for_testing_cv_)
-    outer_->num_workers_cleaned_up_for_testing_cv_->Signal();
-}
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::
-    OnWorkerBecomesIdleLockRequired(SchedulerWorker* worker) {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-
-  outer_->lock_.AssertAcquired();
-  // Record the TaskScheduler.NumTasksBetweenWaits histogram. After GetWork()
-  // returns nullptr, the SchedulerWorker will perform a wait on its
-  // WaitableEvent, so we record how many tasks were ran since the last wait
-  // here.
-  num_tasks_since_last_wait_ = 0;
-  outer_->AddToIdleWorkersStackLockRequired(worker);
-  SetIsOnIdleWorkersStackLockRequired(worker);
-}
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::OnMainExit(
-    SchedulerWorker* worker) {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-
-#if DCHECK_IS_ON()
-  {
-    bool shutdown_complete = outer_->task_tracker_->IsShutdownComplete();
-    AutoSchedulerLock auto_lock(outer_->lock_);
-
-    // |worker| should already have been removed from the idle workers stack and
-    // |workers_| by the time the thread is about to exit. (except in the cases
-    // where the pool is no longer going to be used - in which case, it's fine
-    // for there to be invalid workers in the pool.
-    if (!shutdown_complete && !outer_->join_for_testing_started_.IsSet()) {
-      DCHECK(!outer_->idle_workers_stack_.Contains(worker));
-      DCHECK(!ContainsWorker(outer_->workers_, worker));
-    }
-  }
-#endif
-}
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::
-    SetIsOnIdleWorkersStackLockRequired(SchedulerWorker* worker) {
-  outer_->lock_.AssertAcquired();
-  DCHECK(!is_on_idle_workers_stack_);
-  DCHECK(outer_->idle_workers_stack_.Contains(worker));
-  is_on_idle_workers_stack_ = true;
-}
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::
-    UnSetIsOnIdleWorkersStackLockRequired(SchedulerWorker* worker) {
-  outer_->lock_.AssertAcquired();
-  DCHECK(is_on_idle_workers_stack_);
-  DCHECK(!outer_->idle_workers_stack_.Contains(worker));
-  is_on_idle_workers_stack_ = false;
-}
-
-#if DCHECK_IS_ON()
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::
-    AssertIsOnIdleWorkersStackLockRequired(SchedulerWorker* worker) const {
-  outer_->lock_.AssertAcquired();
-  DCHECK(is_on_idle_workers_stack_);
-  DCHECK(outer_->idle_workers_stack_.Contains(worker));
-}
-#endif
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::BlockingStarted(
-    BlockingType blocking_type) {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-
-  // Blocking calls made outside of tasks should not influence the capacity
-  // count as no task is running.
-  if (!is_running_task_)
-    return;
-
-  switch (blocking_type) {
-    case BlockingType::MAY_BLOCK:
-      MayBlockEntered();
-      break;
-    case BlockingType::WILL_BLOCK:
-      WillBlockEntered();
-      break;
-  }
-}
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::
-    BlockingTypeUpgraded() {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-
-  {
-    AutoSchedulerLock auto_lock(outer_->lock_);
-
-    // Don't do anything if a MAY_BLOCK ScopedBlockingCall instantiated in the
-    // same scope already caused the worker capacity to be incremented.
-    if (incremented_worker_capacity_since_blocked_)
-      return;
-
-    // Cancel the effect of a MAY_BLOCK ScopedBlockingCall instantiated in the
-    // same scope.
-    if (!may_block_start_time_.is_null()) {
-      may_block_start_time_ = TimeTicks();
-      --outer_->num_pending_may_block_workers_;
-    }
-  }
-
-  WillBlockEntered();
-}
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::BlockingEnded() {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-
-  // Ignore blocking calls made outside of tasks.
-  if (!is_running_task_)
-    return;
-
-  AutoSchedulerLock auto_lock(outer_->lock_);
-  if (incremented_worker_capacity_since_blocked_) {
-    outer_->DecrementWorkerCapacityLockRequired();
-  } else {
-    DCHECK(!may_block_start_time_.is_null());
-    --outer_->num_pending_may_block_workers_;
-  }
-
-  incremented_worker_capacity_since_blocked_ = false;
-  may_block_start_time_ = TimeTicks();
-}
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::MayBlockEntered() {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-
-  {
-    AutoSchedulerLock auto_lock(outer_->lock_);
-
-    DCHECK(!incremented_worker_capacity_since_blocked_);
-    DCHECK(may_block_start_time_.is_null());
-    may_block_start_time_ = TimeTicks::Now();
-    ++outer_->num_pending_may_block_workers_;
-  }
-  outer_->PostAdjustWorkerCapacityTaskIfNeeded();
-}
-
-void SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::WillBlockEntered() {
-  DCHECK_CALLED_ON_VALID_THREAD(worker_thread_checker_);
-
-  bool wake_up_allowed = false;
-  {
-    std::unique_ptr<PriorityQueue::Transaction> shared_transaction(
-        outer_->shared_priority_queue_.BeginTransaction());
-    AutoSchedulerLock auto_lock(outer_->lock_);
-
-    DCHECK(!incremented_worker_capacity_since_blocked_);
-    DCHECK(may_block_start_time_.is_null());
-    incremented_worker_capacity_since_blocked_ = true;
-    outer_->IncrementWorkerCapacityLockRequired();
-
-    // If the number of workers was less than the old worker capacity, PostTask
-    // would've handled creating extra workers during WakeUpOneWorker.
-    // Therefore, we don't need to do anything here.
-    if (outer_->workers_.size() < outer_->worker_capacity_ - 1)
-      return;
-
-    if (shared_transaction->IsEmpty()) {
-      outer_->MaintainAtLeastOneIdleWorkerLockRequired();
-    } else {
-      // TODO(crbug.com/757897): We may create extra workers in this case:
-      // |workers.size()| was equal to the old |worker_capacity_|, we had
-      // multiple ScopedBlockingCalls in parallel and we had work on the PQ.
-      wake_up_allowed = outer_->WakeUpOneWorkerLockRequired();
-      // |wake_up_allowed| is true when the pool is started, and a WILL_BLOCK
-      // scope cannot be entered before the pool starts.
-      DCHECK(wake_up_allowed);
-    }
-  }
-  // TODO(crbug.com/813857): This can be better handled in the PostTask()
-  // codepath. We really only should do this if there are tasks pending.
-  if (wake_up_allowed)
-    outer_->PostAdjustWorkerCapacityTaskIfNeeded();
-}
-
-bool SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::
-    MustIncrementWorkerCapacityLockRequired() {
-  outer_->lock_.AssertAcquired();
-
-  if (!incremented_worker_capacity_since_blocked_ &&
-      !may_block_start_time_.is_null() &&
-      TimeTicks::Now() - may_block_start_time_ >= outer_->MayBlockThreshold()) {
-    incremented_worker_capacity_since_blocked_ = true;
-
-    // Reset |may_block_start_time_| so that BlockingScopeExited() knows that it
-    // doesn't have to decrement |outer_->num_pending_may_block_workers_|.
-    may_block_start_time_ = TimeTicks();
-    --outer_->num_pending_may_block_workers_;
-
-    return true;
-  }
-
-  return false;
-}
-
-void SchedulerWorkerPoolImpl::WaitForWorkersIdleLockRequiredForTesting(
-    size_t n) {
-  lock_.AssertAcquired();
-
-  // Make sure workers do not cleanup while watching the idle count.
-  AutoReset<bool> ban_cleanups(&worker_cleanup_disallowed_for_testing_, true);
-
-  while (idle_workers_stack_.Size() < n)
-    idle_workers_stack_cv_for_testing_->Wait();
-}
-
-bool SchedulerWorkerPoolImpl::WakeUpOneWorkerLockRequired() {
-  lock_.AssertAcquired();
-
-  if (workers_.empty()) {
-    ++num_wake_ups_before_start_;
-    return false;
-  }
-
-  // Ensure that there is one worker that can run tasks on top of the idle
-  // stack, capacity permitting.
-  MaintainAtLeastOneIdleWorkerLockRequired();
-
-  // If the worker on top of the idle stack can run tasks, wake it up.
-  if (NumberOfExcessWorkersLockRequired() < idle_workers_stack_.Size()) {
-    SchedulerWorker* worker = idle_workers_stack_.Pop();
-    if (worker) {
-      SchedulerWorkerDelegateImpl* delegate =
-          static_cast<SchedulerWorkerDelegateImpl*>(worker->delegate());
-      delegate->UnSetIsOnIdleWorkersStackLockRequired(worker);
-      worker->WakeUp();
-    }
-  }
-
-  // Ensure that there is one worker that can run tasks on top of the idle
-  // stack, capacity permitting.
-  MaintainAtLeastOneIdleWorkerLockRequired();
-
-  return true;
-}
-
-void SchedulerWorkerPoolImpl::WakeUpOneWorker() {
-  bool wake_up_allowed;
-  {
-    AutoSchedulerLock auto_lock(lock_);
-    wake_up_allowed = WakeUpOneWorkerLockRequired();
-  }
-  if (wake_up_allowed)
-    PostAdjustWorkerCapacityTaskIfNeeded();
-}
-
-void SchedulerWorkerPoolImpl::MaintainAtLeastOneIdleWorkerLockRequired() {
-  lock_.AssertAcquired();
-
-  if (workers_.size() == kMaxNumberOfWorkers)
-    return;
-  DCHECK_LT(workers_.size(), kMaxNumberOfWorkers);
-
-  if (idle_workers_stack_.IsEmpty() && workers_.size() < worker_capacity_) {
-    SchedulerWorker* new_worker =
-        CreateRegisterAndStartSchedulerWorkerLockRequired();
-    if (new_worker)
-      idle_workers_stack_.Push(new_worker);
-  }
-}
-
-void SchedulerWorkerPoolImpl::AddToIdleWorkersStackLockRequired(
-    SchedulerWorker* worker) {
-  lock_.AssertAcquired();
-
-  DCHECK(!idle_workers_stack_.Contains(worker));
-  idle_workers_stack_.Push(worker);
-
-  DCHECK_LE(idle_workers_stack_.Size(), workers_.size());
-
-  idle_workers_stack_cv_for_testing_->Broadcast();
-}
-
-const SchedulerWorker*
-SchedulerWorkerPoolImpl::PeekAtIdleWorkersStackLockRequired() const {
-  lock_.AssertAcquired();
-  return idle_workers_stack_.Peek();
-}
-
-void SchedulerWorkerPoolImpl::RemoveFromIdleWorkersStackLockRequired(
-    SchedulerWorker* worker) {
-  lock_.AssertAcquired();
-  idle_workers_stack_.Remove(worker);
-}
-
-SchedulerWorker*
-SchedulerWorkerPoolImpl::CreateRegisterAndStartSchedulerWorkerLockRequired() {
-  lock_.AssertAcquired();
-
-  DCHECK_LT(workers_.size(), worker_capacity_);
-  DCHECK_LT(workers_.size(), kMaxNumberOfWorkers);
-  // SchedulerWorker needs |lock_| as a predecessor for its thread lock
-  // because in WakeUpOneWorker, |lock_| is first acquired and then
-  // the thread lock is acquired when WakeUp is called on the worker.
-  scoped_refptr<SchedulerWorker> worker = MakeRefCounted<SchedulerWorker>(
-      priority_hint_,
-      std::make_unique<SchedulerWorkerDelegateImpl>(
-          tracked_ref_factory_.GetTrackedRef()),
-      task_tracker_, &lock_, backward_compatibility_);
-
-  if (!worker->Start(scheduler_worker_observer_))
-    return nullptr;
-
-  workers_.push_back(worker);
-  DCHECK_LE(workers_.size(), worker_capacity_);
-
-  if (!cleanup_timestamps_.empty()) {
-    cleanup_timestamps_.pop();
-  }
-  return worker.get();
-}
-
-size_t SchedulerWorkerPoolImpl::NumberOfExcessWorkersLockRequired() const {
-  lock_.AssertAcquired();
-  return std::max<int>(0, workers_.size() - worker_capacity_);
-}
-
-void SchedulerWorkerPoolImpl::AdjustWorkerCapacity() {
-  DCHECK(service_thread_task_runner_->RunsTasksInCurrentSequence());
-
-  std::unique_ptr<PriorityQueue::Transaction> shared_transaction(
-      shared_priority_queue_.BeginTransaction());
-  AutoSchedulerLock auto_lock(lock_);
-
-  const size_t original_worker_capacity = worker_capacity_;
-
-  // Increment worker capacity for each worker that has been within a MAY_BLOCK
-  // ScopedBlockingCall for more than MayBlockThreshold().
-  for (scoped_refptr<SchedulerWorker> worker : workers_) {
-    // The delegates of workers inside a SchedulerWorkerPoolImpl should be
-    // SchedulerWorkerDelegateImpls.
-    SchedulerWorkerDelegateImpl* delegate =
-        static_cast<SchedulerWorkerDelegateImpl*>(worker->delegate());
-    if (delegate->MustIncrementWorkerCapacityLockRequired())
-      IncrementWorkerCapacityLockRequired();
-  }
-
-  // Wake up a worker per pending sequence, capacity permitting.
-  const size_t num_pending_sequences = shared_transaction->Size();
-  const size_t num_wake_ups_needed = std::min(
-      worker_capacity_ - original_worker_capacity, num_pending_sequences);
-
-  for (size_t i = 0; i < num_wake_ups_needed; ++i) {
-    // No need to call PostAdjustWorkerCapacityTaskIfNeeded() as the caller will
-    // take care of that for us.
-    WakeUpOneWorkerLockRequired();
-  }
-
-  MaintainAtLeastOneIdleWorkerLockRequired();
-}
-
-TimeDelta SchedulerWorkerPoolImpl::MayBlockThreshold() const {
-  if (maximum_blocked_threshold_for_testing_.IsSet())
-    return TimeDelta::Max();
-  // This value was set unscientifically based on intuition and may be adjusted
-  // in the future. This value is smaller than |kBlockedWorkersPollPeriod|
-  // because we hope than when multiple workers block around the same time, a
-  // single AdjustWorkerCapacity() call will perform all the necessary capacity
-  // adjustments.
-  return TimeDelta::FromMilliseconds(10);
-}
-
-void SchedulerWorkerPoolImpl::PostAdjustWorkerCapacityTaskIfNeeded() {
-  {
-    AutoSchedulerLock auto_lock(lock_);
-    if (polling_worker_capacity_ ||
-        !ShouldPeriodicallyAdjustWorkerCapacityLockRequired()) {
-      return;
-    }
-    polling_worker_capacity_ = true;
-  }
-  service_thread_task_runner_->PostDelayedTask(
-      FROM_HERE,
-      BindOnce(&SchedulerWorkerPoolImpl::AdjustWorkerCapacityTaskFunction,
-               Unretained(this)),
-      kBlockedWorkersPollPeriod);
-}
-
-void SchedulerWorkerPoolImpl::AdjustWorkerCapacityTaskFunction() {
-  DCHECK(service_thread_task_runner_->RunsTasksInCurrentSequence());
-
-  AdjustWorkerCapacity();
-  {
-    AutoSchedulerLock auto_lock(lock_);
-    DCHECK(polling_worker_capacity_);
-
-    if (!ShouldPeriodicallyAdjustWorkerCapacityLockRequired()) {
-      polling_worker_capacity_ = false;
-      return;
-    }
-  }
-  service_thread_task_runner_->PostDelayedTask(
-      FROM_HERE,
-      BindOnce(&SchedulerWorkerPoolImpl::AdjustWorkerCapacityTaskFunction,
-               Unretained(this)),
-      kBlockedWorkersPollPeriod);
-}
-
-bool SchedulerWorkerPoolImpl::
-    ShouldPeriodicallyAdjustWorkerCapacityLockRequired() {
-  lock_.AssertAcquired();
-  // AdjustWorkerCapacity() must be periodically called when (1) there are no
-  // idle workers that can do work (2) there are workers that are within the
-  // scope of a MAY_BLOCK ScopedBlockingCall but haven't cause a capacity
-  // increment yet.
-  //
-  // - When (1) is false: A newly posted task will run on one of the idle
-  //   workers that are allowed to do work. There is no hurry to increase
-  //   capacity.
-  // - When (2) is false: AdjustWorkerCapacity() would be a no-op.
-  const int idle_workers_that_can_do_work =
-      idle_workers_stack_.Size() - NumberOfExcessWorkersLockRequired();
-  return idle_workers_that_can_do_work <= 0 &&
-         num_pending_may_block_workers_ > 0;
-}
-
-void SchedulerWorkerPoolImpl::DecrementWorkerCapacityLockRequired() {
-  lock_.AssertAcquired();
-  --worker_capacity_;
-}
-
-void SchedulerWorkerPoolImpl::IncrementWorkerCapacityLockRequired() {
-  lock_.AssertAcquired();
-  ++worker_capacity_;
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/scheduler_worker_pool_impl.h b/base/task_scheduler/scheduler_worker_pool_impl.h
deleted file mode 100644
index d331d3c..0000000
--- a/base/task_scheduler/scheduler_worker_pool_impl.h
+++ /dev/null
@@ -1,318 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_SCHEDULER_WORKER_POOL_IMPL_H_
-#define BASE_TASK_SCHEDULER_SCHEDULER_WORKER_POOL_IMPL_H_
-
-#include <stddef.h>
-
-#include <memory>
-#include <string>
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/containers/stack.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/strings/string_piece.h"
-#include "base/synchronization/atomic_flag.h"
-#include "base/synchronization/condition_variable.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/task_runner.h"
-#include "base/task_scheduler/priority_queue.h"
-#include "base/task_scheduler/scheduler_lock.h"
-#include "base/task_scheduler/scheduler_worker.h"
-#include "base/task_scheduler/scheduler_worker_pool.h"
-#include "base/task_scheduler/scheduler_worker_stack.h"
-#include "base/task_scheduler/sequence.h"
-#include "base/task_scheduler/task.h"
-#include "base/task_scheduler/tracked_ref.h"
-#include "base/time/time.h"
-#include "build_config.h"
-
-namespace base {
-
-class SchedulerWorkerObserver;
-class SchedulerWorkerPoolParams;
-
-namespace internal {
-
-class DelayedTaskManager;
-class TaskTracker;
-
-// A pool of workers that run Tasks.
-//
-// The pool doesn't create threads until Start() is called. Tasks can be posted
-// at any time but will not run until after Start() is called.
-//
-// This class is thread-safe.
-class BASE_EXPORT SchedulerWorkerPoolImpl : public SchedulerWorkerPool {
- public:
-  enum class WorkerEnvironment {
-    // No special worker environment required.
-    NONE,
-#if defined(OS_WIN)
-    // Initialize a COM MTA on the worker.
-    COM_MTA,
-#endif  // defined(OS_WIN)
-  };
-
-  // Constructs a pool without workers.
-  //
-  // |histogram_label| is used to label the pool's histograms ("TaskScheduler."
-  // + histogram_name + "." + |histogram_label| + extra suffixes), it must not
-  // be empty. |pool_label| is used to label the pool's threads, it must not be
-  // empty. |priority_hint| is the preferred thread priority; the actual thread
-  // priority depends on shutdown state and platform capabilities.
-  // |task_tracker| keeps track of tasks. |delayed_task_manager| handles tasks
-  // posted with a delay.
-  SchedulerWorkerPoolImpl(StringPiece histogram_label,
-                          StringPiece pool_label,
-                          ThreadPriority priority_hint,
-                          TrackedRef<TaskTracker> task_tracker,
-                          DelayedTaskManager* delayed_task_manager);
-
-  // Creates workers following the |params| specification, allowing existing and
-  // future tasks to run. Uses |service_thread_task_runner| to monitor for
-  // blocked threads in the pool. If specified, |scheduler_worker_observer| will
-  // be notified when a worker enters and exits its main function. It must not
-  // be destroyed before JoinForTesting() has returned (must never be destroyed
-  // in production). |worker_environment| specifies any requested environment to
-  // execute the tasks. Can only be called once. CHECKs on failure.
-  void Start(const SchedulerWorkerPoolParams& params,
-             scoped_refptr<TaskRunner> service_thread_task_runner,
-             SchedulerWorkerObserver* scheduler_worker_observer,
-             WorkerEnvironment worker_environment);
-
-  // Destroying a SchedulerWorkerPoolImpl returned by Create() is not allowed in
-  // production; it is always leaked. In tests, it can only be destroyed after
-  // JoinForTesting() has returned.
-  ~SchedulerWorkerPoolImpl() override;
-
-  // SchedulerWorkerPool:
-  void JoinForTesting() override;
-
-  // Returns the maximum number of non-blocked tasks that can run concurrently
-  // in this pool.
-  //
-  // TODO(fdoray): Remove this method. https://crbug.com/687264
-  int GetMaxConcurrentNonBlockedTasksDeprecated() const;
-
-  // Waits until at least |n| workers are idle. Note that while workers are
-  // disallowed from cleaning up during this call: tests using a custom
-  // |suggested_reclaim_time_| need to be careful to invoke this swiftly after
-  // unblocking the waited upon workers as: if a worker is already detached by
-  // the time this is invoked, it will never make it onto the idle stack and
-  // this call will hang.
-  void WaitForWorkersIdleForTesting(size_t n);
-
-  // Waits until all workers are idle.
-  void WaitForAllWorkersIdleForTesting();
-
-  // Waits until |n| workers have cleaned up. Tests that use this must:
-  //  - Invoke WaitForWorkersCleanedUpForTesting(n) well before any workers
-  //    have had time to clean up.
-  //  - Have a long enough |suggested_reclaim_time_| to strengthen the above.
-  //  - Only invoke this once (currently doesn't support waiting for multiple
-  //    cleanup phases in the same test).
-  void WaitForWorkersCleanedUpForTesting(size_t n);
-
-  // Returns the number of workers in this worker pool.
-  size_t NumberOfWorkersForTesting() const;
-
-  // Returns |worker_capacity_|.
-  size_t GetWorkerCapacityForTesting() const;
-
-  // Returns the number of workers that are idle (i.e. not running tasks).
-  size_t NumberOfIdleWorkersForTesting() const;
-
-  // Sets the MayBlock waiting threshold to TimeDelta::Max().
-  void MaximizeMayBlockThresholdForTesting();
-
- private:
-  class SchedulerWorkerDelegateImpl;
-
-  // Friend tests so that they can access |kBlockedWorkersPollPeriod| and
-  // BlockedThreshold().
-  friend class TaskSchedulerWorkerPoolBlockingTest;
-  friend class TaskSchedulerWorkerPoolMayBlockTest;
-
-  // The period between calls to AdjustWorkerCapacity() when the pool is at
-  // capacity. This value was set unscientifically based on intuition and may be
-  // adjusted in the future.
-  static constexpr TimeDelta kBlockedWorkersPollPeriod =
-      TimeDelta::FromMilliseconds(50);
-
-  // SchedulerWorkerPool:
-  void OnCanScheduleSequence(scoped_refptr<Sequence> sequence) override;
-
-  // Waits until at least |n| workers are idle. |lock_| must be held to call
-  // this function.
-  void WaitForWorkersIdleLockRequiredForTesting(size_t n);
-
-  // Wakes up the last worker from this worker pool to go idle, if any.
-  void WakeUpOneWorker();
-
-  // Performs the same action as WakeUpOneWorker() except asserts |lock_| is
-  // acquired rather than acquires it and returns true if worker wakeups are
-  // permitted.
-  bool WakeUpOneWorkerLockRequired();
-
-  // Adds a worker, if needed, to maintain one idle worker, |worker_capacity_|
-  // permitting.
-  void MaintainAtLeastOneIdleWorkerLockRequired();
-
-  // Adds |worker| to |idle_workers_stack_|.
-  void AddToIdleWorkersStackLockRequired(SchedulerWorker* worker);
-
-  // Peeks from |idle_workers_stack_|.
-  const SchedulerWorker* PeekAtIdleWorkersStackLockRequired() const;
-
-  // Removes |worker| from |idle_workers_stack_|.
-  void RemoveFromIdleWorkersStackLockRequired(SchedulerWorker* worker);
-
-  // Returns true if worker cleanup is permitted.
-  bool CanWorkerCleanupForTestingLockRequired();
-
-  // Tries to add a new SchedulerWorker to the pool. Returns the new
-  // SchedulerWorker on success, nullptr otherwise. Cannot be called before
-  // Start(). Must be called under the protection of |lock_|.
-  SchedulerWorker* CreateRegisterAndStartSchedulerWorkerLockRequired();
-
-  // Returns the number of workers in the pool that should not run tasks due to
-  // the pool being over worker capacity.
-  size_t NumberOfExcessWorkersLockRequired() const;
-
-  // Examines the list of SchedulerWorkers and increments |worker_capacity_| for
-  // each worker that has been within the scope of a MAY_BLOCK
-  // ScopedBlockingCall for more than BlockedThreshold().
-  void AdjustWorkerCapacity();
-
-  // Returns the threshold after which the worker capacity is increased to
-  // compensate for a worker that is within a MAY_BLOCK ScopedBlockingCall.
-  TimeDelta MayBlockThreshold() const;
-
-  // Starts calling AdjustWorkerCapacity() periodically on
-  // |service_thread_task_runner_| if not already requested.
-  void PostAdjustWorkerCapacityTaskIfNeeded();
-
-  // Calls AdjustWorkerCapacity() and schedules it again as necessary. May only
-  // be called from the service thread.
-  void AdjustWorkerCapacityTaskFunction();
-
-  // Returns true if AdjustWorkerCapacity() should periodically be called on
-  // |service_thread_task_runner_|.
-  bool ShouldPeriodicallyAdjustWorkerCapacityLockRequired();
-
-  void DecrementWorkerCapacityLockRequired();
-  void IncrementWorkerCapacityLockRequired();
-
-  const std::string pool_label_;
-  const ThreadPriority priority_hint_;
-
-  // PriorityQueue from which all threads of this worker pool get work.
-  PriorityQueue shared_priority_queue_;
-
-  // Suggested reclaim time for workers. Initialized by Start(). Never modified
-  // afterwards (i.e. can be read without synchronization after Start()).
-  TimeDelta suggested_reclaim_time_;
-
-  SchedulerBackwardCompatibility backward_compatibility_;
-
-  // Synchronizes accesses to |workers_|, |worker_capacity_|,
-  // |num_pending_may_block_workers_|, |idle_workers_stack_|,
-  // |idle_workers_stack_cv_for_testing_|, |num_wake_ups_before_start_|,
-  // |cleanup_timestamps_|, |polling_worker_capacity_|,
-  // |worker_cleanup_disallowed_for_testing_|,
-  // |num_workers_cleaned_up_for_testing_|,
-  // |SchedulerWorkerDelegateImpl::is_on_idle_workers_stack_|,
-  // |SchedulerWorkerDelegateImpl::incremented_worker_capacity_since_blocked_|
-  // and |SchedulerWorkerDelegateImpl::may_block_start_time_|. Has
-  // |shared_priority_queue_|'s lock as its predecessor so that a worker can be
-  // pushed to |idle_workers_stack_| within the scope of a Transaction (more
-  // details in GetWork()).
-  mutable SchedulerLock lock_;
-
-  // All workers owned by this worker pool.
-  std::vector<scoped_refptr<SchedulerWorker>> workers_;
-
-  // Workers can be added as needed up until there are |worker_capacity_|
-  // workers.
-  size_t worker_capacity_ = 0;
-
-  // Initial value of |worker_capacity_| as set in Start().
-  size_t initial_worker_capacity_ = 0;
-
-  // Number workers that are within the scope of a MAY_BLOCK ScopedBlockingCall
-  // but haven't caused a worker capacity increase yet.
-  int num_pending_may_block_workers_ = 0;
-
-  // Environment to be initialized per worker.
-  WorkerEnvironment worker_environment_ = WorkerEnvironment::NONE;
-
-  // Stack of idle workers. Initially, all workers are on this stack. A worker
-  // is removed from the stack before its WakeUp() function is called and when
-  // it receives work from GetWork() (a worker calls GetWork() when its sleep
-  // timeout expires, even if its WakeUp() method hasn't been called). A worker
-  // is pushed on this stack when it receives nullptr from GetWork().
-  SchedulerWorkerStack idle_workers_stack_;
-
-  // Signaled when a worker is added to the idle workers stack.
-  std::unique_ptr<ConditionVariable> idle_workers_stack_cv_for_testing_;
-
-  // Number of wake ups that occurred before Start(). Never modified after
-  // Start() (i.e. can be read without synchronization after Start()).
-  int num_wake_ups_before_start_ = 0;
-
-  // Stack that contains the timestamps of when workers get cleaned up.
-  // Timestamps get popped off the stack as new workers are added.
-  base::stack<TimeTicks, std::vector<TimeTicks>> cleanup_timestamps_;
-
-  // Whether we are currently polling for necessary adjustments to
-  // |worker_capacity_|.
-  bool polling_worker_capacity_ = false;
-
-  // Indicates to the delegates that workers are not permitted to cleanup.
-  bool worker_cleanup_disallowed_for_testing_ = false;
-
-  // Counts the number of workers cleaned up since Start(). Tests with a custom
-  // |suggested_reclaim_time_| can wait on a specific number of workers being
-  // cleaned up via WaitForWorkersCleanedUpForTesting().
-  size_t num_workers_cleaned_up_for_testing_ = 0;
-
-  // Signaled, if non-null, when |num_workers_cleaned_up_for_testing_| is
-  // incremented.
-  std::unique_ptr<ConditionVariable> num_workers_cleaned_up_for_testing_cv_;
-
-  // Used for testing and makes MayBlockThreshold() return the maximum
-  // TimeDelta.
-  AtomicFlag maximum_blocked_threshold_for_testing_;
-
-#if DCHECK_IS_ON()
-  // Set at the start of JoinForTesting().
-  AtomicFlag join_for_testing_started_;
-#endif
-
-  scoped_refptr<TaskRunner> service_thread_task_runner_;
-
-  // Optional observer notified when a worker enters and exits its main
-  // function. Set in Start() and never modified afterwards.
-  SchedulerWorkerObserver* scheduler_worker_observer_ = nullptr;
-
-  // Ensures recently cleaned up workers (ref.
-  // SchedulerWorkerDelegateImpl::CleanupLockRequired()) had time to exit as
-  // they have a raw reference to |this| (and to TaskTracker) which can
-  // otherwise result in racy use-after-frees per no longer being part of
-  // |workers_| and hence not being explicitly joined in JoinForTesting() :
-  // https://crbug.com/810464.
-  TrackedRefFactory<SchedulerWorkerPoolImpl> tracked_ref_factory_;
-
-  DISALLOW_COPY_AND_ASSIGN(SchedulerWorkerPoolImpl);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SCHEDULER_WORKER_POOL_IMPL_H_
diff --git a/base/task_scheduler/scheduler_worker_pool_params.cc b/base/task_scheduler/scheduler_worker_pool_params.cc
deleted file mode 100644
index db85569..0000000
--- a/base/task_scheduler/scheduler_worker_pool_params.cc
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2016 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/task_scheduler/scheduler_worker_pool_params.h"
-
-namespace base {
-
-SchedulerWorkerPoolParams::SchedulerWorkerPoolParams(
-    int max_threads,
-    TimeDelta suggested_reclaim_time,
-    SchedulerBackwardCompatibility backward_compatibility)
-    : max_threads_(max_threads),
-      suggested_reclaim_time_(suggested_reclaim_time),
-      backward_compatibility_(backward_compatibility) {}
-
-SchedulerWorkerPoolParams::SchedulerWorkerPoolParams(
-    const SchedulerWorkerPoolParams& other) = default;
-
-SchedulerWorkerPoolParams& SchedulerWorkerPoolParams::operator=(
-    const SchedulerWorkerPoolParams& other) = default;
-
-}  // namespace base
diff --git a/base/task_scheduler/scheduler_worker_pool_params.h b/base/task_scheduler/scheduler_worker_pool_params.h
deleted file mode 100644
index 928d3b4..0000000
--- a/base/task_scheduler/scheduler_worker_pool_params.h
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_SCHEDULER_WORKER_POOL_PARAMS_H_
-#define BASE_TASK_SCHEDULER_SCHEDULER_WORKER_POOL_PARAMS_H_
-
-#include "base/task_scheduler/scheduler_worker_params.h"
-#include "base/time/time.h"
-
-namespace base {
-
-class BASE_EXPORT SchedulerWorkerPoolParams final {
- public:
-  // Constructs a set of params used to initialize a pool. The pool will contain
-  // up to |max_threads|. |suggested_reclaim_time| sets a suggestion on when to
-  // reclaim idle threads. The pool is free to ignore this value for performance
-  // or correctness reasons. |backward_compatibility| indicates whether backward
-  // compatibility is enabled.
-  SchedulerWorkerPoolParams(
-      int max_threads,
-      TimeDelta suggested_reclaim_time,
-      SchedulerBackwardCompatibility backward_compatibility =
-          SchedulerBackwardCompatibility::DISABLED);
-
-  SchedulerWorkerPoolParams(const SchedulerWorkerPoolParams& other);
-  SchedulerWorkerPoolParams& operator=(const SchedulerWorkerPoolParams& other);
-
-  int max_threads() const { return max_threads_; }
-  TimeDelta suggested_reclaim_time() const { return suggested_reclaim_time_; }
-  SchedulerBackwardCompatibility backward_compatibility() const {
-    return backward_compatibility_;
-  }
-
- private:
-  int max_threads_;
-  TimeDelta suggested_reclaim_time_;
-  SchedulerBackwardCompatibility backward_compatibility_;
-};
-
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SCHEDULER_WORKER_POOL_PARAMS_H_
diff --git a/base/task_scheduler/scheduler_worker_stack.cc b/base/task_scheduler/scheduler_worker_stack.cc
deleted file mode 100644
index e5a0ab1..0000000
--- a/base/task_scheduler/scheduler_worker_stack.cc
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2016 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/task_scheduler/scheduler_worker_stack.h"
-
-#include <algorithm>
-
-#include "base/logging.h"
-#include "base/stl_util.h"
-
-namespace base {
-namespace internal {
-
-SchedulerWorkerStack::SchedulerWorkerStack() = default;
-
-SchedulerWorkerStack::~SchedulerWorkerStack() = default;
-
-void SchedulerWorkerStack::Push(SchedulerWorker* worker) {
-  DCHECK(!Contains(worker)) << "SchedulerWorker already on stack";
-  stack_.push_back(worker);
-}
-
-SchedulerWorker* SchedulerWorkerStack::Pop() {
-  if (IsEmpty())
-    return nullptr;
-  SchedulerWorker* const worker = stack_.back();
-  stack_.pop_back();
-  return worker;
-}
-
-SchedulerWorker* SchedulerWorkerStack::Peek() const {
-  if (IsEmpty())
-    return nullptr;
-  return stack_.back();
-}
-
-bool SchedulerWorkerStack::Contains(const SchedulerWorker* worker) const {
-  return ContainsValue(stack_, worker);
-}
-
-void SchedulerWorkerStack::Remove(const SchedulerWorker* worker) {
-  auto it = std::find(stack_.begin(), stack_.end(), worker);
-  if (it != stack_.end())
-    stack_.erase(it);
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/scheduler_worker_stack.h b/base/task_scheduler/scheduler_worker_stack.h
deleted file mode 100644
index b96fc5a..0000000
--- a/base/task_scheduler/scheduler_worker_stack.h
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_SCHEDULER_WORKER_STACK_H_
-#define BASE_TASK_SCHEDULER_SCHEDULER_WORKER_STACK_H_
-
-#include <stddef.h>
-
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-
-namespace base {
-namespace internal {
-
-class SchedulerWorker;
-
-// A stack of SchedulerWorkers. Supports removal of arbitrary SchedulerWorkers.
-// DCHECKs when a SchedulerWorker is inserted multiple times. SchedulerWorkers
-// are not owned by the stack. Push() is amortized O(1). Pop(), Peek(), Size()
-// and Empty() are O(1). Contains() and Remove() are O(n).
-// This class is NOT thread-safe.
-class BASE_EXPORT SchedulerWorkerStack {
- public:
-  SchedulerWorkerStack();
-  ~SchedulerWorkerStack();
-
-  // Inserts |worker| at the top of the stack. |worker| must not already be on
-  // the stack.
-  void Push(SchedulerWorker* worker);
-
-  // Removes the top SchedulerWorker from the stack and returns it.
-  // Returns nullptr if the stack is empty.
-  SchedulerWorker* Pop();
-
-  // Returns the top SchedulerWorker from the stack, nullptr if empty.
-  SchedulerWorker* Peek() const;
-
-  // Returns true if |worker| is already on the stack.
-  bool Contains(const SchedulerWorker* worker) const;
-
-  // Removes |worker| from the stack.
-  void Remove(const SchedulerWorker* worker);
-
-  // Returns the number of SchedulerWorkers on the stack.
-  size_t Size() const { return stack_.size(); }
-
-  // Returns true if the stack is empty.
-  bool IsEmpty() const { return stack_.empty(); }
-
- private:
-  std::vector<SchedulerWorker*> stack_;
-
-  DISALLOW_COPY_AND_ASSIGN(SchedulerWorkerStack);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SCHEDULER_WORKER_STACK_H_
diff --git a/base/task_scheduler/scoped_set_task_priority_for_current_thread.cc b/base/task_scheduler/scoped_set_task_priority_for_current_thread.cc
deleted file mode 100644
index a163863..0000000
--- a/base/task_scheduler/scoped_set_task_priority_for_current_thread.cc
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2016 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/task_scheduler/scoped_set_task_priority_for_current_thread.h"
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/threading/thread_local.h"
-
-namespace base {
-namespace internal {
-
-namespace {
-
-LazyInstance<ThreadLocalPointer<const TaskPriority>>::Leaky
-    tls_task_priority_for_current_thread = LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace
-
-ScopedSetTaskPriorityForCurrentThread::ScopedSetTaskPriorityForCurrentThread(
-    TaskPriority priority)
-    : priority_(priority) {
-  DCHECK(!tls_task_priority_for_current_thread.Get().Get());
-  tls_task_priority_for_current_thread.Get().Set(&priority_);
-}
-
-ScopedSetTaskPriorityForCurrentThread::
-    ~ScopedSetTaskPriorityForCurrentThread() {
-  DCHECK_EQ(&priority_, tls_task_priority_for_current_thread.Get().Get());
-  tls_task_priority_for_current_thread.Get().Set(nullptr);
-}
-
-TaskPriority GetTaskPriorityForCurrentThread() {
-  const TaskPriority* priority =
-      tls_task_priority_for_current_thread.Get().Get();
-  return priority ? *priority : TaskPriority::USER_VISIBLE;
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/scoped_set_task_priority_for_current_thread.h b/base/task_scheduler/scoped_set_task_priority_for_current_thread.h
deleted file mode 100644
index 4508911..0000000
--- a/base/task_scheduler/scoped_set_task_priority_for_current_thread.h
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_SCOPED_SET_TASK_PRIORITY_FOR_CURRENT_THREAD_H_
-#define BASE_TASK_SCHEDULER_SCOPED_SET_TASK_PRIORITY_FOR_CURRENT_THREAD_H_
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/task_scheduler/task_traits.h"
-
-namespace base {
-namespace internal {
-
-class BASE_EXPORT ScopedSetTaskPriorityForCurrentThread {
- public:
-  // Within the scope of this object, GetTaskPriorityForCurrentThread() will
-  // return |priority|.
-  ScopedSetTaskPriorityForCurrentThread(TaskPriority priority);
-  ~ScopedSetTaskPriorityForCurrentThread();
-
- private:
-  const TaskPriority priority_;
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedSetTaskPriorityForCurrentThread);
-};
-
-// Returns the priority of the TaskScheduler task running on the current thread,
-// or TaskPriority::USER_VISIBLE if no TaskScheduler task is running on the
-// current thread.
-BASE_EXPORT TaskPriority GetTaskPriorityForCurrentThread();
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SCOPED_SET_TASK_PRIORITY_FOR_CURRENT_THREAD_H_
diff --git a/base/task_scheduler/sequence.cc b/base/task_scheduler/sequence.cc
deleted file mode 100644
index 4737f8e..0000000
--- a/base/task_scheduler/sequence.cc
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright 2016 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/task_scheduler/sequence.h"
-
-#include <utility>
-
-#include "base/logging.h"
-#include "base/time/time.h"
-
-namespace base {
-namespace internal {
-
-Sequence::Sequence() = default;
-
-bool Sequence::PushTask(Task task) {
-  // Use CHECK instead of DCHECK to crash earlier. See http://crbug.com/711167
-  // for details.
-  CHECK(task.task);
-  DCHECK(task.sequenced_time.is_null());
-  task.sequenced_time = base::TimeTicks::Now();
-
-  AutoSchedulerLock auto_lock(lock_);
-  ++num_tasks_per_priority_[static_cast<int>(task.traits.priority())];
-  queue_.push(std::move(task));
-
-  // Return true if the sequence was empty before the push.
-  return queue_.size() == 1;
-}
-
-Optional<Task> Sequence::TakeTask() {
-  AutoSchedulerLock auto_lock(lock_);
-  DCHECK(!queue_.empty());
-  DCHECK(queue_.front().task);
-
-  const int priority_index = static_cast<int>(queue_.front().traits.priority());
-  DCHECK_GT(num_tasks_per_priority_[priority_index], 0U);
-  --num_tasks_per_priority_[priority_index];
-
-  return std::move(queue_.front());
-}
-
-TaskTraits Sequence::PeekTaskTraits() const {
-  AutoSchedulerLock auto_lock(lock_);
-  DCHECK(!queue_.empty());
-  DCHECK(queue_.front().task);
-  return queue_.front().traits;
-}
-
-bool Sequence::Pop() {
-  AutoSchedulerLock auto_lock(lock_);
-  DCHECK(!queue_.empty());
-  DCHECK(!queue_.front().task);
-  queue_.pop();
-  return queue_.empty();
-}
-
-SequenceSortKey Sequence::GetSortKey() const {
-  TaskPriority priority = TaskPriority::LOWEST;
-  base::TimeTicks next_task_sequenced_time;
-
-  {
-    AutoSchedulerLock auto_lock(lock_);
-    DCHECK(!queue_.empty());
-
-    // Find the highest task priority in the sequence.
-    const int highest_priority_index = static_cast<int>(TaskPriority::HIGHEST);
-    const int lowest_priority_index = static_cast<int>(TaskPriority::LOWEST);
-    for (int i = highest_priority_index; i > lowest_priority_index; --i) {
-      if (num_tasks_per_priority_[i] > 0) {
-        priority = static_cast<TaskPriority>(i);
-        break;
-      }
-    }
-
-    // Save the sequenced time of the next task in the sequence.
-    next_task_sequenced_time = queue_.front().sequenced_time;
-  }
-
-  return SequenceSortKey(priority, next_task_sequenced_time);
-}
-
-Sequence::~Sequence() = default;
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/sequence.h b/base/task_scheduler/sequence.h
deleted file mode 100644
index ec5e8c1..0000000
--- a/base/task_scheduler/sequence.h
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_SEQUENCE_H_
-#define BASE_TASK_SCHEDULER_SEQUENCE_H_
-
-#include <stddef.h>
-
-#include "base/base_export.h"
-#include "base/containers/queue.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/optional.h"
-#include "base/sequence_token.h"
-#include "base/task_scheduler/scheduler_lock.h"
-#include "base/task_scheduler/sequence_sort_key.h"
-#include "base/task_scheduler/task.h"
-#include "base/task_scheduler/task_traits.h"
-#include "base/threading/sequence_local_storage_map.h"
-
-namespace base {
-namespace internal {
-
-// A Sequence holds slots each containing up to a single Task that must be
-// executed in posting order.
-//
-// In comments below, an "empty Sequence" is a Sequence with no slot.
-//
-// Note: there is a known refcounted-ownership cycle in the Scheduler
-// architecture: Sequence -> Task -> TaskRunner -> Sequence -> ...
-// This is okay so long as the other owners of Sequence (PriorityQueue and
-// SchedulerWorker in alternation and
-// SchedulerWorkerPoolImpl::SchedulerWorkerDelegateImpl::GetWork()
-// temporarily) keep running it (and taking Tasks from it as a result). A
-// dangling reference cycle would only occur should they release their reference
-// to it while it's not empty. In other words, it is only correct for them to
-// release it after PopTask() returns false to indicate it was made empty by
-// that call (in which case the next PushTask() will return true to indicate to
-// the caller that the Sequence should be re-enqueued for execution).
-//
-// This class is thread-safe.
-class BASE_EXPORT Sequence : public RefCountedThreadSafe<Sequence> {
- public:
-  Sequence();
-
-  // Adds |task| in a new slot at the end of the Sequence. Returns true if the
-  // Sequence was empty before this operation.
-  bool PushTask(Task task);
-
-  // Transfers ownership of the Task in the front slot of the Sequence to the
-  // caller. The front slot of the Sequence will be nullptr and remain until
-  // Pop(). Cannot be called on an empty Sequence or a Sequence whose front slot
-  // is already nullptr.
-  //
-  // Because this method cannot be called on an empty Sequence, the returned
-  // Optional<Task> is never nullptr. An Optional is used in preparation for the
-  // merge between TaskScheduler and TaskQueueManager (in Blink).
-  // https://crbug.com/783309
-  Optional<Task> TakeTask();
-
-  // Returns the TaskTraits of the Task in front of the Sequence. Cannot be
-  // called on an empty Sequence or on a Sequence whose front slot is empty.
-  TaskTraits PeekTaskTraits() const;
-
-  // Removes the front slot of the Sequence. The front slot must have been
-  // emptied by TakeTask() before this is called. Cannot be called on an empty
-  // Sequence. Returns true if the Sequence is empty after this operation.
-  bool Pop();
-
-  // Returns a SequenceSortKey representing the priority of the Sequence. Cannot
-  // be called on an empty Sequence.
-  SequenceSortKey GetSortKey() const;
-
-  // Returns a token that uniquely identifies this Sequence.
-  const SequenceToken& token() const { return token_; }
-
-  SequenceLocalStorageMap* sequence_local_storage() {
-    return &sequence_local_storage_;
-  }
-
- private:
-  friend class RefCountedThreadSafe<Sequence>;
-  ~Sequence();
-
-  const SequenceToken token_ = SequenceToken::Create();
-
-  // Synchronizes access to all members.
-  mutable SchedulerLock lock_;
-
-  // Queue of tasks to execute.
-  base::queue<Task> queue_;
-
-  // Number of tasks contained in the Sequence for each priority.
-  size_t num_tasks_per_priority_[static_cast<int>(TaskPriority::HIGHEST) + 1] =
-      {};
-
-  // Holds data stored through the SequenceLocalStorageSlot API.
-  SequenceLocalStorageMap sequence_local_storage_;
-
-  DISALLOW_COPY_AND_ASSIGN(Sequence);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SEQUENCE_H_
diff --git a/base/task_scheduler/sequence_sort_key.cc b/base/task_scheduler/sequence_sort_key.cc
deleted file mode 100644
index e356c8b..0000000
--- a/base/task_scheduler/sequence_sort_key.cc
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2016 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/task_scheduler/sequence_sort_key.h"
-
-namespace base {
-namespace internal {
-
-SequenceSortKey::SequenceSortKey(TaskPriority priority,
-                                 TimeTicks next_task_sequenced_time)
-    : priority_(priority),
-      next_task_sequenced_time_(next_task_sequenced_time) {}
-
-bool SequenceSortKey::operator<(const SequenceSortKey& other) const {
-  // This SequenceSortKey is considered less important than |other| if it has a
-  // lower priority or if it has the same priority but its next task was posted
-  // later than |other|'s.
-  const int priority_diff =
-      static_cast<int>(priority_) - static_cast<int>(other.priority_);
-  if (priority_diff < 0)
-    return true;
-  if (priority_diff > 0)
-    return false;
-  return next_task_sequenced_time_ > other.next_task_sequenced_time_;
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/sequence_sort_key.h b/base/task_scheduler/sequence_sort_key.h
deleted file mode 100644
index 2e126c5..0000000
--- a/base/task_scheduler/sequence_sort_key.h
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_SEQUENCE_SORT_KEY_H_
-#define BASE_TASK_SCHEDULER_SEQUENCE_SORT_KEY_H_
-
-#include "base/base_export.h"
-#include "base/task_scheduler/task_traits.h"
-#include "base/time/time.h"
-
-namespace base {
-namespace internal {
-
-// An immutable but assignable representation of the priority of a Sequence.
-class BASE_EXPORT SequenceSortKey final {
- public:
-  SequenceSortKey(TaskPriority priority, TimeTicks next_task_sequenced_time);
-
-  TaskPriority priority() const { return priority_; }
-  TimeTicks next_task_sequenced_time() const {
-    return next_task_sequenced_time_;
-  }
-
-  bool operator<(const SequenceSortKey& other) const;
-  bool operator>(const SequenceSortKey& other) const { return other < *this; }
-
-  bool operator==(const SequenceSortKey& other) const {
-    return priority_ == other.priority_ &&
-           next_task_sequenced_time_ == other.next_task_sequenced_time_;
-  }
-  bool operator!=(const SequenceSortKey& other) const {
-    return !(other == *this);
-  };
-
- private:
-  // The private section allows this class to keep its immutable property while
-  // being copy-assignable (i.e. instead of making its members const).
-
-  // Highest task priority in the sequence at the time this sort key was
-  // created.
-  TaskPriority priority_;
-
-  // Sequenced time of the next task to run in the sequence at the time this
-  // sort key was created.
-  TimeTicks next_task_sequenced_time_;
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SEQUENCE_SORT_KEY_H_
diff --git a/base/task_scheduler/service_thread.cc b/base/task_scheduler/service_thread.cc
deleted file mode 100644
index 9ee0986..0000000
--- a/base/task_scheduler/service_thread.cc
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright 2018 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/task_scheduler/service_thread.h"
-
-#include "base/task_scheduler/post_task.h"
-#include "base/task_scheduler/task_tracker.h"
-#include "base/task_scheduler/task_traits.h"
-#include "base/time/time.h"
-
-namespace base {
-namespace internal {
-
-ServiceThread::ServiceThread() : Thread("TaskSchedulerServiceThread") {}
-
-void ServiceThread::Init() {}
-
-NOINLINE void ServiceThread::Run(RunLoop* run_loop) {
-  const int line_number = __LINE__;
-  Thread::Run(run_loop);
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/service_thread.h b/base/task_scheduler/service_thread.h
deleted file mode 100644
index 14ccd76..0000000
--- a/base/task_scheduler/service_thread.h
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2018 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_TASK_SCHEDULER_SERVICE_THREAD_H_
-#define BASE_TASK_SCHEDULER_SERVICE_THREAD_H_
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/threading/thread.h"
-#include "base/timer/timer.h"
-
-namespace base {
-namespace internal {
-
-class TaskTracker;
-
-// The TaskScheduler's ServiceThread is a mostly idle thread that is responsible
-// for handling async events (e.g. delayed tasks and async I/O). Its role is to
-// merely forward such events to their destination (hence staying mostly idle
-// and highly responsive).
-// It aliases Thread::Run() to enforce that ServiceThread::Run() be on the stack
-// and make it easier to identify the service thread in stack traces.
-class BASE_EXPORT ServiceThread : public Thread {
- public:
-  // Constructs a ServiceThread which will report latency metrics through
-  // |task_tracker| if non-null. In that case, this ServiceThread will assume a
-  // registered TaskScheduler instance and that |task_tracker| will outlive this
-  // ServiceThread.
-  ServiceThread();
-
- private:
-  // Thread:
-  void Init() override;
-  void Run(RunLoop* run_loop) override;
-
-  DISALLOW_COPY_AND_ASSIGN(ServiceThread);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SERVICE_THREAD_H_
diff --git a/base/task_scheduler/single_thread_task_runner_thread_mode.h b/base/task_scheduler/single_thread_task_runner_thread_mode.h
deleted file mode 100644
index 6ed4228..0000000
--- a/base/task_scheduler/single_thread_task_runner_thread_mode.h
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_SINGLE_THREAD_TASK_RUNNER_THREAD_MODE_H_
-#define BASE_TASK_SCHEDULER_SINGLE_THREAD_TASK_RUNNER_THREAD_MODE_H_
-
-namespace base {
-
-enum class SingleThreadTaskRunnerThreadMode {
-  // Allow the SingleThreadTaskRunner's thread to be shared with others,
-  // allowing for efficient use of thread resources when this
-  // SingleThreadTaskRunner is idle. This is the default mode and is
-  // recommended for most code.
-  SHARED,
-  // Dedicate a single thread for this SingleThreadTaskRunner. No other tasks
-  // from any other source will run on the thread backing the
-  // SingleThreadTaskRunner. Use sparingly as this reserves an entire thread for
-  // this SingleThreadTaskRunner.
-  DEDICATED,
-};
-
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_SINGLE_THREAD_TASK_RUNNER_THREAD_MODE_H_
diff --git a/base/task_scheduler/task.cc b/base/task_scheduler/task.cc
deleted file mode 100644
index 563bb1e..0000000
--- a/base/task_scheduler/task.cc
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright 2016 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/task_scheduler/task.h"
-
-#include <utility>
-
-#include "base/atomic_sequence_num.h"
-#include "base/critical_closure.h"
-
-namespace base {
-namespace internal {
-
-namespace {
-
-AtomicSequenceNumber g_sequence_nums_for_tracing;
-
-}  // namespace
-
-Task::Task(const Location& posted_from,
-           OnceClosure task,
-           const TaskTraits& traits,
-           TimeDelta delay)
-    : PendingTask(
-          posted_from,
-          traits.shutdown_behavior() == TaskShutdownBehavior::BLOCK_SHUTDOWN
-              ? MakeCriticalClosure(std::move(task))
-              : std::move(task),
-          delay.is_zero() ? TimeTicks() : TimeTicks::Now() + delay,
-          Nestable::kNonNestable),
-      // Prevent a delayed BLOCK_SHUTDOWN task from blocking shutdown before it
-      // starts running by changing its shutdown behavior to SKIP_ON_SHUTDOWN.
-      traits(
-          (!delay.is_zero() &&
-           traits.shutdown_behavior() == TaskShutdownBehavior::BLOCK_SHUTDOWN)
-              ? TaskTraits::Override(traits,
-                                     {TaskShutdownBehavior::SKIP_ON_SHUTDOWN})
-              : traits),
-      delay(delay) {
-  // TaskScheduler doesn't use |sequence_num| but tracing (toplevel.flow) relies
-  // on it being unique. While this subtle dependency is a bit overreaching,
-  // TaskScheduler is the only task system that doesn't use |sequence_num| and
-  // the dependent code rarely changes so this isn't worth a big change and
-  // faking it here isn't too bad for now (posting tasks is full of atomic ops
-  // already).
-  this->sequence_num = g_sequence_nums_for_tracing.GetNext();
-}
-
-// This should be "= default but MSVC has trouble with "noexcept = default" in
-// this case.
-Task::Task(Task&& other) noexcept
-    : PendingTask(std::move(other)),
-      traits(other.traits),
-      delay(other.delay),
-      sequenced_time(other.sequenced_time),
-      sequenced_task_runner_ref(std::move(other.sequenced_task_runner_ref)),
-      single_thread_task_runner_ref(
-          std::move(other.single_thread_task_runner_ref)) {}
-
-Task::~Task() = default;
-
-Task& Task::operator=(Task&& other) = default;
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/task.h b/base/task_scheduler/task.h
deleted file mode 100644
index 3e937a8..0000000
--- a/base/task_scheduler/task.h
+++ /dev/null
@@ -1,74 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_TASK_H_
-#define BASE_TASK_SCHEDULER_TASK_H_
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/location.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/pending_task.h"
-#include "base/sequenced_task_runner.h"
-#include "base/single_thread_task_runner.h"
-#include "base/task_scheduler/task_traits.h"
-#include "base/time/time.h"
-
-namespace base {
-namespace internal {
-
-// A task is a unit of work inside the task scheduler. Support for tracing and
-// profiling inherited from PendingTask.
-struct BASE_EXPORT Task : public PendingTask {
-  // |posted_from| is the site the task was posted from. |task| is the closure
-  // to run. |traits_in| is metadata about the task. |delay| is a delay that
-  // must expire before the Task runs. If |delay| is non-zero and the shutdown
-  // behavior in |traits| is BLOCK_SHUTDOWN, the shutdown behavior is
-  // automatically adjusted to SKIP_ON_SHUTDOWN.
-  Task(const Location& posted_from,
-       OnceClosure task,
-       const TaskTraits& traits,
-       TimeDelta delay);
-
-  // Task is move-only to avoid mistakes that cause reference counts to be
-  // accidentally bumped.
-  Task(Task&& other) noexcept;
-
-  ~Task();
-
-  Task& operator=(Task&& other);
-
-  // The TaskTraits of this task.
-  TaskTraits traits;
-
-  // The delay that must expire before the task runs.
-  TimeDelta delay;
-
-  // The time at which the task was inserted in its sequence. For an undelayed
-  // task, this happens at post time. For a delayed task, this happens some
-  // time after the task's delay has expired. If the task hasn't been inserted
-  // in a sequence yet, this defaults to a null TimeTicks.
-  TimeTicks sequenced_time;
-
-  // A reference to the SequencedTaskRunner or SingleThreadTaskRunner that
-  // posted this task, if any. Used to set ThreadTaskRunnerHandle and/or
-  // SequencedTaskRunnerHandle while the task is running.
-  // Note: this creates an ownership cycle
-  //   Sequence -> Task -> TaskRunner -> Sequence -> ...
-  // but that's okay as it's broken when the Task is popped from its Sequence
-  // after being executed which means this cycle forces the TaskRunner to stick
-  // around until all its tasks have been executed which is a requirement to
-  // support TaskRunnerHandles.
-  scoped_refptr<SequencedTaskRunner> sequenced_task_runner_ref;
-  scoped_refptr<SingleThreadTaskRunner> single_thread_task_runner_ref;
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(Task);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_TASK_H_
diff --git a/base/task_scheduler/task_scheduler.cc b/base/task_scheduler/task_scheduler.cc
deleted file mode 100644
index 6d20ead..0000000
--- a/base/task_scheduler/task_scheduler.cc
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright 2016 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/task_scheduler/task_scheduler.h"
-
-#include <algorithm>
-
-#include "base/logging.h"
-#include "base/memory/ptr_util.h"
-#include "base/sys_info.h"
-#include "base/task_scheduler/scheduler_worker_pool_params.h"
-#include "base/task_scheduler/task_scheduler_impl.h"
-#include "base/threading/platform_thread.h"
-#include "base/time/time.h"
-
-namespace base {
-
-namespace {
-
-// |g_task_scheduler| is intentionally leaked on shutdown.
-TaskScheduler* g_task_scheduler = nullptr;
-
-}  // namespace
-
-TaskScheduler::InitParams::InitParams(
-    const SchedulerWorkerPoolParams& background_worker_pool_params_in,
-    const SchedulerWorkerPoolParams& background_blocking_worker_pool_params_in,
-    const SchedulerWorkerPoolParams& foreground_worker_pool_params_in,
-    const SchedulerWorkerPoolParams& foreground_blocking_worker_pool_params_in,
-    SharedWorkerPoolEnvironment shared_worker_pool_environment_in)
-    : background_worker_pool_params(background_worker_pool_params_in),
-      background_blocking_worker_pool_params(
-          background_blocking_worker_pool_params_in),
-      foreground_worker_pool_params(foreground_worker_pool_params_in),
-      foreground_blocking_worker_pool_params(
-          foreground_blocking_worker_pool_params_in),
-      shared_worker_pool_environment(shared_worker_pool_environment_in) {}
-
-TaskScheduler::InitParams::~InitParams() = default;
-
-#if !defined(OS_NACL)
-// static
-void TaskScheduler::CreateAndStartWithDefaultParams(StringPiece name) {
-  Create(name);
-  GetInstance()->StartWithDefaultParams();
-}
-
-void TaskScheduler::StartWithDefaultParams() {
-  // Values were chosen so that:
-  // * There are few background threads.
-  // * Background threads never outnumber foreground threads.
-  // * The system is utilized maximally by foreground threads.
-  // * The main thread is assumed to be busy, cap foreground workers at
-  //   |num_cores - 1|.
-  const int num_cores = SysInfo::NumberOfProcessors();
-  constexpr int kBackgroundMaxThreads = 1;
-  constexpr int kBackgroundBlockingMaxThreads = 2;
-  const int kForegroundMaxThreads = std::max(1, num_cores - 1);
-  const int kForegroundBlockingMaxThreads = std::max(2, num_cores - 1);
-
-  constexpr TimeDelta kSuggestedReclaimTime = TimeDelta::FromSeconds(30);
-
-  Start({{kBackgroundMaxThreads, kSuggestedReclaimTime},
-         {kBackgroundBlockingMaxThreads, kSuggestedReclaimTime},
-         {kForegroundMaxThreads, kSuggestedReclaimTime},
-         {kForegroundBlockingMaxThreads, kSuggestedReclaimTime}});
-}
-#endif  // !defined(OS_NACL)
-
-void TaskScheduler::Create(StringPiece name) {
-  SetInstance(std::make_unique<internal::TaskSchedulerImpl>(name));
-}
-
-// static
-void TaskScheduler::SetInstance(std::unique_ptr<TaskScheduler> task_scheduler) {
-  delete g_task_scheduler;
-  g_task_scheduler = task_scheduler.release();
-}
-
-// static
-TaskScheduler* TaskScheduler::GetInstance() {
-  return g_task_scheduler;
-}
-
-}  // namespace base
diff --git a/base/task_scheduler/task_scheduler.h b/base/task_scheduler/task_scheduler.h
deleted file mode 100644
index 3135f8c..0000000
--- a/base/task_scheduler/task_scheduler.h
+++ /dev/null
@@ -1,244 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_TASK_SCHEDULER_H_
-#define BASE_TASK_SCHEDULER_TASK_SCHEDULER_H_
-
-#include <memory>
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/gtest_prod_util.h"
-#include "base/memory/ref_counted.h"
-#include "base/sequenced_task_runner.h"
-#include "base/single_thread_task_runner.h"
-#include "base/strings/string_piece.h"
-#include "base/task_runner.h"
-#include "base/task_scheduler/scheduler_worker_pool_params.h"
-#include "base/task_scheduler/single_thread_task_runner_thread_mode.h"
-#include "base/task_scheduler/task_traits.h"
-#include "base/time/time.h"
-#include "build_config.h"
-
-namespace gin {
-class V8Platform;
-}
-
-namespace content {
-// Can't use the FRIEND_TEST_ALL_PREFIXES macro because the test is in a
-// different namespace.
-class BrowserMainLoopTest_CreateThreadsInSingleProcess_Test;
-}  // namespace content
-
-namespace base {
-
-class HistogramBase;
-class Location;
-class SchedulerWorkerObserver;
-
-// Interface for a task scheduler and static methods to manage the instance used
-// by the post_task.h API.
-//
-// The task scheduler doesn't create threads until Start() is called. Tasks can
-// be posted at any time but will not run until after Start() is called.
-//
-// The instance methods of this class are thread-safe.
-//
-// Note: All base/task_scheduler users should go through post_task.h instead of
-// TaskScheduler except for the one callsite per process which manages the
-// process's instance.
-class BASE_EXPORT TaskScheduler {
- public:
-  struct BASE_EXPORT InitParams {
-    enum class SharedWorkerPoolEnvironment {
-      // Use the default environment (no environment).
-      DEFAULT,
-#if defined(OS_WIN)
-      // Place the worker in a COM MTA.
-      COM_MTA,
-#endif  // defined(OS_WIN)
-    };
-
-    InitParams(
-        const SchedulerWorkerPoolParams& background_worker_pool_params_in,
-        const SchedulerWorkerPoolParams&
-            background_blocking_worker_pool_params_in,
-        const SchedulerWorkerPoolParams& foreground_worker_pool_params_in,
-        const SchedulerWorkerPoolParams&
-            foreground_blocking_worker_pool_params_in,
-        SharedWorkerPoolEnvironment shared_worker_pool_environment_in =
-            SharedWorkerPoolEnvironment::DEFAULT);
-    ~InitParams();
-
-    SchedulerWorkerPoolParams background_worker_pool_params;
-    SchedulerWorkerPoolParams background_blocking_worker_pool_params;
-    SchedulerWorkerPoolParams foreground_worker_pool_params;
-    SchedulerWorkerPoolParams foreground_blocking_worker_pool_params;
-    SharedWorkerPoolEnvironment shared_worker_pool_environment;
-  };
-
-  // Destroying a TaskScheduler is not allowed in production; it is always
-  // leaked. In tests, it should only be destroyed after JoinForTesting() has
-  // returned.
-  virtual ~TaskScheduler() = default;
-
-  // Allows the task scheduler to create threads and run tasks following the
-  // |init_params| specification.
-  //
-  // If specified, |scheduler_worker_observer| will be notified when a worker
-  // enters and exits its main function. It must not be destroyed before
-  // JoinForTesting() has returned (must never be destroyed in production).
-  //
-  // CHECKs on failure.
-  virtual void Start(
-      const InitParams& init_params,
-      SchedulerWorkerObserver* scheduler_worker_observer = nullptr) = 0;
-
-  // Posts |task| with a |delay| and specific |traits|. |delay| can be zero.
-  // For one off tasks that don't require a TaskRunner.
-  virtual void PostDelayedTaskWithTraits(const Location& from_here,
-                                         const TaskTraits& traits,
-                                         OnceClosure task,
-                                         TimeDelta delay) = 0;
-
-  // Returns a TaskRunner whose PostTask invocations result in scheduling tasks
-  // using |traits|. Tasks may run in any order and in parallel.
-  virtual scoped_refptr<TaskRunner> CreateTaskRunnerWithTraits(
-      const TaskTraits& traits) = 0;
-
-  // Returns a SequencedTaskRunner whose PostTask invocations result in
-  // scheduling tasks using |traits|. Tasks run one at a time in posting order.
-  virtual scoped_refptr<SequencedTaskRunner>
-  CreateSequencedTaskRunnerWithTraits(const TaskTraits& traits) = 0;
-
-  // Returns a SingleThreadTaskRunner whose PostTask invocations result in
-  // scheduling tasks using |traits|. Tasks run on a single thread in posting
-  // order.
-  virtual scoped_refptr<SingleThreadTaskRunner>
-  CreateSingleThreadTaskRunnerWithTraits(
-      const TaskTraits& traits,
-      SingleThreadTaskRunnerThreadMode thread_mode) = 0;
-
-#if defined(OS_WIN)
-  // Returns a SingleThreadTaskRunner whose PostTask invocations result in
-  // scheduling tasks using |traits| in a COM Single-Threaded Apartment. Tasks
-  // run in the same Single-Threaded Apartment in posting order for the returned
-  // SingleThreadTaskRunner. There is not necessarily a one-to-one
-  // correspondence between SingleThreadTaskRunners and Single-Threaded
-  // Apartments. The implementation is free to share apartments or create new
-  // apartments as necessary. In either case, care should be taken to make sure
-  // COM pointers are not smuggled across apartments.
-  virtual scoped_refptr<SingleThreadTaskRunner>
-  CreateCOMSTATaskRunnerWithTraits(
-      const TaskTraits& traits,
-      SingleThreadTaskRunnerThreadMode thread_mode) = 0;
-#endif  // defined(OS_WIN)
-
-  // Synchronously shuts down the scheduler. Once this is called, only tasks
-  // posted with the BLOCK_SHUTDOWN behavior will be run. When this returns:
-  // - All SKIP_ON_SHUTDOWN tasks that were already running have completed their
-  //   execution.
-  // - All posted BLOCK_SHUTDOWN tasks have completed their execution.
-  // - CONTINUE_ON_SHUTDOWN tasks might still be running.
-  // Note that an implementation can keep threads and other resources alive to
-  // support running CONTINUE_ON_SHUTDOWN after this returns. This can only be
-  // called once.
-  virtual void Shutdown() = 0;
-
-  // Waits until there are no pending undelayed tasks. May be called in tests
-  // to validate that a condition is met after all undelayed tasks have run.
-  //
-  // Does not wait for delayed tasks. Waits for undelayed tasks posted from
-  // other threads during the call. Returns immediately when shutdown completes.
-  virtual void FlushForTesting() = 0;
-
-  // Returns and calls |flush_callback| when there are no incomplete undelayed
-  // tasks. |flush_callback| may be called back on any thread and should not
-  // perform a lot of work. May be used when additional work on the current
-  // thread needs to be performed during a flush. Only one
-  // FlushAsyncForTesting() may be pending at any given time.
-  virtual void FlushAsyncForTesting(OnceClosure flush_callback) = 0;
-
-  // Joins all threads. Tasks that are already running are allowed to complete
-  // their execution. This can only be called once. Using this task scheduler
-  // instance to create task runners or post tasks is not permitted during or
-  // after this call.
-  virtual void JoinForTesting() = 0;
-
-// CreateAndStartWithDefaultParams(), Create(), and SetInstance() register a
-// TaskScheduler to handle tasks posted through the post_task.h API for this
-// process.
-//
-// Processes that need to initialize TaskScheduler with custom params or that
-// need to allow tasks to be posted before the TaskScheduler creates its
-// threads should use Create() followed by Start(). Other processes can use
-// CreateAndStartWithDefaultParams().
-//
-// A registered TaskScheduler is only deleted when a new TaskScheduler is
-// registered. The last registered TaskScheduler is leaked on shutdown. The
-// methods below must not be called when TaskRunners created by a previous
-// TaskScheduler are still alive. The methods are not thread-safe; proper
-// synchronization is required to use the post_task.h API after registering a
-// new TaskScheduler.
-
-#if !defined(OS_NACL)
-  // Creates and starts a task scheduler using default params. |name| is used to
-  // label histograms, it must not be empty. It should identify the component
-  // that calls this. Start() is called by this method; it is invalid to call it
-  // again afterwards. CHECKs on failure. For tests, prefer
-  // base::test::ScopedTaskEnvironment (ensures isolation).
-  static void CreateAndStartWithDefaultParams(StringPiece name);
-
-  // Same as CreateAndStartWithDefaultParams() but allows callers to split the
-  // Create() and StartWithDefaultParams() calls.
-  void StartWithDefaultParams();
-#endif  // !defined(OS_NACL)
-
-  // Creates a ready to start task scheduler. |name| is used to label
-  // histograms, it must not be empty. It should identify the component that
-  // creates the TaskScheduler. The task scheduler doesn't create threads until
-  // Start() is called. Tasks can be posted at any time but will not run until
-  // after Start() is called. For tests, prefer
-  // base::test::ScopedTaskEnvironment (ensures isolation).
-  static void Create(StringPiece name);
-
-  // Registers |task_scheduler| to handle tasks posted through the post_task.h
-  // API for this process. For tests, prefer base::test::ScopedTaskEnvironment
-  // (ensures isolation).
-  static void SetInstance(std::unique_ptr<TaskScheduler> task_scheduler);
-
-  // Retrieve the TaskScheduler set via SetInstance() or
-  // CreateAndSet(Simple|Default)TaskScheduler(). This should be used very
-  // rarely; most users of TaskScheduler should use the post_task.h API. In
-  // particular, refrain from doing
-  //   if (!TaskScheduler::GetInstance()) {
-  //     TaskScheduler::SetInstance(...);
-  //     base::PostTask(...);
-  //   }
-  // instead make sure to SetInstance() early in one determinstic place in the
-  // process' initialization phase.
-  // In doubt, consult with //base/task_scheduler/OWNERS.
-  static TaskScheduler* GetInstance();
-
- private:
-  friend class gin::V8Platform;
-  friend class content::BrowserMainLoopTest_CreateThreadsInSingleProcess_Test;
-
-  // Returns the maximum number of non-single-threaded non-blocked tasks posted
-  // with |traits| that can run concurrently in this TaskScheduler.
-  //
-  // Do not use this method. To process n items, post n tasks that each process
-  // 1 item rather than GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated()
-  // tasks that each process
-  // n/GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated() items.
-  //
-  // TODO(fdoray): Remove this method. https://crbug.com/687264
-  virtual int GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated(
-      const TaskTraits& traits) const = 0;
-};
-
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_TASK_SCHEDULER_H_
diff --git a/base/task_scheduler/task_scheduler_impl.cc b/base/task_scheduler/task_scheduler_impl.cc
deleted file mode 100644
index 88250c2..0000000
--- a/base/task_scheduler/task_scheduler_impl.cc
+++ /dev/null
@@ -1,216 +0,0 @@
-// Copyright 2016 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/task_scheduler/task_scheduler_impl.h"
-
-#include <string>
-#include <utility>
-
-#include "base/compiler_specific.h"
-#include "base/message_loop/message_loop.h"
-#include "base/strings/string_util.h"
-#include "base/task_scheduler/delayed_task_manager.h"
-#include "base/task_scheduler/environment_config.h"
-#include "base/task_scheduler/scheduler_worker_pool_params.h"
-#include "base/task_scheduler/sequence.h"
-#include "base/task_scheduler/sequence_sort_key.h"
-#include "base/task_scheduler/service_thread.h"
-#include "base/task_scheduler/task.h"
-#include "base/task_scheduler/task_tracker.h"
-#include "base/time/time.h"
-
-namespace base {
-namespace internal {
-
-TaskSchedulerImpl::TaskSchedulerImpl(StringPiece histogram_label)
-    : TaskSchedulerImpl(histogram_label,
-                        std::make_unique<TaskTrackerImpl>(histogram_label)) {}
-
-TaskSchedulerImpl::TaskSchedulerImpl(
-    StringPiece histogram_label,
-    std::unique_ptr<TaskTrackerImpl> task_tracker)
-    : task_tracker_(std::move(task_tracker)),
-      service_thread_(std::make_unique<ServiceThread>()),
-      single_thread_task_runner_manager_(task_tracker_->GetTrackedRef(),
-                                         &delayed_task_manager_) {
-  DCHECK(!histogram_label.empty());
-
-  static_assert(arraysize(worker_pools_) == ENVIRONMENT_COUNT,
-                "The size of |worker_pools_| must match ENVIRONMENT_COUNT.");
-  static_assert(
-      arraysize(kEnvironmentParams) == ENVIRONMENT_COUNT,
-      "The size of |kEnvironmentParams| must match ENVIRONMENT_COUNT.");
-
-  for (int environment_type = 0; environment_type < ENVIRONMENT_COUNT;
-       ++environment_type) {
-    worker_pools_[environment_type] = std::make_unique<SchedulerWorkerPoolImpl>(
-        JoinString(
-            {histogram_label, kEnvironmentParams[environment_type].name_suffix},
-            "."),
-        kEnvironmentParams[environment_type].name_suffix,
-        kEnvironmentParams[environment_type].priority_hint,
-        task_tracker_->GetTrackedRef(), &delayed_task_manager_);
-  }
-}
-
-TaskSchedulerImpl::~TaskSchedulerImpl() {
-#if DCHECK_IS_ON()
-  DCHECK(join_for_testing_returned_.IsSet());
-#endif
-}
-
-void TaskSchedulerImpl::Start(
-    const TaskScheduler::InitParams& init_params,
-    SchedulerWorkerObserver* scheduler_worker_observer) {
-  // Start the service thread. On platforms that support it (POSIX except NaCL
-  // SFI), the service thread runs a MessageLoopForIO which is used to support
-  // FileDescriptorWatcher in the scope in which tasks run.
-  ServiceThread::Options service_thread_options;
-  service_thread_options.message_loop_type =
-#if defined(OS_POSIX) && !defined(OS_NACL_SFI)
-      MessageLoop::TYPE_IO;
-#else
-      MessageLoop::TYPE_DEFAULT;
-#endif
-  service_thread_options.timer_slack = TIMER_SLACK_MAXIMUM;
-  CHECK(service_thread_->StartWithOptions(service_thread_options));
-
-#if defined(OS_POSIX) && !defined(OS_NACL_SFI)
-  // Needs to happen after starting the service thread to get its
-  // message_loop().
-  task_tracker_->set_watch_file_descriptor_message_loop(
-      static_cast<MessageLoopForIO*>(service_thread_->message_loop()));
-
-#if DCHECK_IS_ON()
-  task_tracker_->set_service_thread_handle(service_thread_->GetThreadHandle());
-#endif  // DCHECK_IS_ON()
-#endif  // defined(OS_POSIX) && !defined(OS_NACL_SFI)
-
-  // Needs to happen after starting the service thread to get its task_runner().
-  scoped_refptr<TaskRunner> service_thread_task_runner =
-      service_thread_->task_runner();
-  delayed_task_manager_.Start(service_thread_task_runner);
-
-  single_thread_task_runner_manager_.Start(scheduler_worker_observer);
-
-  const SchedulerWorkerPoolImpl::WorkerEnvironment worker_environment =
-#if defined(OS_WIN)
-      init_params.shared_worker_pool_environment ==
-              InitParams::SharedWorkerPoolEnvironment::COM_MTA
-          ? SchedulerWorkerPoolImpl::WorkerEnvironment::COM_MTA
-          : SchedulerWorkerPoolImpl::WorkerEnvironment::NONE;
-#else
-      SchedulerWorkerPoolImpl::WorkerEnvironment::NONE;
-#endif
-
-  worker_pools_[BACKGROUND]->Start(
-      init_params.background_worker_pool_params, service_thread_task_runner,
-      scheduler_worker_observer, worker_environment);
-  worker_pools_[BACKGROUND_BLOCKING]->Start(
-      init_params.background_blocking_worker_pool_params,
-      service_thread_task_runner, scheduler_worker_observer,
-      worker_environment);
-  worker_pools_[FOREGROUND]->Start(
-      init_params.foreground_worker_pool_params, service_thread_task_runner,
-      scheduler_worker_observer, worker_environment);
-  worker_pools_[FOREGROUND_BLOCKING]->Start(
-      init_params.foreground_blocking_worker_pool_params,
-      service_thread_task_runner, scheduler_worker_observer,
-      worker_environment);
-}
-
-void TaskSchedulerImpl::PostDelayedTaskWithTraits(const Location& from_here,
-                                                  const TaskTraits& traits,
-                                                  OnceClosure task,
-                                                  TimeDelta delay) {
-  // Post |task| as part of a one-off single-task Sequence.
-  const TaskTraits new_traits = SetUserBlockingPriorityIfNeeded(traits);
-  GetWorkerPoolForTraits(new_traits)
-      ->PostTaskWithSequence(
-          Task(from_here, std::move(task), new_traits, delay),
-          MakeRefCounted<Sequence>());
-}
-
-scoped_refptr<TaskRunner> TaskSchedulerImpl::CreateTaskRunnerWithTraits(
-    const TaskTraits& traits) {
-  const TaskTraits new_traits = SetUserBlockingPriorityIfNeeded(traits);
-  return GetWorkerPoolForTraits(new_traits)
-      ->CreateTaskRunnerWithTraits(new_traits);
-}
-
-scoped_refptr<SequencedTaskRunner>
-TaskSchedulerImpl::CreateSequencedTaskRunnerWithTraits(
-    const TaskTraits& traits) {
-  const TaskTraits new_traits = SetUserBlockingPriorityIfNeeded(traits);
-  return GetWorkerPoolForTraits(new_traits)
-      ->CreateSequencedTaskRunnerWithTraits(new_traits);
-}
-
-scoped_refptr<SingleThreadTaskRunner>
-TaskSchedulerImpl::CreateSingleThreadTaskRunnerWithTraits(
-    const TaskTraits& traits,
-    SingleThreadTaskRunnerThreadMode thread_mode) {
-  return single_thread_task_runner_manager_
-      .CreateSingleThreadTaskRunnerWithTraits(
-          SetUserBlockingPriorityIfNeeded(traits), thread_mode);
-}
-
-#if defined(OS_WIN)
-scoped_refptr<SingleThreadTaskRunner>
-TaskSchedulerImpl::CreateCOMSTATaskRunnerWithTraits(
-    const TaskTraits& traits,
-    SingleThreadTaskRunnerThreadMode thread_mode) {
-  return single_thread_task_runner_manager_.CreateCOMSTATaskRunnerWithTraits(
-      SetUserBlockingPriorityIfNeeded(traits), thread_mode);
-}
-#endif  // defined(OS_WIN)
-
-int TaskSchedulerImpl::GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated(
-    const TaskTraits& traits) const {
-  return GetWorkerPoolForTraits(traits)
-      ->GetMaxConcurrentNonBlockedTasksDeprecated();
-}
-
-void TaskSchedulerImpl::Shutdown() {
-  // TODO(fdoray): Increase the priority of BACKGROUND tasks blocking shutdown.
-  task_tracker_->Shutdown();
-}
-
-void TaskSchedulerImpl::FlushForTesting() {
-  task_tracker_->FlushForTesting();
-}
-
-void TaskSchedulerImpl::FlushAsyncForTesting(OnceClosure flush_callback) {
-  task_tracker_->FlushAsyncForTesting(std::move(flush_callback));
-}
-
-void TaskSchedulerImpl::JoinForTesting() {
-#if DCHECK_IS_ON()
-  DCHECK(!join_for_testing_returned_.IsSet());
-#endif
-  // The service thread must be stopped before the workers are joined, otherwise
-  // tasks scheduled by the DelayedTaskManager might be posted between joining
-  // those workers and stopping the service thread which will cause a CHECK. See
-  // https://crbug.com/771701.
-  service_thread_->Stop();
-  single_thread_task_runner_manager_.JoinForTesting();
-  for (const auto& worker_pool : worker_pools_)
-    worker_pool->JoinForTesting();
-#if DCHECK_IS_ON()
-  join_for_testing_returned_.Set();
-#endif
-}
-
-SchedulerWorkerPoolImpl* TaskSchedulerImpl::GetWorkerPoolForTraits(
-    const TaskTraits& traits) const {
-  return worker_pools_[GetEnvironmentIndexForTraits(traits)].get();
-}
-
-TaskTraits TaskSchedulerImpl::SetUserBlockingPriorityIfNeeded(
-    const TaskTraits& traits) const {
-  return traits;
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/task_scheduler_impl.h b/base/task_scheduler/task_scheduler_impl.h
deleted file mode 100644
index f409dc5..0000000
--- a/base/task_scheduler/task_scheduler_impl.h
+++ /dev/null
@@ -1,123 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_TASK_SCHEDULER_IMPL_H_
-#define BASE_TASK_SCHEDULER_TASK_SCHEDULER_IMPL_H_
-
-#include <memory>
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/memory/ref_counted.h"
-#include "base/strings/string_piece.h"
-#include "base/synchronization/atomic_flag.h"
-#include "base/task_scheduler/delayed_task_manager.h"
-#include "base/task_scheduler/scheduler_single_thread_task_runner_manager.h"
-#include "base/task_scheduler/scheduler_worker_pool_impl.h"
-#include "base/task_scheduler/single_thread_task_runner_thread_mode.h"
-#include "base/task_scheduler/task_scheduler.h"
-#include "base/task_scheduler/task_tracker.h"
-#include "base/task_scheduler/task_traits.h"
-#include "build_config.h"
-
-#if defined(OS_POSIX) && !defined(OS_NACL_SFI)
-#include "base/task_scheduler/task_tracker_posix.h"
-#endif
-
-#if defined(OS_WIN)
-#include "base/win/com_init_check_hook.h"
-#endif
-
-namespace base {
-
-class HistogramBase;
-class Thread;
-
-namespace internal {
-
-// Default TaskScheduler implementation. This class is thread-safe.
-class BASE_EXPORT TaskSchedulerImpl : public TaskScheduler {
- public:
-  using TaskTrackerImpl =
-#if defined(OS_POSIX) && !defined(OS_NACL_SFI)
-      TaskTrackerPosix;
-#else
-      TaskTracker;
-#endif
-
-  // Creates a TaskSchedulerImpl with a production TaskTracker.
-  //|histogram_label| is used to label histograms, it must not be empty.
-  explicit TaskSchedulerImpl(StringPiece histogram_label);
-
-  // For testing only. Creates a TaskSchedulerImpl with a custom TaskTracker.
-  TaskSchedulerImpl(StringPiece histogram_label,
-                    std::unique_ptr<TaskTrackerImpl> task_tracker);
-
-  ~TaskSchedulerImpl() override;
-
-  // TaskScheduler:
-  void Start(const TaskScheduler::InitParams& init_params,
-             SchedulerWorkerObserver* scheduler_worker_observer) override;
-  void PostDelayedTaskWithTraits(const Location& from_here,
-                                 const TaskTraits& traits,
-                                 OnceClosure task,
-                                 TimeDelta delay) override;
-  scoped_refptr<TaskRunner> CreateTaskRunnerWithTraits(
-      const TaskTraits& traits) override;
-  scoped_refptr<SequencedTaskRunner> CreateSequencedTaskRunnerWithTraits(
-      const TaskTraits& traits) override;
-  scoped_refptr<SingleThreadTaskRunner> CreateSingleThreadTaskRunnerWithTraits(
-      const TaskTraits& traits,
-      SingleThreadTaskRunnerThreadMode thread_mode) override;
-#if defined(OS_WIN)
-  scoped_refptr<SingleThreadTaskRunner> CreateCOMSTATaskRunnerWithTraits(
-      const TaskTraits& traits,
-      SingleThreadTaskRunnerThreadMode thread_mode) override;
-#endif  // defined(OS_WIN)
-  int GetMaxConcurrentNonBlockedTasksWithTraitsDeprecated(
-      const TaskTraits& traits) const override;
-  void Shutdown() override;
-  void FlushForTesting() override;
-  void FlushAsyncForTesting(OnceClosure flush_callback) override;
-  void JoinForTesting() override;
-
- private:
-  // Returns the worker pool that runs Tasks with |traits|.
-  SchedulerWorkerPoolImpl* GetWorkerPoolForTraits(
-      const TaskTraits& traits) const;
-
-  // Returns |traits|, with priority set to TaskPriority::USER_BLOCKING if
-  // |all_tasks_user_blocking_| is set.
-  TaskTraits SetUserBlockingPriorityIfNeeded(const TaskTraits& traits) const;
-
-  const std::unique_ptr<TaskTrackerImpl> task_tracker_;
-  std::unique_ptr<Thread> service_thread_;
-  DelayedTaskManager delayed_task_manager_;
-  SchedulerSingleThreadTaskRunnerManager single_thread_task_runner_manager_;
-
-  // There are 4 SchedulerWorkerPoolImpl in this array to match the 4
-  // SchedulerWorkerPoolParams in TaskScheduler::InitParams.
-  std::unique_ptr<SchedulerWorkerPoolImpl> worker_pools_[4];
-
-#if DCHECK_IS_ON()
-  // Set once JoinForTesting() has returned.
-  AtomicFlag join_for_testing_returned_;
-#endif
-
-#if defined(OS_WIN) && defined(COM_INIT_CHECK_HOOK_ENABLED)
-  // Provides COM initialization verification for supported builds.
-  base::win::ComInitCheckHook com_init_check_hook_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(TaskSchedulerImpl);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_TASK_SCHEDULER_IMPL_H_
diff --git a/base/task_scheduler/task_tracker.cc b/base/task_scheduler/task_tracker.cc
deleted file mode 100644
index 704aadd..0000000
--- a/base/task_scheduler/task_tracker.cc
+++ /dev/null
@@ -1,658 +0,0 @@
-// Copyright 2016 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/task_scheduler/task_tracker.h"
-
-#include <limits>
-#include <string>
-#include <vector>
-
-#include "base/base_switches.h"
-#include "base/callback.h"
-#include "base/command_line.h"
-#include "base/json/json_writer.h"
-#include "base/memory/ptr_util.h"
-#include "base/sequence_token.h"
-#include "base/strings/string_util.h"
-#include "base/synchronization/condition_variable.h"
-#include "base/task_scheduler/scoped_set_task_priority_for_current_thread.h"
-#include "base/threading/sequence_local_storage_map.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-#include "base/threading/thread_restrictions.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "base/time/time.h"
-#include "base/values.h"
-
-namespace base {
-namespace internal {
-
-namespace {
-
-constexpr char kParallelExecutionMode[] = "parallel";
-constexpr char kSequencedExecutionMode[] = "sequenced";
-constexpr char kSingleThreadExecutionMode[] = "single thread";
-
-// An immutable copy of a scheduler task's info required by tracing.
-class TaskTracingInfo {
- public:
-  TaskTracingInfo(const TaskTraits& task_traits,
-                  const char* execution_mode,
-                  const SequenceToken& sequence_token)
-      : task_traits_(task_traits),
-        execution_mode_(execution_mode),
-        sequence_token_(sequence_token) {}
-
- private:
-  const TaskTraits task_traits_;
-  const char* const execution_mode_;
-  const SequenceToken sequence_token_;
-
-  DISALLOW_COPY_AND_ASSIGN(TaskTracingInfo);
-};
-
-// Returns the maximum number of TaskPriority::BACKGROUND sequences that can be
-// scheduled concurrently based on command line flags.
-int GetMaxNumScheduledBackgroundSequences() {
-  // The CommandLine might not be initialized if TaskScheduler is initialized
-  // in a dynamic library which doesn't have access to argc/argv.
-  if (CommandLine::InitializedForCurrentProcess() &&
-      CommandLine::ForCurrentProcess()->HasSwitch(
-          switches::kDisableBackgroundTasks)) {
-    return 0;
-  }
-  return std::numeric_limits<int>::max();
-}
-
-}  // namespace
-
-// Atomic internal state used by TaskTracker. Sequential consistency shouldn't
-// be assumed from these calls (i.e. a thread reading
-// |HasShutdownStarted() == true| isn't guaranteed to see all writes made before
-// |StartShutdown()| on the thread that invoked it).
-class TaskTracker::State {
- public:
-  State() = default;
-
-  // Sets a flag indicating that shutdown has started. Returns true if there are
-  // tasks blocking shutdown. Can only be called once.
-  bool StartShutdown() {
-    const auto new_value =
-        subtle::NoBarrier_AtomicIncrement(&bits_, kShutdownHasStartedMask);
-
-    // Check that the "shutdown has started" bit isn't zero. This would happen
-    // if it was incremented twice.
-    DCHECK(new_value & kShutdownHasStartedMask);
-
-    const auto num_tasks_blocking_shutdown =
-        new_value >> kNumTasksBlockingShutdownBitOffset;
-    return num_tasks_blocking_shutdown != 0;
-  }
-
-  // Returns true if shutdown has started.
-  bool HasShutdownStarted() const {
-    return subtle::NoBarrier_Load(&bits_) & kShutdownHasStartedMask;
-  }
-
-  // Returns true if there are tasks blocking shutdown.
-  bool AreTasksBlockingShutdown() const {
-    const auto num_tasks_blocking_shutdown =
-        subtle::NoBarrier_Load(&bits_) >> kNumTasksBlockingShutdownBitOffset;
-    DCHECK_GE(num_tasks_blocking_shutdown, 0);
-    return num_tasks_blocking_shutdown != 0;
-  }
-
-  // Increments the number of tasks blocking shutdown. Returns true if shutdown
-  // has started.
-  bool IncrementNumTasksBlockingShutdown() {
-#if DCHECK_IS_ON()
-    // Verify that no overflow will occur.
-    const auto num_tasks_blocking_shutdown =
-        subtle::NoBarrier_Load(&bits_) >> kNumTasksBlockingShutdownBitOffset;
-    DCHECK_LT(num_tasks_blocking_shutdown,
-              std::numeric_limits<subtle::Atomic32>::max() -
-                  kNumTasksBlockingShutdownIncrement);
-#endif
-
-    const auto new_bits = subtle::NoBarrier_AtomicIncrement(
-        &bits_, kNumTasksBlockingShutdownIncrement);
-    return new_bits & kShutdownHasStartedMask;
-  }
-
-  // Decrements the number of tasks blocking shutdown. Returns true if shutdown
-  // has started and the number of tasks blocking shutdown becomes zero.
-  bool DecrementNumTasksBlockingShutdown() {
-    const auto new_bits = subtle::NoBarrier_AtomicIncrement(
-        &bits_, -kNumTasksBlockingShutdownIncrement);
-    const bool shutdown_has_started = new_bits & kShutdownHasStartedMask;
-    const auto num_tasks_blocking_shutdown =
-        new_bits >> kNumTasksBlockingShutdownBitOffset;
-    DCHECK_GE(num_tasks_blocking_shutdown, 0);
-    return shutdown_has_started && num_tasks_blocking_shutdown == 0;
-  }
-
- private:
-  static constexpr subtle::Atomic32 kShutdownHasStartedMask = 1;
-  static constexpr subtle::Atomic32 kNumTasksBlockingShutdownBitOffset = 1;
-  static constexpr subtle::Atomic32 kNumTasksBlockingShutdownIncrement =
-      1 << kNumTasksBlockingShutdownBitOffset;
-
-  // The LSB indicates whether shutdown has started. The other bits count the
-  // number of tasks blocking shutdown.
-  // No barriers are required to read/write |bits_| as this class is only used
-  // as an atomic state checker, it doesn't provide sequential consistency
-  // guarantees w.r.t. external state. Sequencing of the TaskTracker::State
-  // operations themselves is guaranteed by the AtomicIncrement RMW (read-
-  // modify-write) semantics however. For example, if two threads are racing to
-  // call IncrementNumTasksBlockingShutdown() and StartShutdown() respectively,
-  // either the first thread will win and the StartShutdown() call will see the
-  // blocking task or the second thread will win and
-  // IncrementNumTasksBlockingShutdown() will know that shutdown has started.
-  subtle::Atomic32 bits_ = 0;
-
-  DISALLOW_COPY_AND_ASSIGN(State);
-};
-
-struct TaskTracker::PreemptedBackgroundSequence {
-  PreemptedBackgroundSequence() = default;
-  PreemptedBackgroundSequence(scoped_refptr<Sequence> sequence_in,
-                              TimeTicks next_task_sequenced_time_in,
-                              CanScheduleSequenceObserver* observer_in)
-      : sequence(std::move(sequence_in)),
-        next_task_sequenced_time(next_task_sequenced_time_in),
-        observer(observer_in) {}
-  PreemptedBackgroundSequence(PreemptedBackgroundSequence&& other) = default;
-  ~PreemptedBackgroundSequence() = default;
-  PreemptedBackgroundSequence& operator=(PreemptedBackgroundSequence&& other) =
-      default;
-  bool operator<(const PreemptedBackgroundSequence& other) const {
-    return next_task_sequenced_time < other.next_task_sequenced_time;
-  }
-  bool operator>(const PreemptedBackgroundSequence& other) const {
-    return next_task_sequenced_time > other.next_task_sequenced_time;
-  }
-
-  // A background sequence waiting to be scheduled.
-  scoped_refptr<Sequence> sequence;
-
-  // The sequenced time of the next task in |sequence|.
-  TimeTicks next_task_sequenced_time;
-
-  // An observer to notify when |sequence| can be scheduled.
-  CanScheduleSequenceObserver* observer = nullptr;
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(PreemptedBackgroundSequence);
-};
-
-TaskTracker::TaskTracker(StringPiece histogram_label)
-    : TaskTracker(histogram_label, GetMaxNumScheduledBackgroundSequences()) {}
-
-TaskTracker::TaskTracker(StringPiece histogram_label,
-                         int max_num_scheduled_background_sequences)
-    : state_(new State),
-      flush_cv_(flush_lock_.CreateConditionVariable()),
-      shutdown_lock_(&flush_lock_),
-      max_num_scheduled_background_sequences_(
-          max_num_scheduled_background_sequences),
-      tracked_ref_factory_(this) {
-}
-
-TaskTracker::~TaskTracker() = default;
-
-void TaskTracker::Shutdown() {
-  PerformShutdown();
-  DCHECK(IsShutdownComplete());
-
-  // Unblock FlushForTesting() and perform the FlushAsyncForTesting callback
-  // when shutdown completes.
-  {
-    AutoSchedulerLock auto_lock(flush_lock_);
-    flush_cv_->Signal();
-  }
-  CallFlushCallbackForTesting();
-}
-
-void TaskTracker::FlushForTesting() {
-  AutoSchedulerLock auto_lock(flush_lock_);
-  while (subtle::Acquire_Load(&num_incomplete_undelayed_tasks_) != 0 &&
-         !IsShutdownComplete()) {
-    flush_cv_->Wait();
-  }
-}
-
-void TaskTracker::FlushAsyncForTesting(OnceClosure flush_callback) {
-  DCHECK(flush_callback);
-  {
-    AutoSchedulerLock auto_lock(flush_lock_);
-    DCHECK(!flush_callback_for_testing_)
-        << "Only one FlushAsyncForTesting() may be pending at any time.";
-    flush_callback_for_testing_ = std::move(flush_callback);
-  }
-
-  if (subtle::Acquire_Load(&num_incomplete_undelayed_tasks_) == 0 ||
-      IsShutdownComplete()) {
-    CallFlushCallbackForTesting();
-  }
-}
-
-bool TaskTracker::WillPostTask(const Task& task) {
-  DCHECK(task.task);
-
-  if (!BeforePostTask(task.traits.shutdown_behavior()))
-    return false;
-
-  if (task.delayed_run_time.is_null())
-    subtle::NoBarrier_AtomicIncrement(&num_incomplete_undelayed_tasks_, 1);
-
-  return true;
-}
-
-scoped_refptr<Sequence> TaskTracker::WillScheduleSequence(
-    scoped_refptr<Sequence> sequence,
-    CanScheduleSequenceObserver* observer) {
-  const SequenceSortKey sort_key = sequence->GetSortKey();
-
-  // A foreground sequence can always be scheduled.
-  if (sort_key.priority() != TaskPriority::BACKGROUND)
-    return sequence;
-
-  // It is convenient not to have to specify an observer when scheduling
-  // foreground sequences in tests.
-  DCHECK(observer);
-
-  AutoSchedulerLock auto_lock(background_lock_);
-
-  if (num_scheduled_background_sequences_ <
-      max_num_scheduled_background_sequences_) {
-    ++num_scheduled_background_sequences_;
-    return sequence;
-  }
-
-  preempted_background_sequences_.emplace(
-      std::move(sequence), sort_key.next_task_sequenced_time(), observer);
-  return nullptr;
-}
-
-scoped_refptr<Sequence> TaskTracker::RunAndPopNextTask(
-    scoped_refptr<Sequence> sequence,
-    CanScheduleSequenceObserver* observer) {
-  DCHECK(sequence);
-
-  // Run the next task in |sequence|.
-  Optional<Task> task = sequence->TakeTask();
-  // TODO(fdoray): Support TakeTask() returning null. https://crbug.com/783309
-  DCHECK(task);
-
-  const TaskShutdownBehavior shutdown_behavior =
-      task->traits.shutdown_behavior();
-  const TaskPriority task_priority = task->traits.priority();
-  const bool can_run_task = BeforeRunTask(shutdown_behavior);
-  const bool is_delayed = !task->delayed_run_time.is_null();
-
-  RunOrSkipTask(std::move(task.value()), sequence.get(), can_run_task);
-  if (can_run_task)
-    AfterRunTask(shutdown_behavior);
-
-  if (!is_delayed)
-    DecrementNumIncompleteUndelayedTasks();
-
-  const bool sequence_is_empty_after_pop = sequence->Pop();
-
-  // Never reschedule a Sequence emptied by Pop(). The contract is such that
-  // next poster to make it non-empty is responsible to schedule it.
-  if (sequence_is_empty_after_pop)
-    sequence = nullptr;
-
-  if (task_priority == TaskPriority::BACKGROUND) {
-    // Allow |sequence| to be rescheduled only if its next task is set to run
-    // earlier than the earliest currently preempted sequence
-    return ManageBackgroundSequencesAfterRunningTask(std::move(sequence),
-                                                     observer);
-  }
-
-  return sequence;
-}
-
-bool TaskTracker::HasShutdownStarted() const {
-  return state_->HasShutdownStarted();
-}
-
-bool TaskTracker::IsShutdownComplete() const {
-  AutoSchedulerLock auto_lock(shutdown_lock_);
-  return shutdown_event_ && shutdown_event_->IsSignaled();
-}
-
-void TaskTracker::SetHasShutdownStartedForTesting() {
-  AutoSchedulerLock auto_lock(shutdown_lock_);
-
-  // Create a dummy |shutdown_event_| to satisfy TaskTracker's expectation of
-  // its existence during shutdown (e.g. in OnBlockingShutdownTasksComplete()).
-  shutdown_event_.reset(
-      new WaitableEvent(WaitableEvent::ResetPolicy::MANUAL,
-                        WaitableEvent::InitialState::NOT_SIGNALED));
-
-  state_->StartShutdown();
-}
-
-void TaskTracker::RunOrSkipTask(Task task,
-                                Sequence* sequence,
-                                bool can_run_task) {
-  const bool previous_singleton_allowed =
-      ThreadRestrictions::SetSingletonAllowed(
-          task.traits.shutdown_behavior() !=
-          TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN);
-  const bool previous_io_allowed =
-      ThreadRestrictions::SetIOAllowed(task.traits.may_block());
-  const bool previous_wait_allowed = ThreadRestrictions::SetWaitAllowed(
-      task.traits.with_base_sync_primitives());
-
-  {
-    const SequenceToken& sequence_token = sequence->token();
-    DCHECK(sequence_token.IsValid());
-    ScopedSetSequenceTokenForCurrentThread
-        scoped_set_sequence_token_for_current_thread(sequence_token);
-    ScopedSetTaskPriorityForCurrentThread
-        scoped_set_task_priority_for_current_thread(task.traits.priority());
-    ScopedSetSequenceLocalStorageMapForCurrentThread
-        scoped_set_sequence_local_storage_map_for_current_thread(
-            sequence->sequence_local_storage());
-
-    // Set up TaskRunnerHandle as expected for the scope of the task.
-    std::unique_ptr<SequencedTaskRunnerHandle> sequenced_task_runner_handle;
-    std::unique_ptr<ThreadTaskRunnerHandle> single_thread_task_runner_handle;
-    DCHECK(!task.sequenced_task_runner_ref ||
-           !task.single_thread_task_runner_ref);
-    if (task.sequenced_task_runner_ref) {
-      sequenced_task_runner_handle.reset(
-          new SequencedTaskRunnerHandle(task.sequenced_task_runner_ref));
-    } else if (task.single_thread_task_runner_ref) {
-      single_thread_task_runner_handle.reset(
-          new ThreadTaskRunnerHandle(task.single_thread_task_runner_ref));
-    }
-
-    if (can_run_task) {
-      std::move(task.task).Run();
-    }
-
-    // Make sure the arguments bound to the callback are deleted within the
-    // scope in which the callback runs.
-    task.task = OnceClosure();
-  }
-
-  ThreadRestrictions::SetWaitAllowed(previous_wait_allowed);
-  ThreadRestrictions::SetIOAllowed(previous_io_allowed);
-  ThreadRestrictions::SetSingletonAllowed(previous_singleton_allowed);
-}
-
-void TaskTracker::PerformShutdown() {
-  {
-    AutoSchedulerLock auto_lock(shutdown_lock_);
-
-    // This method can only be called once.
-    DCHECK(!shutdown_event_);
-    DCHECK(!state_->HasShutdownStarted());
-
-    shutdown_event_.reset(
-        new WaitableEvent(WaitableEvent::ResetPolicy::MANUAL,
-                          WaitableEvent::InitialState::NOT_SIGNALED));
-
-    const bool tasks_are_blocking_shutdown = state_->StartShutdown();
-
-    // From now, if a thread causes the number of tasks blocking shutdown to
-    // become zero, it will call OnBlockingShutdownTasksComplete().
-
-    if (!tasks_are_blocking_shutdown) {
-      // If another thread posts a BLOCK_SHUTDOWN task at this moment, it will
-      // block until this method releases |shutdown_lock_|. Then, it will fail
-      // DCHECK(!shutdown_event_->IsSignaled()). This is the desired behavior
-      // because posting a BLOCK_SHUTDOWN task when TaskTracker::Shutdown() has
-      // started and no tasks are blocking shutdown isn't allowed.
-      shutdown_event_->Signal();
-      return;
-    }
-  }
-
-  // Remove the cap on the maximum number of background sequences that can be
-  // scheduled concurrently. Done after starting shutdown to ensure that non-
-  // BLOCK_SHUTDOWN sequences don't get a chance to run and that BLOCK_SHUTDOWN
-  // sequences run on threads running with a normal priority.
-  SetMaxNumScheduledBackgroundSequences(std::numeric_limits<int>::max());
-
-  // It is safe to access |shutdown_event_| without holding |lock_| because the
-  // pointer never changes after being set above.
-  {
-    base::ThreadRestrictions::ScopedAllowWait allow_wait;
-    shutdown_event_->Wait();
-  }
-}
-
-void TaskTracker::SetMaxNumScheduledBackgroundSequences(
-    int max_num_scheduled_background_sequences) {
-  std::vector<PreemptedBackgroundSequence> sequences_to_schedule;
-
-  {
-    AutoSchedulerLock auto_lock(background_lock_);
-    max_num_scheduled_background_sequences_ =
-        max_num_scheduled_background_sequences;
-
-    while (num_scheduled_background_sequences_ <
-               max_num_scheduled_background_sequences &&
-           !preempted_background_sequences_.empty()) {
-      sequences_to_schedule.push_back(
-          GetPreemptedBackgroundSequenceToScheduleLockRequired());
-    }
-  }
-
-  for (auto& sequence_to_schedule : sequences_to_schedule)
-    SchedulePreemptedBackgroundSequence(std::move(sequence_to_schedule));
-}
-
-TaskTracker::PreemptedBackgroundSequence
-TaskTracker::GetPreemptedBackgroundSequenceToScheduleLockRequired() {
-  background_lock_.AssertAcquired();
-  DCHECK(!preempted_background_sequences_.empty());
-
-  ++num_scheduled_background_sequences_;
-  DCHECK_LE(num_scheduled_background_sequences_,
-            max_num_scheduled_background_sequences_);
-
-  // The const_cast on top is okay since the PreemptedBackgroundSequence is
-  // transactionnaly being popped from |preempted_background_sequences_| right
-  // after and the move doesn't alter the sort order (a requirement for the
-  // Windows STL's consistency debug-checks for std::priority_queue::top()).
-  PreemptedBackgroundSequence popped_sequence =
-      std::move(const_cast<PreemptedBackgroundSequence&>(
-          preempted_background_sequences_.top()));
-  preempted_background_sequences_.pop();
-  return popped_sequence;
-}
-
-void TaskTracker::SchedulePreemptedBackgroundSequence(
-    PreemptedBackgroundSequence sequence_to_schedule) {
-  DCHECK(sequence_to_schedule.observer);
-  sequence_to_schedule.observer->OnCanScheduleSequence(
-      std::move(sequence_to_schedule.sequence));
-}
-
-#if DCHECK_IS_ON()
-bool TaskTracker::IsPostingBlockShutdownTaskAfterShutdownAllowed() {
-  return false;
-}
-#endif
-
-bool TaskTracker::HasIncompleteUndelayedTasksForTesting() const {
-  return subtle::Acquire_Load(&num_incomplete_undelayed_tasks_) != 0;
-}
-
-bool TaskTracker::BeforePostTask(TaskShutdownBehavior shutdown_behavior) {
-  if (shutdown_behavior == TaskShutdownBehavior::BLOCK_SHUTDOWN) {
-    // BLOCK_SHUTDOWN tasks block shutdown between the moment they are posted
-    // and the moment they complete their execution.
-    const bool shutdown_started = state_->IncrementNumTasksBlockingShutdown();
-
-    if (shutdown_started) {
-      AutoSchedulerLock auto_lock(shutdown_lock_);
-
-      // A BLOCK_SHUTDOWN task posted after shutdown has completed is an
-      // ordering bug. This aims to catch those early.
-      DCHECK(shutdown_event_);
-      if (shutdown_event_->IsSignaled()) {
-#if DCHECK_IS_ON()
-// clang-format off
-        // TODO(robliao): http://crbug.com/698140. Since the service thread
-        // doesn't stop processing its own tasks at shutdown, we may still
-        // attempt to post a BLOCK_SHUTDOWN task in response to a
-        // FileDescriptorWatcher. Same is true for FilePathWatcher
-        // (http://crbug.com/728235). Until it's possible for such services to
-        // post to non-BLOCK_SHUTDOWN sequences which are themselves funneled to
-        // the main execution sequence (a future plan for the post_task.h API),
-        // this DCHECK will be flaky and must be disabled.
-        // DCHECK(IsPostingBlockShutdownTaskAfterShutdownAllowed());
-// clang-format on
-#endif
-        state_->DecrementNumTasksBlockingShutdown();
-        return false;
-      }
-    }
-
-    return true;
-  }
-
-  // A non BLOCK_SHUTDOWN task is allowed to be posted iff shutdown hasn't
-  // started.
-  return !state_->HasShutdownStarted();
-}
-
-bool TaskTracker::BeforeRunTask(TaskShutdownBehavior shutdown_behavior) {
-  switch (shutdown_behavior) {
-    case TaskShutdownBehavior::BLOCK_SHUTDOWN: {
-      // The number of tasks blocking shutdown has been incremented when the
-      // task was posted.
-      DCHECK(state_->AreTasksBlockingShutdown());
-
-      // Trying to run a BLOCK_SHUTDOWN task after shutdown has completed is
-      // unexpected as it either shouldn't have been posted if shutdown
-      // completed or should be blocking shutdown if it was posted before it
-      // did.
-      DCHECK(!state_->HasShutdownStarted() || !IsShutdownComplete());
-
-      return true;
-    }
-
-    case TaskShutdownBehavior::SKIP_ON_SHUTDOWN: {
-      // SKIP_ON_SHUTDOWN tasks block shutdown while they are running.
-      const bool shutdown_started = state_->IncrementNumTasksBlockingShutdown();
-
-      if (shutdown_started) {
-        // The SKIP_ON_SHUTDOWN task isn't allowed to run during shutdown.
-        // Decrement the number of tasks blocking shutdown that was wrongly
-        // incremented.
-        const bool shutdown_started_and_no_tasks_block_shutdown =
-            state_->DecrementNumTasksBlockingShutdown();
-        if (shutdown_started_and_no_tasks_block_shutdown)
-          OnBlockingShutdownTasksComplete();
-
-        return false;
-      }
-
-      return true;
-    }
-
-    case TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN: {
-      return !state_->HasShutdownStarted();
-    }
-  }
-
-  NOTREACHED();
-  return false;
-}
-
-void TaskTracker::AfterRunTask(TaskShutdownBehavior shutdown_behavior) {
-  if (shutdown_behavior == TaskShutdownBehavior::BLOCK_SHUTDOWN ||
-      shutdown_behavior == TaskShutdownBehavior::SKIP_ON_SHUTDOWN) {
-    const bool shutdown_started_and_no_tasks_block_shutdown =
-        state_->DecrementNumTasksBlockingShutdown();
-    if (shutdown_started_and_no_tasks_block_shutdown)
-      OnBlockingShutdownTasksComplete();
-  }
-}
-
-void TaskTracker::OnBlockingShutdownTasksComplete() {
-  AutoSchedulerLock auto_lock(shutdown_lock_);
-
-  // This method can only be called after shutdown has started.
-  DCHECK(state_->HasShutdownStarted());
-  DCHECK(shutdown_event_);
-
-  shutdown_event_->Signal();
-}
-
-void TaskTracker::DecrementNumIncompleteUndelayedTasks() {
-  const auto new_num_incomplete_undelayed_tasks =
-      subtle::Barrier_AtomicIncrement(&num_incomplete_undelayed_tasks_, -1);
-  DCHECK_GE(new_num_incomplete_undelayed_tasks, 0);
-  if (new_num_incomplete_undelayed_tasks == 0) {
-    {
-      AutoSchedulerLock auto_lock(flush_lock_);
-      flush_cv_->Signal();
-    }
-    CallFlushCallbackForTesting();
-  }
-}
-
-scoped_refptr<Sequence> TaskTracker::ManageBackgroundSequencesAfterRunningTask(
-    scoped_refptr<Sequence> just_ran_sequence,
-    CanScheduleSequenceObserver* observer) {
-  const TimeTicks next_task_sequenced_time =
-      just_ran_sequence
-          ? just_ran_sequence->GetSortKey().next_task_sequenced_time()
-          : TimeTicks();
-  PreemptedBackgroundSequence sequence_to_schedule;
-
-  {
-    AutoSchedulerLock auto_lock(background_lock_);
-
-    DCHECK(preempted_background_sequences_.empty() ||
-           num_scheduled_background_sequences_ ==
-               max_num_scheduled_background_sequences_);
-    --num_scheduled_background_sequences_;
-
-    if (just_ran_sequence) {
-      if (preempted_background_sequences_.empty() ||
-          preempted_background_sequences_.top().next_task_sequenced_time >
-              next_task_sequenced_time) {
-        ++num_scheduled_background_sequences_;
-        return just_ran_sequence;
-      }
-
-      preempted_background_sequences_.emplace(
-          std::move(just_ran_sequence), next_task_sequenced_time, observer);
-    }
-
-    if (!preempted_background_sequences_.empty()) {
-      sequence_to_schedule =
-          GetPreemptedBackgroundSequenceToScheduleLockRequired();
-    }
-  }
-
-  // |sequence_to_schedule.sequence| may be null if there was no preempted
-  // background sequence.
-  if (sequence_to_schedule.sequence)
-    SchedulePreemptedBackgroundSequence(std::move(sequence_to_schedule));
-
-  return nullptr;
-}
-
-void TaskTracker::CallFlushCallbackForTesting() {
-  OnceClosure flush_callback;
-  {
-    AutoSchedulerLock auto_lock(flush_lock_);
-    flush_callback = std::move(flush_callback_for_testing_);
-  }
-  if (flush_callback)
-    std::move(flush_callback).Run();
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/task_tracker.h b/base/task_scheduler/task_tracker.h
deleted file mode 100644
index 3240e3a..0000000
--- a/base/task_scheduler/task_tracker.h
+++ /dev/null
@@ -1,324 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_TASK_TRACKER_H_
-#define BASE_TASK_SCHEDULER_TASK_TRACKER_H_
-
-#include <functional>
-#include <memory>
-#include <queue>
-
-#include "base/atomicops.h"
-#include "base/base_export.h"
-#include "base/callback_forward.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/strings/string_piece.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/task_scheduler/can_schedule_sequence_observer.h"
-#include "base/task_scheduler/scheduler_lock.h"
-#include "base/task_scheduler/sequence.h"
-#include "base/task_scheduler/task.h"
-#include "base/task_scheduler/task_traits.h"
-#include "base/task_scheduler/tracked_ref.h"
-
-namespace base {
-
-class ConditionVariable;
-
-namespace internal {
-
-// TaskTracker enforces policies that determines whether:
-// - A task can be added to a sequence (WillPostTask).
-// - A sequence can be scheduled (WillScheduleSequence).
-// - The next task in a scheduled sequence can run (RunAndPopNextTask).
-// TaskTracker also sets up the environment to run a task (RunAndPopNextTask)
-// and records metrics and trace events. This class is thread-safe.
-//
-// Life of a sequence:
-// (possible states: IDLE, PREEMPTED, SCHEDULED, RUNNING)
-//
-//                            Create a sequence
-//                                   |
-//  ------------------------> Sequence is IDLE
-//  |                                |
-//  |                     Add a task to the sequence
-//  |            (allowed by TaskTracker::WillPostTask)
-//  |                                |
-//  |               TaskTracker:WillScheduleSequence
-//  |           _____________________|_____________________
-//  |           |                                          |
-//  |    Returns true                                Returns false
-//  |           |                                          |
-//  |           |                                Sequence is PREEMPTED <----
-//  |           |                                          |               |
-//  |           |                            Eventually,                   |
-//  |           |                            CanScheduleSequenceObserver   |
-//  |           |                            is notified that the          |
-//  |           |                            sequence can be scheduled.    |
-//  |           |__________________________________________|               |
-//  |                               |                                      |
-//  |                   (*) Sequence is SCHEDULED                          |
-//  |                               |                                      |
-//  |                A thread is ready to run the next                     |
-//  |                      task in the sequence                            |
-//  |                               |                                      |
-//  |                TaskTracker::RunAndPopNextTask                        |
-//  |                A task from the sequence is run                       |
-//  |                      Sequence is RUNNING                             |
-//  |                               |                                      |
-//  |         ______________________|____                                  |
-//  |         |                          |                                 |
-//  |   Sequence is empty      Sequence has more tasks                     |
-//  |_________|             _____________|_______________                  |
-//                          |                            |                 |
-//                   Sequence can be            Sequence cannot be         |
-//                   scheduled                  scheduled at this          |
-//                          |                   moment                     |
-//                   Go back to (*)                      |_________________|
-//
-//
-// Note: A background task is a task posted with TaskPriority::BACKGROUND. A
-// foreground task is a task posted with TaskPriority::USER_VISIBLE or
-// TaskPriority::USER_BLOCKING.
-class BASE_EXPORT TaskTracker {
- public:
-  // |histogram_label| is used as a suffix for histograms, it must not be empty.
-  // The first constructor sets the maximum number of TaskPriority::BACKGROUND
-  // sequences that can be scheduled concurrently to 0 if the
-  // --disable-background-tasks flag is specified, max() otherwise. The second
-  // constructor sets it to |max_num_scheduled_background_sequences|.
-  TaskTracker(StringPiece histogram_label);
-  TaskTracker(StringPiece histogram_label,
-              int max_num_scheduled_background_sequences);
-
-  virtual ~TaskTracker();
-
-  // Synchronously shuts down the scheduler. Once this is called, only tasks
-  // posted with the BLOCK_SHUTDOWN behavior will be run. Returns when:
-  // - All SKIP_ON_SHUTDOWN tasks that were already running have completed their
-  //   execution.
-  // - All posted BLOCK_SHUTDOWN tasks have completed their execution.
-  // CONTINUE_ON_SHUTDOWN tasks still may be running after Shutdown returns.
-  // This can only be called once.
-  void Shutdown();
-
-  // Waits until there are no incomplete undelayed tasks. May be called in tests
-  // to validate that a condition is met after all undelayed tasks have run.
-  //
-  // Does not wait for delayed tasks. Waits for undelayed tasks posted from
-  // other threads during the call. Returns immediately when shutdown completes.
-  void FlushForTesting();
-
-  // Returns and calls |flush_callback| when there are no incomplete undelayed
-  // tasks. |flush_callback| may be called back on any thread and should not
-  // perform a lot of work. May be used when additional work on the current
-  // thread needs to be performed during a flush. Only one
-  // FlushAsyncForTesting() may be pending at any given time.
-  void FlushAsyncForTesting(OnceClosure flush_callback);
-
-  // Informs this TaskTracker that |task| is about to be posted. Returns true if
-  // this operation is allowed (|task| should be posted if-and-only-if it is).
-  bool WillPostTask(const Task& task);
-
-  // Informs this TaskTracker that |sequence| is about to be scheduled. If this
-  // returns |sequence|, it is expected that RunAndPopNextTask() will soon be
-  // called with |sequence| as argument. Otherwise, RunAndPopNextTask() must not
-  // be called with |sequence| as argument until |observer| is notified that
-  // |sequence| can be scheduled (the caller doesn't need to keep a pointer to
-  // |sequence|; it will be included in the notification to |observer|).
-  // WillPostTask() must have allowed the task in front of |sequence| to be
-  // posted before this is called. |observer| is only required if the priority
-  // of |sequence| is TaskPriority::BACKGROUND
-  scoped_refptr<Sequence> WillScheduleSequence(
-      scoped_refptr<Sequence> sequence,
-      CanScheduleSequenceObserver* observer);
-
-  // Runs the next task in |sequence| unless the current shutdown state prevents
-  // that. Then, pops the task from |sequence| (even if it didn't run). Returns
-  // |sequence| if it can be rescheduled immediately. If |sequence| is non-empty
-  // after popping a task from it but it can't be rescheduled immediately, it
-  // will be handed back to |observer| when it can be rescheduled.
-  // WillPostTask() must have allowed the task in front of |sequence| to be
-  // posted before this is called. Also, WillScheduleSequence(),
-  // RunAndPopNextTask() or CanScheduleSequenceObserver::OnCanScheduleSequence()
-  // must have allowed |sequence| to be (re)scheduled.
-  scoped_refptr<Sequence> RunAndPopNextTask(
-      scoped_refptr<Sequence> sequence,
-      CanScheduleSequenceObserver* observer);
-
-  // Returns true once shutdown has started (Shutdown() has been called but
-  // might not have returned). Note: sequential consistency with the thread
-  // calling Shutdown() (or SetHasShutdownStartedForTesting()) isn't guaranteed
-  // by this call.
-  bool HasShutdownStarted() const;
-
-  // Returns true if shutdown has completed (Shutdown() has returned).
-  bool IsShutdownComplete() const;
-
-  // Causes HasShutdownStarted() to return true. Unlike when Shutdown() returns,
-  // IsShutdownComplete() won't return true after this returns. Shutdown()
-  // cannot be called after this.
-  void SetHasShutdownStartedForTesting();
-
-  TrackedRef<TaskTracker> GetTrackedRef() {
-    return tracked_ref_factory_.GetTrackedRef();
-  }
-
- protected:
-  // Runs and deletes |task| if |can_run_task| is true. Otherwise, just deletes
-  // |task|. |task| is always deleted in the environment where it runs or would
-  // have run. |sequence| is the sequence from which |task| was extracted. An
-  // override is expected to call its parent's implementation but is free to
-  // perform extra work before and after doing so.
-  virtual void RunOrSkipTask(Task task, Sequence* sequence, bool can_run_task);
-
-#if DCHECK_IS_ON()
-  // Returns true if this context should be exempt from blocking shutdown
-  // DCHECKs.
-  // TODO(robliao): Remove when http://crbug.com/698140 is fixed.
-  virtual bool IsPostingBlockShutdownTaskAfterShutdownAllowed();
-#endif
-
-  // Returns true if there are undelayed tasks that haven't completed their
-  // execution (still queued or in progress). If it returns false: the side-
-  // effects of all completed tasks are guaranteed to be visible to the caller.
-  bool HasIncompleteUndelayedTasksForTesting() const;
-
- private:
-  class State;
-  struct PreemptedBackgroundSequence;
-
-  void PerformShutdown();
-
-  // Updates the maximum number of background sequences that can be scheduled
-  // concurrently to |max_num_scheduled_background_sequences|. Then, schedules
-  // as many preempted background sequences as allowed by the new value.
-  void SetMaxNumScheduledBackgroundSequences(
-      int max_num_scheduled_background_sequences);
-
-  // Pops the next sequence in |preempted_background_sequences_| and increments
-  // |num_scheduled_background_sequences_|. Must only be called in the scope of
-  // |background_lock_|, with |preempted_background_sequences_| non-empty. The
-  // caller must forward the returned sequence to the associated
-  // CanScheduleSequenceObserver as soon as |background_lock_| is released.
-  PreemptedBackgroundSequence
-  GetPreemptedBackgroundSequenceToScheduleLockRequired();
-
-  // Schedules |sequence_to_schedule.sequence| using
-  // |sequence_to_schedule.observer|. Does not verify that the sequence is
-  // allowed to be scheduled.
-  void SchedulePreemptedBackgroundSequence(
-      PreemptedBackgroundSequence sequence_to_schedule);
-
-  // Called before WillPostTask() informs the tracing system that a task has
-  // been posted. Updates |num_tasks_blocking_shutdown_| if necessary and
-  // returns true if the current shutdown state allows the task to be posted.
-  bool BeforePostTask(TaskShutdownBehavior shutdown_behavior);
-
-  // Called before a task with |shutdown_behavior| is run by RunTask(). Updates
-  // |num_tasks_blocking_shutdown_| if necessary and returns true if the current
-  // shutdown state allows the task to be run.
-  bool BeforeRunTask(TaskShutdownBehavior shutdown_behavior);
-
-  // Called after a task with |shutdown_behavior| has been run by RunTask().
-  // Updates |num_tasks_blocking_shutdown_| and signals |shutdown_cv_| if
-  // necessary.
-  void AfterRunTask(TaskShutdownBehavior shutdown_behavior);
-
-  // Called when the number of tasks blocking shutdown becomes zero after
-  // shutdown has started.
-  void OnBlockingShutdownTasksComplete();
-
-  // Decrements the number of incomplete undelayed tasks and signals |flush_cv_|
-  // if it reaches zero.
-  void DecrementNumIncompleteUndelayedTasks();
-
-  // To be called after running a background task from |just_ran_sequence|.
-  // Performs the following actions:
-  //  - If |just_ran_sequence| is non-null:
-  //    - returns it if it should be rescheduled by the caller of
-  //      RunAndPopNextTask(), i.e. its next task is set to run earlier than the
-  //      earliest currently preempted sequence.
-  //    - Otherwise |just_ran_sequence| is preempted and the next preempted
-  //      sequence is scheduled (|observer| will be notified when
-  //      |just_ran_sequence| should be scheduled again).
-  //  - If |just_ran_sequence| is null (RunAndPopNextTask() just popped the last
-  //    task from it):
-  //    - the next preempeted sequence (if any) is scheduled.
-  //  - In all cases: adjusts the number of scheduled background sequences
-  //    accordingly.
-  scoped_refptr<Sequence> ManageBackgroundSequencesAfterRunningTask(
-      scoped_refptr<Sequence> just_ran_sequence,
-      CanScheduleSequenceObserver* observer);
-
-  // Calls |flush_callback_for_testing_| if one is available in a lock-safe
-  // manner.
-  void CallFlushCallbackForTesting();
-
-  // Number of tasks blocking shutdown and boolean indicating whether shutdown
-  // has started.
-  const std::unique_ptr<State> state_;
-
-  // Number of undelayed tasks that haven't completed their execution. Is
-  // decremented with a memory barrier after a task runs. Is accessed with an
-  // acquire memory barrier in FlushForTesting(). The memory barriers ensure
-  // that the memory written by flushed tasks is visible when FlushForTesting()
-  // returns.
-  subtle::Atomic32 num_incomplete_undelayed_tasks_ = 0;
-
-  // Lock associated with |flush_cv_|. Partially synchronizes access to
-  // |num_incomplete_undelayed_tasks_|. Full synchronization isn't needed
-  // because it's atomic, but synchronization is needed to coordinate waking and
-  // sleeping at the right time. Fully synchronizes access to
-  // |flush_callback_for_testing_|.
-  mutable SchedulerLock flush_lock_;
-
-  // Signaled when |num_incomplete_undelayed_tasks_| is or reaches zero or when
-  // shutdown completes.
-  const std::unique_ptr<ConditionVariable> flush_cv_;
-
-  // Invoked if non-null when |num_incomplete_undelayed_tasks_| is zero or when
-  // shutdown completes.
-  OnceClosure flush_callback_for_testing_;
-
-  // Synchronizes access to shutdown related members below.
-  mutable SchedulerLock shutdown_lock_;
-
-  // Event instantiated when shutdown starts and signaled when shutdown
-  // completes.
-  std::unique_ptr<WaitableEvent> shutdown_event_;
-
-  // Synchronizes accesses to |preempted_background_sequences_|,
-  // |max_num_scheduled_background_sequences_| and
-  // |num_scheduled_background_sequences_|.
-  SchedulerLock background_lock_;
-
-  // A priority queue of sequences that are waiting to be scheduled. Use
-  // std::greater so that the sequence which contains the task that has been
-  // posted the earliest is on top of the priority queue.
-  std::priority_queue<PreemptedBackgroundSequence,
-                      std::vector<PreemptedBackgroundSequence>,
-                      std::greater<PreemptedBackgroundSequence>>
-      preempted_background_sequences_;
-
-  // Maximum number of background sequences that can that be scheduled
-  // concurrently.
-  int max_num_scheduled_background_sequences_;
-
-  // Number of currently scheduled background sequences.
-  int num_scheduled_background_sequences_ = 0;
-
-  // Ensures all state (e.g. dangling cleaned up workers) is coalesced before
-  // destroying the TaskTracker (e.g. in test environments).
-  // Ref. https://crbug.com/827615.
-  TrackedRefFactory<TaskTracker> tracked_ref_factory_;
-
-  DISALLOW_COPY_AND_ASSIGN(TaskTracker);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_TASK_TRACKER_H_
diff --git a/base/task_scheduler/task_tracker_posix.cc b/base/task_scheduler/task_tracker_posix.cc
deleted file mode 100644
index 8289d90..0000000
--- a/base/task_scheduler/task_tracker_posix.cc
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2016 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/task_scheduler/task_tracker_posix.h"
-
-#include <utility>
-
-#include "base/files/file_descriptor_watcher_posix.h"
-
-namespace base {
-namespace internal {
-
-TaskTrackerPosix::TaskTrackerPosix(StringPiece name) : TaskTracker(name) {}
-TaskTrackerPosix::~TaskTrackerPosix() = default;
-
-void TaskTrackerPosix::RunOrSkipTask(Task task,
-                                     Sequence* sequence,
-                                     bool can_run_task) {
-  DCHECK(watch_file_descriptor_message_loop_);
-  FileDescriptorWatcher file_descriptor_watcher(
-      watch_file_descriptor_message_loop_);
-  TaskTracker::RunOrSkipTask(std::move(task), sequence, can_run_task);
-}
-
-#if DCHECK_IS_ON()
-bool TaskTrackerPosix::IsPostingBlockShutdownTaskAfterShutdownAllowed() {
-  return service_thread_handle_.is_equal(PlatformThread::CurrentHandle());
-}
-#endif
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/task_tracker_posix.h b/base/task_scheduler/task_tracker_posix.h
deleted file mode 100644
index 4689f7a..0000000
--- a/base/task_scheduler/task_tracker_posix.h
+++ /dev/null
@@ -1,74 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_TASK_TRACKER_POSIX_H_
-#define BASE_TASK_SCHEDULER_TASK_TRACKER_POSIX_H_
-
-#include <memory>
-
-#include "base/base_export.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/task_scheduler/task_tracker.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-
-class MessageLoopForIO;
-
-namespace internal {
-
-struct Task;
-
-// A TaskTracker that instantiates a FileDescriptorWatcher in the scope in which
-// a task runs. Used on all POSIX platforms except NaCl SFI.
-// set_watch_file_descriptor_message_loop() must be called before the
-// TaskTracker can run tasks.
-class BASE_EXPORT TaskTrackerPosix : public TaskTracker {
- public:
-  TaskTrackerPosix(StringPiece name);
-  ~TaskTrackerPosix() override;
-
-  // Sets the MessageLoopForIO with which to setup FileDescriptorWatcher in the
-  // scope in which tasks run. Must be called before starting to run tasks.
-  // External synchronization is required between a call to this and a call to
-  // RunTask().
-  void set_watch_file_descriptor_message_loop(
-      MessageLoopForIO* watch_file_descriptor_message_loop) {
-    watch_file_descriptor_message_loop_ = watch_file_descriptor_message_loop;
-  }
-
-#if DCHECK_IS_ON()
-  // TODO(robliao): http://crbug.com/698140. This addresses service thread tasks
-  // that could run after the task scheduler has shut down. Anything from the
-  // service thread is exempted from the task scheduler shutdown DCHECKs.
-  void set_service_thread_handle(
-      const PlatformThreadHandle& service_thread_handle) {
-    DCHECK(!service_thread_handle.is_null());
-    service_thread_handle_ = service_thread_handle;
-  }
-#endif
-
- protected:
-  // TaskTracker:
-  void RunOrSkipTask(Task task, Sequence* sequence, bool can_run_task) override;
-
- private:
-#if DCHECK_IS_ON()
-  bool IsPostingBlockShutdownTaskAfterShutdownAllowed() override;
-#endif
-
-  MessageLoopForIO* watch_file_descriptor_message_loop_ = nullptr;
-
-#if DCHECK_IS_ON()
-  PlatformThreadHandle service_thread_handle_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(TaskTrackerPosix);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_TASK_TRACKER_POSIX_H_
diff --git a/base/task_scheduler/task_traits.cc b/base/task_scheduler/task_traits.cc
deleted file mode 100644
index e82e303..0000000
--- a/base/task_scheduler/task_traits.cc
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2016 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/task_scheduler/task_traits.h"
-
-#include <stddef.h>
-
-#include <ostream>
-
-#include "base/logging.h"
-
-namespace base {
-
-const char* TaskPriorityToString(TaskPriority task_priority) {
-  switch (task_priority) {
-    case TaskPriority::BACKGROUND:
-      return "BACKGROUND";
-    case TaskPriority::USER_VISIBLE:
-      return "USER_VISIBLE";
-    case TaskPriority::USER_BLOCKING:
-      return "USER_BLOCKING";
-  }
-  NOTREACHED();
-  return "";
-}
-
-const char* TaskShutdownBehaviorToString(
-    TaskShutdownBehavior shutdown_behavior) {
-  switch (shutdown_behavior) {
-    case TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN:
-      return "CONTINUE_ON_SHUTDOWN";
-    case TaskShutdownBehavior::SKIP_ON_SHUTDOWN:
-      return "SKIP_ON_SHUTDOWN";
-    case TaskShutdownBehavior::BLOCK_SHUTDOWN:
-      return "BLOCK_SHUTDOWN";
-  }
-  NOTREACHED();
-  return "";
-}
-
-std::ostream& operator<<(std::ostream& os, const TaskPriority& task_priority) {
-  os << TaskPriorityToString(task_priority);
-  return os;
-}
-
-std::ostream& operator<<(std::ostream& os,
-                         const TaskShutdownBehavior& shutdown_behavior) {
-  os << TaskShutdownBehaviorToString(shutdown_behavior);
-  return os;
-}
-
-}  // namespace base
diff --git a/base/task_scheduler/task_traits.h b/base/task_scheduler/task_traits.h
deleted file mode 100644
index 1adba6d..0000000
--- a/base/task_scheduler/task_traits.h
+++ /dev/null
@@ -1,247 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_TASK_TRAITS_H_
-#define BASE_TASK_SCHEDULER_TASK_TRAITS_H_
-
-#include <stdint.h>
-
-#include <iosfwd>
-#include <type_traits>
-
-#include "base/base_export.h"
-#include "base/task_scheduler/task_traits_details.h"
-#include "build_config.h"
-
-namespace base {
-
-// Valid priorities supported by the task scheduler. Note: internal algorithms
-// depend on priorities being expressed as a continuous zero-based list from
-// lowest to highest priority. Users of this API shouldn't otherwise care about
-// nor use the underlying values.
-enum class TaskPriority {
-  // This will always be equal to the lowest priority available.
-  LOWEST = 0,
-  // User won't notice if this task takes an arbitrarily long time to complete.
-  BACKGROUND = LOWEST,
-  // This task affects UI or responsiveness of future user interactions. It is
-  // not an immediate response to a user interaction.
-  // Examples:
-  // - Updating the UI to reflect progress on a long task.
-  // - Loading data that might be shown in the UI after a future user
-  //   interaction.
-  USER_VISIBLE,
-  // This task affects UI immediately after a user interaction.
-  // Example: Generating data shown in the UI immediately after a click.
-  USER_BLOCKING,
-  // This will always be equal to the highest priority available.
-  HIGHEST = USER_BLOCKING,
-};
-
-// Valid shutdown behaviors supported by the task scheduler.
-enum class TaskShutdownBehavior {
-  // Tasks posted with this mode which have not started executing before
-  // shutdown is initiated will never run. Tasks with this mode running at
-  // shutdown will be ignored (the worker will not be joined).
-  //
-  // This option provides a nice way to post stuff you don't want blocking
-  // shutdown. For example, you might be doing a slow DNS lookup and if it's
-  // blocked on the OS, you may not want to stop shutdown, since the result
-  // doesn't really matter at that point.
-  //
-  // However, you need to be very careful what you do in your callback when you
-  // use this option. Since the thread will continue to run until the OS
-  // terminates the process, the app can be in the process of tearing down when
-  // you're running. This means any singletons or global objects you use may
-  // suddenly become invalid out from under you. For this reason, it's best to
-  // use this only for slow but simple operations like the DNS example.
-  CONTINUE_ON_SHUTDOWN,
-
-  // Tasks posted with this mode that have not started executing at
-  // shutdown will never run. However, any task that has already begun
-  // executing when shutdown is invoked will be allowed to continue and
-  // will block shutdown until completion.
-  //
-  // Note: Because TaskScheduler::Shutdown() may block while these tasks are
-  // executing, care must be taken to ensure that they do not block on the
-  // thread that called TaskScheduler::Shutdown(), as this may lead to deadlock.
-  SKIP_ON_SHUTDOWN,
-
-  // Tasks posted with this mode before shutdown is complete will block shutdown
-  // until they're executed. Generally, this should be used only to save
-  // critical user data.
-  //
-  // Note: Tasks with BACKGROUND priority that block shutdown will be promoted
-  // to USER_VISIBLE priority during shutdown.
-  BLOCK_SHUTDOWN,
-};
-
-// Tasks with this trait may block. This includes but is not limited to tasks
-// that wait on synchronous file I/O operations: read or write a file from disk,
-// interact with a pipe or a socket, rename or delete a file, enumerate files in
-// a directory, etc. This trait isn't required for the mere use of locks. For
-// tasks that block on base/ synchronization primitives, see the
-// WithBaseSyncPrimitives trait.
-struct MayBlock {};
-
-// DEPRECATED. Use base::ScopedAllowBaseSyncPrimitives(ForTesting) instead.
-//
-// Tasks with this trait will pass base::AssertBaseSyncPrimitivesAllowed(), i.e.
-// will be allowed on the following methods :
-// - base::WaitableEvent::Wait
-// - base::ConditionVariable::Wait
-// - base::PlatformThread::Join
-// - base::PlatformThread::Sleep
-// - base::Process::WaitForExit
-// - base::Process::WaitForExitWithTimeout
-//
-// Tasks should generally not use these methods.
-//
-// Instead of waiting on a WaitableEvent or a ConditionVariable, put the work
-// that should happen after the wait in a callback and post that callback from
-// where the WaitableEvent or ConditionVariable would have been signaled. If
-// something needs to be scheduled after many tasks have executed, use
-// base::BarrierClosure.
-//
-// On Windows, join processes asynchronously using base::win::ObjectWatcher.
-//
-// MayBlock() must be specified in conjunction with this trait if and only if
-// removing usage of methods listed above in the labeled tasks would still
-// result in tasks that may block (per MayBlock()'s definition).
-//
-// In doubt, consult with //base/task_scheduler/OWNERS.
-struct WithBaseSyncPrimitives {};
-
-// Describes immutable metadata for a single task or a group of tasks.
-class BASE_EXPORT TaskTraits {
- private:
-  // ValidTrait ensures TaskTraits' constructor only accepts appropriate types.
-  struct ValidTrait {
-    ValidTrait(TaskPriority) {}
-    ValidTrait(TaskShutdownBehavior) {}
-    ValidTrait(MayBlock) {}
-    ValidTrait(WithBaseSyncPrimitives) {}
-  };
-
- public:
-  // Invoking this constructor without arguments produces TaskTraits that are
-  // appropriate for tasks that
-  //     (1) don't block (ref. MayBlock() and WithBaseSyncPrimitives()),
-  //     (2) prefer inheriting the current priority to specifying their own, and
-  //     (3) can either block shutdown or be skipped on shutdown
-  //         (TaskScheduler implementation is free to choose a fitting default).
-  //
-  // To get TaskTraits for tasks that require stricter guarantees and/or know
-  // the specific TaskPriority appropriate for them, provide arguments of type
-  // TaskPriority, TaskShutdownBehavior, MayBlock, and/or WithBaseSyncPrimitives
-  // in any order to the constructor.
-  //
-  // E.g.
-  // constexpr base::TaskTraits default_traits = {};
-  // constexpr base::TaskTraits user_visible_traits =
-  //     {base::TaskPriority::USER_VISIBLE};
-  // constexpr base::TaskTraits user_visible_may_block_traits = {
-  //     base::TaskPriority::USER_VISIBLE, base::MayBlock()};
-  // constexpr base::TaskTraits other_user_visible_may_block_traits = {
-  //     base::MayBlock(), base::TaskPriority::USER_VISIBLE};
-  template <class... ArgTypes,
-            class CheckArgumentsAreValid = internal::InitTypes<
-                decltype(ValidTrait(std::declval<ArgTypes>()))...>>
-  constexpr TaskTraits(ArgTypes... args)
-      : priority_set_explicitly_(
-            internal::HasArgOfType<TaskPriority, ArgTypes...>::value),
-        priority_(internal::GetValueFromArgList(
-            internal::EnumArgGetter<TaskPriority, TaskPriority::USER_VISIBLE>(),
-            args...)),
-        shutdown_behavior_set_explicitly_(
-            internal::HasArgOfType<TaskShutdownBehavior, ArgTypes...>::value),
-        shutdown_behavior_(internal::GetValueFromArgList(
-            internal::EnumArgGetter<TaskShutdownBehavior,
-                                    TaskShutdownBehavior::SKIP_ON_SHUTDOWN>(),
-            args...)),
-        may_block_(internal::GetValueFromArgList(
-            internal::BooleanArgGetter<MayBlock>(),
-            args...)),
-        with_base_sync_primitives_(internal::GetValueFromArgList(
-            internal::BooleanArgGetter<WithBaseSyncPrimitives>(),
-            args...)) {}
-
-  constexpr TaskTraits(const TaskTraits& other) = default;
-  TaskTraits& operator=(const TaskTraits& other) = default;
-
-  // Returns TaskTraits constructed by combining |left| and |right|. If a trait
-  // is specified in both |left| and |right|, the returned TaskTraits will have
-  // the value from |right|.
-  static constexpr TaskTraits Override(const TaskTraits& left,
-                                       const TaskTraits& right) {
-    return TaskTraits(left, right);
-  }
-
-  // Returns true if the priority was set explicitly.
-  constexpr bool priority_set_explicitly() const {
-    return priority_set_explicitly_;
-  }
-
-  // Returns the priority of tasks with these traits.
-  constexpr TaskPriority priority() const { return priority_; }
-
-  // Returns true if the shutdown behavior was set explicitly.
-  constexpr bool shutdown_behavior_set_explicitly() const {
-    return shutdown_behavior_set_explicitly_;
-  }
-
-  // Returns the shutdown behavior of tasks with these traits.
-  constexpr TaskShutdownBehavior shutdown_behavior() const {
-    return shutdown_behavior_;
-  }
-
-  // Returns true if tasks with these traits may block.
-  constexpr bool may_block() const { return may_block_; }
-
-  // Returns true if tasks with these traits may use base/ sync primitives.
-  constexpr bool with_base_sync_primitives() const {
-    return with_base_sync_primitives_;
-  }
-
- private:
-  constexpr TaskTraits(const TaskTraits& left, const TaskTraits& right)
-      : priority_set_explicitly_(left.priority_set_explicitly_ ||
-                                 right.priority_set_explicitly_),
-        priority_(right.priority_set_explicitly_ ? right.priority_
-                                                 : left.priority_),
-        shutdown_behavior_set_explicitly_(
-            left.shutdown_behavior_set_explicitly_ ||
-            right.shutdown_behavior_set_explicitly_),
-        shutdown_behavior_(right.shutdown_behavior_set_explicitly_
-                               ? right.shutdown_behavior_
-                               : left.shutdown_behavior_),
-        may_block_(left.may_block_ || right.may_block_),
-        with_base_sync_primitives_(left.with_base_sync_primitives_ ||
-                                   right.with_base_sync_primitives_) {}
-
-  bool priority_set_explicitly_;
-  TaskPriority priority_;
-  bool shutdown_behavior_set_explicitly_;
-  TaskShutdownBehavior shutdown_behavior_;
-  bool may_block_;
-  bool with_base_sync_primitives_;
-};
-
-// Returns string literals for the enums defined in this file. These methods
-// should only be used for tracing and debugging.
-BASE_EXPORT const char* TaskPriorityToString(TaskPriority task_priority);
-BASE_EXPORT const char* TaskShutdownBehaviorToString(
-    TaskShutdownBehavior task_priority);
-
-// Stream operators so that the enums defined in this file can be used in
-// DCHECK and EXPECT statements.
-BASE_EXPORT std::ostream& operator<<(std::ostream& os,
-                                     const TaskPriority& shutdown_behavior);
-BASE_EXPORT std::ostream& operator<<(
-    std::ostream& os,
-    const TaskShutdownBehavior& shutdown_behavior);
-
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_TASK_TRAITS_H_
diff --git a/base/task_scheduler/task_traits_details.h b/base/task_scheduler/task_traits_details.h
deleted file mode 100644
index 05fb605..0000000
--- a/base/task_scheduler/task_traits_details.h
+++ /dev/null
@@ -1,128 +0,0 @@
-// Copyright 2017 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_TASK_SCHEDULER_TASK_TRAITS_DETAILS_H_
-#define BASE_TASK_SCHEDULER_TASK_TRAITS_DETAILS_H_
-
-#include <type_traits>
-#include <utility>
-
-namespace base {
-namespace internal {
-
-// HasArgOfType<CheckedType, ArgTypes...>::value is true iff a type in ArgTypes
-// matches CheckedType.
-template <class...>
-struct HasArgOfType : std::false_type {};
-template <class CheckedType, class FirstArgType, class... ArgTypes>
-struct HasArgOfType<CheckedType, FirstArgType, ArgTypes...>
-    : std::conditional<std::is_same<CheckedType, FirstArgType>::value,
-                       std::true_type,
-                       HasArgOfType<CheckedType, ArgTypes...>>::type {};
-
-// When the following call is made:
-//    GetValueFromArgListImpl(CallFirstTag(), GetterType(), args...);
-// If |args| is empty, the compiler selects the first overload. This overload
-// returns getter.GetDefaultValue(). If |args| is not empty, the compiler
-// prefers using the second overload because the type of the first argument
-// matches exactly. This overload returns getter.GetValueFromArg(first_arg),
-// where |first_arg| is the first element in |args|. If
-// getter.GetValueFromArg(first_arg) isn't defined, the compiler uses the third
-// overload instead. This overload discards the first argument in |args| and
-// makes a recursive call to GetValueFromArgListImpl() with CallFirstTag() as
-// first argument.
-
-// Tag dispatching.
-struct CallSecondTag {};
-struct CallFirstTag : CallSecondTag {};
-
-// Overload 1: Default value.
-template <class GetterType>
-constexpr typename GetterType::ValueType GetValueFromArgListImpl(
-    CallFirstTag,
-    GetterType getter) {
-  return getter.GetDefaultValue();
-}
-
-// Overload 2: Get value from first argument. Check that no argument in |args|
-// has the same type as |first_arg|.
-template <class GetterType,
-          class FirstArgType,
-          class... ArgTypes,
-          class TestGetValueFromArgDefined =
-              decltype(std::declval<GetterType>().GetValueFromArg(
-                  std::declval<FirstArgType>()))>
-constexpr typename GetterType::ValueType GetValueFromArgListImpl(
-    CallFirstTag,
-    GetterType getter,
-    const FirstArgType& first_arg,
-    const ArgTypes&... args) {
-  static_assert(!HasArgOfType<FirstArgType, ArgTypes...>::value,
-                "Multiple arguments of the same type were provided to the "
-                "constructor of TaskTraits.");
-  return getter.GetValueFromArg(first_arg);
-}
-
-// Overload 3: Discard first argument.
-template <class GetterType, class FirstArgType, class... ArgTypes>
-constexpr typename GetterType::ValueType GetValueFromArgListImpl(
-    CallSecondTag,
-    GetterType getter,
-    const FirstArgType&,
-    const ArgTypes&... args) {
-  return GetValueFromArgListImpl(CallFirstTag(), getter, args...);
-}
-
-// If there is an argument |arg_of_type| of type Getter::ArgType in |args|,
-// returns getter.GetValueFromArg(arg_of_type). If there are more than one
-// argument of type Getter::ArgType in |args|, generates a compile-time error.
-// Otherwise, returns getter.GetDefaultValue().
-//
-// |getter| must provide:
-//
-// ValueType:
-//     The return type of GetValueFromArgListImpl().
-//
-// ArgType:
-//     The type of the argument from which GetValueFromArgListImpl() derives its
-//     return value.
-//
-// ValueType GetValueFromArg(ArgType):
-//     Converts an argument of type ArgType into a value returned by
-//     GetValueFromArgListImpl().
-//
-// ValueType GetDefaultValue():
-//     Returns the value returned by GetValueFromArgListImpl() if none of its
-//     arguments is of type ArgType.
-template <class GetterType, class... ArgTypes>
-constexpr typename GetterType::ValueType GetValueFromArgList(
-    GetterType getter,
-    const ArgTypes&... args) {
-  return GetValueFromArgListImpl(CallFirstTag(), getter, args...);
-}
-
-template <typename ArgType>
-struct BooleanArgGetter {
-  using ValueType = bool;
-  constexpr ValueType GetValueFromArg(ArgType) const { return true; }
-  constexpr ValueType GetDefaultValue() const { return false; }
-};
-
-template <typename ArgType, ArgType DefaultValue>
-struct EnumArgGetter {
-  using ValueType = ArgType;
-  constexpr ValueType GetValueFromArg(ArgType arg) const { return arg; }
-  constexpr ValueType GetDefaultValue() const { return DefaultValue; }
-};
-
-// Allows instantiation of multiple types in one statement. Used to prevent
-// instantiation of the constructor of TaskTraits with inappropriate argument
-// types.
-template <class...>
-struct InitTypes {};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_TASK_TRAITS_DETAILS_H_
diff --git a/base/task_scheduler/test_task_factory.cc b/base/task_scheduler/test_task_factory.cc
deleted file mode 100644
index 0867547..0000000
--- a/base/task_scheduler/test_task_factory.cc
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright 2016 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/task_scheduler/test_task_factory.h"
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/callback.h"
-#include "base/location.h"
-#include "base/logging.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace base {
-namespace internal {
-namespace test {
-
-TestTaskFactory::TestTaskFactory(scoped_refptr<TaskRunner> task_runner,
-                                 ExecutionMode execution_mode)
-    : cv_(&lock_),
-      task_runner_(std::move(task_runner)),
-      execution_mode_(execution_mode) {
-  // Detach |thread_checker_| from the current thread. It will be attached to
-  // the first thread that calls ThreadCheckerImpl::CalledOnValidThread().
-  thread_checker_.DetachFromThread();
-}
-
-TestTaskFactory::~TestTaskFactory() {
-  WaitForAllTasksToRun();
-}
-
-bool TestTaskFactory::PostTask(PostNestedTask post_nested_task,
-                               OnceClosure after_task_closure) {
-  AutoLock auto_lock(lock_);
-  return task_runner_->PostTask(
-      FROM_HERE, BindOnce(&TestTaskFactory::RunTaskCallback, Unretained(this),
-                          num_posted_tasks_++, post_nested_task,
-                          std::move(after_task_closure)));
-}
-
-void TestTaskFactory::WaitForAllTasksToRun() const {
-  AutoLock auto_lock(lock_);
-  while (ran_tasks_.size() < num_posted_tasks_)
-    cv_.Wait();
-}
-
-void TestTaskFactory::RunTaskCallback(size_t task_index,
-                                      PostNestedTask post_nested_task,
-                                      OnceClosure after_task_closure) {
-  if (post_nested_task == PostNestedTask::YES)
-    PostTask(PostNestedTask::NO, Closure());
-
-  EXPECT_TRUE(task_runner_->RunsTasksInCurrentSequence());
-
-  // Verify TaskRunnerHandles are set as expected in the task's scope.
-  switch (execution_mode_) {
-    case ExecutionMode::PARALLEL:
-      EXPECT_FALSE(ThreadTaskRunnerHandle::IsSet());
-      EXPECT_FALSE(SequencedTaskRunnerHandle::IsSet());
-      break;
-    case ExecutionMode::SEQUENCED:
-      EXPECT_FALSE(ThreadTaskRunnerHandle::IsSet());
-      EXPECT_TRUE(SequencedTaskRunnerHandle::IsSet());
-      EXPECT_EQ(task_runner_, SequencedTaskRunnerHandle::Get());
-      break;
-    case ExecutionMode::SINGLE_THREADED:
-      // SequencedTaskRunnerHandle inherits from ThreadTaskRunnerHandle so
-      // both are expected to be "set" in the SINGLE_THREADED case.
-      EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
-      EXPECT_TRUE(SequencedTaskRunnerHandle::IsSet());
-      EXPECT_EQ(task_runner_, ThreadTaskRunnerHandle::Get());
-      EXPECT_EQ(task_runner_, SequencedTaskRunnerHandle::Get());
-      break;
-  }
-
-  {
-    AutoLock auto_lock(lock_);
-
-    DCHECK_LE(task_index, num_posted_tasks_);
-
-    if ((execution_mode_ == ExecutionMode::SINGLE_THREADED ||
-         execution_mode_ == ExecutionMode::SEQUENCED) &&
-        task_index != ran_tasks_.size()) {
-      ADD_FAILURE() << "A task didn't run in the expected order.";
-    }
-
-    if (execution_mode_ == ExecutionMode::SINGLE_THREADED)
-      EXPECT_TRUE(thread_checker_.CalledOnValidThread());
-
-    if (ran_tasks_.find(task_index) != ran_tasks_.end())
-      ADD_FAILURE() << "A task ran more than once.";
-    ran_tasks_.insert(task_index);
-
-    cv_.Signal();
-  }
-
-  if (!after_task_closure.is_null())
-    std::move(after_task_closure).Run();
-}
-
-}  // namespace test
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/test_task_factory.h b/base/task_scheduler/test_task_factory.h
deleted file mode 100644
index 300b7bf..0000000
--- a/base/task_scheduler/test_task_factory.h
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_TEST_TASK_FACTORY_H_
-#define BASE_TASK_SCHEDULER_TEST_TASK_FACTORY_H_
-
-#include <stddef.h>
-
-#include <unordered_set>
-
-#include "base/callback_forward.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/synchronization/condition_variable.h"
-#include "base/synchronization/lock.h"
-#include "base/task_runner.h"
-#include "base/task_scheduler/task_traits.h"
-#include "base/task_scheduler/test_utils.h"
-#include "base/threading/thread_checker_impl.h"
-
-namespace base {
-namespace internal {
-namespace test {
-
-// A TestTaskFactory posts tasks to a TaskRunner and verifies that they run as
-// expected. Generates a test failure when:
-// - The RunsTasksInCurrentSequence() method of the TaskRunner returns false on
-//   a thread on which a Task is run.
-// - The TaskRunnerHandles set in the context of the task don't match what's
-//   expected for the tested ExecutionMode.
-// - The ExecutionMode of the TaskRunner is SEQUENCED or SINGLE_THREADED and
-//   Tasks don't run in posting order.
-// - The ExecutionMode of the TaskRunner is SINGLE_THREADED and Tasks don't run
-//   on the same thread.
-// - A Task runs more than once.
-class TestTaskFactory {
- public:
-  enum class PostNestedTask {
-    YES,
-    NO,
-  };
-
-  // Constructs a TestTaskFactory that posts tasks to |task_runner|.
-  // |execution_mode| is the ExecutionMode of |task_runner|.
-  TestTaskFactory(scoped_refptr<TaskRunner> task_runner,
-                  ExecutionMode execution_mode);
-
-  ~TestTaskFactory();
-
-  // Posts a task. The posted task will:
-  // - Post a new task if |post_nested_task| is YES. The nested task won't run
-  //   |after_task_closure|.
-  // - Verify conditions in which the task runs (see potential failures above).
-  // - Run |after_task_closure| if it is not null.
-  bool PostTask(PostNestedTask post_nested_task,
-                OnceClosure after_task_closure);
-
-  // Waits for all tasks posted by PostTask() to start running. It is not
-  // guaranteed that the tasks have completed their execution when this returns.
-  void WaitForAllTasksToRun() const;
-
-  const TaskRunner* task_runner() const { return task_runner_.get(); }
-
- private:
-  void RunTaskCallback(size_t task_index,
-                       PostNestedTask post_nested_task,
-                       OnceClosure after_task_closure);
-
-  // Synchronizes access to all members.
-  mutable Lock lock_;
-
-  // Condition variable signaled when a task runs.
-  mutable ConditionVariable cv_;
-
-  // Task runner through which this factory posts tasks.
-  const scoped_refptr<TaskRunner> task_runner_;
-
-  // Execution mode of |task_runner_|.
-  const ExecutionMode execution_mode_;
-
-  // Number of tasks posted by PostTask().
-  size_t num_posted_tasks_ = 0;
-
-  // Indexes of tasks that ran.
-  std::unordered_set<size_t> ran_tasks_;
-
-  // Used to verify that all tasks run on the same thread when |execution_mode_|
-  // is SINGLE_THREADED.
-  ThreadCheckerImpl thread_checker_;
-
-  DISALLOW_COPY_AND_ASSIGN(TestTaskFactory);
-};
-
-}  // namespace test
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_TEST_TASK_FACTORY_H_
diff --git a/base/task_scheduler/test_utils.cc b/base/task_scheduler/test_utils.cc
deleted file mode 100644
index eb509f8..0000000
--- a/base/task_scheduler/test_utils.cc
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2017 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/task_scheduler/test_utils.h"
-
-#include <utility>
-
-#include "base/task_scheduler/scheduler_worker_pool.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace base {
-namespace internal {
-namespace test {
-
-MockSchedulerWorkerObserver::MockSchedulerWorkerObserver() = default;
-MockSchedulerWorkerObserver::~MockSchedulerWorkerObserver() = default;
-
-scoped_refptr<Sequence> CreateSequenceWithTask(Task task) {
-  scoped_refptr<Sequence> sequence = MakeRefCounted<Sequence>();
-  sequence->PushTask(std::move(task));
-  return sequence;
-}
-
-scoped_refptr<TaskRunner> CreateTaskRunnerWithExecutionMode(
-    SchedulerWorkerPool* worker_pool,
-    test::ExecutionMode execution_mode) {
-  // Allow tasks posted to the returned TaskRunner to wait on a WaitableEvent.
-  const TaskTraits traits = {WithBaseSyncPrimitives()};
-  switch (execution_mode) {
-    case test::ExecutionMode::PARALLEL:
-      return worker_pool->CreateTaskRunnerWithTraits(traits);
-    case test::ExecutionMode::SEQUENCED:
-      return worker_pool->CreateSequencedTaskRunnerWithTraits(traits);
-    default:
-      // Fall through.
-      break;
-  }
-  ADD_FAILURE() << "Unexpected ExecutionMode";
-  return nullptr;
-}
-
-}  // namespace test
-}  // namespace internal
-}  // namespace base
diff --git a/base/task_scheduler/test_utils.h b/base/task_scheduler/test_utils.h
deleted file mode 100644
index 42e4eed..0000000
--- a/base/task_scheduler/test_utils.h
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright 2016 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_TASK_SCHEDULER_TEST_UTILS_H_
-#define BASE_TASK_SCHEDULER_TEST_UTILS_H_
-
-#include "base/memory/ref_counted.h"
-#include "base/task_runner.h"
-#include "base/task_scheduler/scheduler_worker_observer.h"
-#include "base/task_scheduler/sequence.h"
-#include "testing/gmock/include/gmock/gmock.h"
-
-namespace base {
-namespace internal {
-
-class SchedulerWorkerPool;
-struct Task;
-
-namespace test {
-
-class MockSchedulerWorkerObserver : public SchedulerWorkerObserver {
- public:
-  MockSchedulerWorkerObserver();
-  ~MockSchedulerWorkerObserver();
-
-  MOCK_METHOD0(OnSchedulerWorkerMainEntry, void());
-  MOCK_METHOD0(OnSchedulerWorkerMainExit, void());
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(MockSchedulerWorkerObserver);
-};
-
-// An enumeration of possible task scheduler TaskRunner types. Used to
-// parametrize relevant task_scheduler tests.
-enum class ExecutionMode { PARALLEL, SEQUENCED, SINGLE_THREADED };
-
-// Creates a Sequence and pushes |task| to it. Returns that sequence.
-scoped_refptr<Sequence> CreateSequenceWithTask(Task task);
-
-// Creates a TaskRunner that posts tasks to |worker_pool| with the
-// |execution_mode| execution mode and the WithBaseSyncPrimitives() trait.
-// Caveat: this does not support ExecutionMode::SINGLE_THREADED.
-scoped_refptr<TaskRunner> CreateTaskRunnerWithExecutionMode(
-    SchedulerWorkerPool* worker_pool,
-    test::ExecutionMode execution_mode);
-
-}  // namespace test
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_TEST_UTILS_H_
diff --git a/base/task_scheduler/tracked_ref.h b/base/task_scheduler/tracked_ref.h
deleted file mode 100644
index d99a345..0000000
--- a/base/task_scheduler/tracked_ref.h
+++ /dev/null
@@ -1,173 +0,0 @@
-// Copyright 2018 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_TASK_SCHEDULER_TRACKED_REF_H_
-#define BASE_TASK_SCHEDULER_TRACKED_REF_H_
-
-#include <memory>
-
-#include "base/atomic_ref_count.h"
-#include "base/gtest_prod_util.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/synchronization/waitable_event.h"
-
-namespace base {
-namespace internal {
-
-// TrackedRefs are effectively a ref-counting scheme for objects that have a
-// single owner.
-//
-// Deletion is still controlled by the single owner but ~T() itself will block
-// until all the TrackedRefs handed by its TrackedRefFactory have been released
-// (by ~TrackedRef<T>()).
-//
-// Just like WeakPtrFactory: TrackedRefFactory<T> should be the last member of T
-// to ensure ~TrackedRefFactory<T>() runs first in ~T().
-//
-// The owner of a T should hence be certain that the last TrackedRefs to T are
-// already gone or on their way out before destroying it or ~T() will hang
-// (indicating a bug in the tear down logic -- proper refcounting on the other
-// hand would result in a leak).
-//
-// TrackedRefFactory only makes sense to use on types that are always leaked in
-// production but need to be torn down in tests (blocking destruction is
-// impractical in production -- ref. ScopedAllowBaseSyncPrimitivesForTesting
-// below).
-//
-// Why would we ever need such a thing? In task_scheduler there is a clear
-// ownership hierarchy with mostly single owners and little refcounting. In
-// production nothing is ever torn down so this isn't a problem. In tests
-// however we must JoinForTesting(). At that point, all the raw back T* refs
-// used by the worker threads are problematic because they can result in use-
-// after-frees if a worker outlives the deletion of its corresponding
-// TaskScheduler/TaskTracker/SchedulerWorkerPool/etc.
-//
-// JoinForTesting() isn't so hard when all workers are managed. But with cleanup
-// semantics (reclaiming a worker who's been idle for too long) it becomes
-// tricky because workers can go unaccounted for before they exit their main
-// (https://crbug.com/827615).
-//
-// For that reason and to clearly document the ownership model, task_scheduler
-// uses TrackedRefs.
-//
-// On top of being a clearer ownership model than proper refcounting, a hang in
-// tear down in a test with out-of-order tear down logic is much preferred to
-// letting its worker thread and associated constructs outlive the test
-// (potentially resulting in flakes in unrelated tests running later in the same
-// process).
-//
-// Note: While there's nothing task_scheduler specific about TrackedRefs it
-// requires an ownership model where all the TrackedRefs are released on other
-// threads in sync with ~T(). This isn't a typical use case beyond shutting down
-// TaskScheduler in tests and as such this is kept internal here for now.
-
-template <class T>
-class TrackedRefFactory;
-
-// TrackedRef<T> can be used like a T*.
-template <class T>
-class TrackedRef {
- public:
-  // Moveable and copyable.
-  TrackedRef(TrackedRef<T>&& other)
-      : ptr_(other.ptr_), factory_(other.factory_) {
-    // Null out |other_|'s factory so its destructor doesn't decrement
-    // |live_tracked_refs_|.
-    other.factory_ = nullptr;
-  }
-  TrackedRef(const TrackedRef<T>& other)
-      : ptr_(other.ptr_), factory_(other.factory_) {
-    factory_->live_tracked_refs_.Increment();
-  }
-
-  // Intentionally not assignable for now because it makes the logic slightly
-  // convoluted and it's not a use case that makes sense for the types using
-  // this at the moment.
-  TrackedRef& operator=(TrackedRef<T>&& other) = delete;
-  TrackedRef& operator=(const TrackedRef<T>& other) = delete;
-
-  ~TrackedRef() {
-    if (factory_ && !factory_->live_tracked_refs_.Decrement()) {
-      DCHECK(factory_->ready_to_destroy_);
-      DCHECK(!factory_->ready_to_destroy_->IsSignaled());
-      factory_->ready_to_destroy_->Signal();
-    }
-  }
-
-  T& operator*() const { return *ptr_; }
-
-  T* operator->() const { return ptr_; }
-
-  explicit operator bool() const { return ptr_ != nullptr; }
-
- private:
-  friend class TrackedRefFactory<T>;
-
-  TrackedRef(T* ptr, TrackedRefFactory<T>* factory)
-      : ptr_(ptr), factory_(factory) {
-    factory_->live_tracked_refs_.Increment();
-  }
-
-  T* ptr_;
-  TrackedRefFactory<T>* factory_;
-};
-
-// TrackedRefFactory<T> should be the last member of T.
-template <class T>
-class TrackedRefFactory {
- public:
-  TrackedRefFactory(T* ptr)
-      : ptr_(ptr), self_ref_(WrapUnique(new TrackedRef<T>(ptr_, this))) {
-    DCHECK(ptr_);
-  }
-
-  ~TrackedRefFactory() {
-    // Enter the destruction phase.
-    ready_to_destroy_ = std::make_unique<WaitableEvent>(
-        WaitableEvent::ResetPolicy::MANUAL,
-        WaitableEvent::InitialState::NOT_SIGNALED);
-
-    // Release self-ref (if this was the last one it will signal the event right
-    // away).
-    self_ref_.reset();
-
-    ready_to_destroy_->Wait();
-  }
-
-  TrackedRef<T> GetTrackedRef() {
-    // TrackedRefs cannot be obtained after |live_tracked_refs_| has already
-    // reached zero. In other words, the owner of a TrackedRefFactory shouldn't
-    // vend new TrackedRefs while it's being destroyed (owners of TrackedRefs
-    // may still copy/move their refs around during the destruction phase).
-    DCHECK(!live_tracked_refs_.IsZero());
-    return TrackedRef<T>(ptr_, this);
-  }
-
- private:
-  friend class TrackedRef<T>;
-  FRIEND_TEST_ALL_PREFIXES(TrackedRefTest, CopyAndMoveSemantics);
-
-  T* const ptr_;
-
-  // The number of live TrackedRefs vended by this factory.
-  AtomicRefCount live_tracked_refs_{0};
-
-  // Non-null during the destruction phase. Signaled once |live_tracked_refs_|
-  // reaches 0. Note: while this could a direct member, only initializing it in
-  // the destruction phase avoids keeping a handle open for the entire session.
-  std::unique_ptr<WaitableEvent> ready_to_destroy_;
-
-  // TrackedRefFactory holds a TrackedRef as well to prevent
-  // |live_tracked_refs_| from ever reaching zero before ~TrackedRefFactory().
-  std::unique_ptr<TrackedRef<T>> self_ref_;
-
-  DISALLOW_COPY_AND_ASSIGN(TrackedRefFactory);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_TASK_SCHEDULER_TRACKED_REF_H_
diff --git a/base/test/scoped_task_environment.cc b/base/test/scoped_task_environment.cc
deleted file mode 100644
index 3d580b0..0000000
--- a/base/test/scoped_task_environment.cc
+++ /dev/null
@@ -1,346 +0,0 @@
-// Copyright 2017 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/test/scoped_task_environment.h"
-
-#include "base/bind_helpers.h"
-#include "base/logging.h"
-#include "base/memory/ptr_util.h"
-#include "base/message_loop/message_loop.h"
-#include "base/run_loop.h"
-#include "base/synchronization/condition_variable.h"
-#include "base/synchronization/lock.h"
-#include "base/task_scheduler/post_task.h"
-#include "base/task_scheduler/task_scheduler.h"
-#include "base/task_scheduler/task_scheduler_impl.h"
-#include "base/test/test_mock_time_task_runner.h"
-#include "base/threading/sequence_local_storage_map.h"
-#include "base/threading/thread_restrictions.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "base/time/time.h"
-
-#if defined(OS_POSIX)
-#include "base/files/file_descriptor_watcher_posix.h"
-#endif
-
-namespace base {
-namespace test {
-
-namespace {
-
-std::unique_ptr<MessageLoop> CreateMessageLoopForMainThreadType(
-    ScopedTaskEnvironment::MainThreadType main_thread_type) {
-  switch (main_thread_type) {
-    case ScopedTaskEnvironment::MainThreadType::DEFAULT:
-      return std::make_unique<MessageLoop>(MessageLoop::TYPE_DEFAULT);
-    case ScopedTaskEnvironment::MainThreadType::MOCK_TIME:
-      return nullptr;
-    case ScopedTaskEnvironment::MainThreadType::UI:
-      return std::make_unique<MessageLoop>(MessageLoop::TYPE_UI);
-    case ScopedTaskEnvironment::MainThreadType::IO:
-      return std::make_unique<MessageLoop>(MessageLoop::TYPE_IO);
-  }
-  NOTREACHED();
-  return nullptr;
-}
-
-}  // namespace
-
-class ScopedTaskEnvironment::TestTaskTracker
-    : public internal::TaskSchedulerImpl::TaskTrackerImpl {
- public:
-  TestTaskTracker();
-
-  // Allow running tasks.
-  void AllowRunTasks();
-
-  // Disallow running tasks. Returns true on success; success requires there to
-  // be no tasks currently running. Returns false if >0 tasks are currently
-  // running. Prior to returning false, it will attempt to block until at least
-  // one task has completed (in an attempt to avoid callers busy-looping
-  // DisallowRunTasks() calls with the same set of slowly ongoing tasks). This
-  // block attempt will also have a short timeout (in an attempt to prevent the
-  // fallout of blocking: if the only task remaining is blocked on the main
-  // thread, waiting for it to complete results in a deadlock...).
-  bool DisallowRunTasks();
-
- private:
-  friend class ScopedTaskEnvironment;
-
-  // internal::TaskSchedulerImpl::TaskTrackerImpl:
-  void RunOrSkipTask(internal::Task task,
-                     internal::Sequence* sequence,
-                     bool can_run_task) override;
-
-  // Synchronizes accesses to members below.
-  Lock lock_;
-
-  // True if running tasks is allowed.
-  bool can_run_tasks_ = true;
-
-  // Signaled when |can_run_tasks_| becomes true.
-  ConditionVariable can_run_tasks_cv_;
-
-  // Signaled when a task is completed.
-  ConditionVariable task_completed_;
-
-  // Number of tasks that are currently running.
-  int num_tasks_running_ = 0;
-
-  DISALLOW_COPY_AND_ASSIGN(TestTaskTracker);
-};
-
-ScopedTaskEnvironment::ScopedTaskEnvironment(
-    MainThreadType main_thread_type,
-    ExecutionMode execution_control_mode)
-    : execution_control_mode_(execution_control_mode),
-      message_loop_(CreateMessageLoopForMainThreadType(main_thread_type)),
-      mock_time_task_runner_(
-          main_thread_type == MainThreadType::MOCK_TIME
-              ? MakeRefCounted<TestMockTimeTaskRunner>(
-                    TestMockTimeTaskRunner::Type::kBoundToThread)
-              : nullptr),
-      slsm_for_mock_time_(
-          main_thread_type == MainThreadType::MOCK_TIME
-              ? std::make_unique<internal::SequenceLocalStorageMap>()
-              : nullptr),
-      slsm_registration_for_mock_time_(
-          main_thread_type == MainThreadType::MOCK_TIME
-              ? std::make_unique<
-                    internal::ScopedSetSequenceLocalStorageMapForCurrentThread>(
-                    slsm_for_mock_time_.get())
-              : nullptr),
-#if defined(OS_POSIX)
-      file_descriptor_watcher_(
-          main_thread_type == MainThreadType::IO
-              ? std::make_unique<FileDescriptorWatcher>(
-                    static_cast<MessageLoopForIO*>(message_loop_.get()))
-              : nullptr),
-#endif  // defined(OS_POSIX)
-      task_tracker_(new TestTaskTracker()) {
-  CHECK(!TaskScheduler::GetInstance());
-
-  // Instantiate a TaskScheduler with 2 threads in each of its 4 pools. Threads
-  // stay alive even when they don't have work.
-  // Each pool uses two threads to prevent deadlocks in unit tests that have a
-  // sequence that uses WithBaseSyncPrimitives() to wait on the result of
-  // another sequence. This isn't perfect (doesn't solve wait chains) but solves
-  // the basic use case for now.
-  // TODO(fdoray/jeffreyhe): Make the TaskScheduler dynamically replace blocked
-  // threads and get rid of this limitation. http://crbug.com/738104
-  constexpr int kMaxThreads = 2;
-  const TimeDelta kSuggestedReclaimTime = TimeDelta::Max();
-  const SchedulerWorkerPoolParams worker_pool_params(kMaxThreads,
-                                                     kSuggestedReclaimTime);
-  TaskScheduler::SetInstance(std::make_unique<internal::TaskSchedulerImpl>(
-      "ScopedTaskEnvironment", WrapUnique(task_tracker_)));
-  task_scheduler_ = TaskScheduler::GetInstance();
-  TaskScheduler::GetInstance()->Start({worker_pool_params, worker_pool_params,
-                                       worker_pool_params, worker_pool_params});
-
-  if (execution_control_mode_ == ExecutionMode::QUEUED)
-    CHECK(task_tracker_->DisallowRunTasks());
-}
-
-ScopedTaskEnvironment::~ScopedTaskEnvironment() {
-  // Ideally this would RunLoop().RunUntilIdle() here to catch any errors or
-  // infinite post loop in the remaining work but this isn't possible right now
-  // because base::~MessageLoop() didn't use to do this and adding it here would
-  // make the migration away from MessageLoop that much harder.
-  CHECK_EQ(TaskScheduler::GetInstance(), task_scheduler_);
-  // Without FlushForTesting(), DeleteSoon() and ReleaseSoon() tasks could be
-  // skipped, resulting in memory leaks.
-  task_tracker_->AllowRunTasks();
-  TaskScheduler::GetInstance()->FlushForTesting();
-  TaskScheduler::GetInstance()->Shutdown();
-  TaskScheduler::GetInstance()->JoinForTesting();
-  // Destroying TaskScheduler state can result in waiting on worker threads.
-  // Make sure this is allowed to avoid flaking tests that have disallowed waits
-  // on their main thread.
-  ScopedAllowBaseSyncPrimitivesForTesting allow_waits_to_destroy_task_tracker;
-  TaskScheduler::SetInstance(nullptr);
-}
-
-scoped_refptr<base::SingleThreadTaskRunner>
-ScopedTaskEnvironment::GetMainThreadTaskRunner() {
-  if (message_loop_)
-    return message_loop_->task_runner();
-  DCHECK(mock_time_task_runner_);
-  return mock_time_task_runner_;
-}
-
-bool ScopedTaskEnvironment::MainThreadHasPendingTask() const {
-  if (message_loop_)
-    return !message_loop_->IsIdleForTesting();
-  DCHECK(mock_time_task_runner_);
-  return mock_time_task_runner_->HasPendingTask();
-}
-
-void ScopedTaskEnvironment::RunUntilIdle() {
-  // TODO(gab): This can be heavily simplified to essentially:
-  //     bool HasMainThreadTasks() {
-  //      if (message_loop_)
-  //        return !message_loop_->IsIdleForTesting();
-  //      return mock_time_task_runner_->NextPendingTaskDelay().is_zero();
-  //     }
-  //     while (task_tracker_->HasIncompleteTasks() || HasMainThreadTasks()) {
-  //       base::RunLoop().RunUntilIdle();
-  //       // Avoid busy-looping.
-  //       if (task_tracker_->HasIncompleteTasks())
-  //         PlatformThread::Sleep(TimeDelta::FromMilliSeconds(1));
-  //     }
-  // Challenge: HasMainThreadTasks() requires support for proper
-  // IncomingTaskQueue::IsIdleForTesting() (check all queues).
-  //
-  // Other than that it works because once |task_tracker_->HasIncompleteTasks()|
-  // is false we know for sure that the only thing that can make it true is a
-  // main thread task (ScopedTaskEnvironment owns all the threads). As such we
-  // can't racily see it as false on the main thread and be wrong as if it the
-  // main thread sees the atomic count at zero, it's the only one that can make
-  // it go up. And the only thing that can make it go up on the main thread are
-  // main thread tasks and therefore we're done if there aren't any left.
-  //
-  // This simplification further allows simplification of DisallowRunTasks().
-  //
-  // This can also be simplified even further once TaskTracker becomes directly
-  // aware of main thread tasks. https://crbug.com/660078.
-
-  for (;;) {
-    task_tracker_->AllowRunTasks();
-
-    // First run as many tasks as possible on the main thread in parallel with
-    // tasks in TaskScheduler. This increases likelihood of TSAN catching
-    // threading errors and eliminates possibility of hangs should a
-    // TaskScheduler task synchronously block on a main thread task
-    // (TaskScheduler::FlushForTesting() can't be used here for that reason).
-    RunLoop().RunUntilIdle();
-
-    // Then halt TaskScheduler. DisallowRunTasks() failing indicates that there
-    // were TaskScheduler tasks currently running. In that case, try again from
-    // top when DisallowRunTasks() yields control back to this thread as they
-    // may have posted main thread tasks.
-    if (!task_tracker_->DisallowRunTasks())
-      continue;
-
-    // Once TaskScheduler is halted. Run any remaining main thread tasks (which
-    // may have been posted by TaskScheduler tasks that completed between the
-    // above main thread RunUntilIdle() and TaskScheduler DisallowRunTasks()).
-    // Note: this assumes that no main thread task synchronously blocks on a
-    // TaskScheduler tasks (it certainly shouldn't); this call could otherwise
-    // hang.
-    RunLoop().RunUntilIdle();
-
-    // The above RunUntilIdle() guarantees there are no remaining main thread
-    // tasks (the TaskScheduler being halted during the last RunUntilIdle() is
-    // key as it prevents a task being posted to it racily with it determining
-    // it had no work remaining). Therefore, we're done if there is no more work
-    // on TaskScheduler either (there can be TaskScheduler work remaining if
-    // DisallowRunTasks() preempted work and/or the last RunUntilIdle() posted
-    // more TaskScheduler tasks).
-    // Note: this last |if| couldn't be turned into a |do {} while();|. A
-    // conditional loop makes it such that |continue;| results in checking the
-    // condition (not unconditionally loop again) which would be incorrect for
-    // the above logic as it'd then be possible for a TaskScheduler task to be
-    // running during the DisallowRunTasks() test, causing it to fail, but then
-    // post to the main thread and complete before the loop's condition is
-    // verified which could result in HasIncompleteUndelayedTasksForTesting()
-    // returning false and the loop erroneously exiting with a pending task on
-    // the main thread.
-    if (!task_tracker_->HasIncompleteUndelayedTasksForTesting())
-      break;
-  }
-
-  // The above loop always ends with running tasks being disallowed. Re-enable
-  // parallel execution before returning unless in ExecutionMode::QUEUED.
-  if (execution_control_mode_ != ExecutionMode::QUEUED)
-    task_tracker_->AllowRunTasks();
-}
-
-void ScopedTaskEnvironment::FastForwardBy(TimeDelta delta) {
-  DCHECK(mock_time_task_runner_);
-  mock_time_task_runner_->FastForwardBy(delta);
-}
-
-void ScopedTaskEnvironment::FastForwardUntilNoTasksRemain() {
-  DCHECK(mock_time_task_runner_);
-  mock_time_task_runner_->FastForwardUntilNoTasksRemain();
-}
-
-const TickClock* ScopedTaskEnvironment::GetMockTickClock() {
-  DCHECK(mock_time_task_runner_);
-  return mock_time_task_runner_->GetMockTickClock();
-}
-
-std::unique_ptr<TickClock> ScopedTaskEnvironment::DeprecatedGetMockTickClock() {
-  DCHECK(mock_time_task_runner_);
-  return mock_time_task_runner_->DeprecatedGetMockTickClock();
-}
-
-size_t ScopedTaskEnvironment::GetPendingMainThreadTaskCount() const {
-  DCHECK(mock_time_task_runner_);
-  return mock_time_task_runner_->GetPendingTaskCount();
-}
-
-TimeDelta ScopedTaskEnvironment::NextMainThreadPendingTaskDelay() const {
-  DCHECK(mock_time_task_runner_);
-  return mock_time_task_runner_->NextPendingTaskDelay();
-}
-
-ScopedTaskEnvironment::TestTaskTracker::TestTaskTracker()
-    : internal::TaskSchedulerImpl::TaskTrackerImpl("ScopedTaskEnvironment"),
-      can_run_tasks_cv_(&lock_),
-      task_completed_(&lock_) {}
-
-void ScopedTaskEnvironment::TestTaskTracker::AllowRunTasks() {
-  AutoLock auto_lock(lock_);
-  can_run_tasks_ = true;
-  can_run_tasks_cv_.Broadcast();
-}
-
-bool ScopedTaskEnvironment::TestTaskTracker::DisallowRunTasks() {
-  AutoLock auto_lock(lock_);
-
-  // Can't disallow run task if there are tasks running.
-  if (num_tasks_running_ > 0) {
-    // Attempt to wait a bit so that the caller doesn't busy-loop with the same
-    // set of pending work. A short wait is required to avoid deadlock
-    // scenarios. See DisallowRunTasks()'s declaration for more details.
-    task_completed_.TimedWait(TimeDelta::FromMilliseconds(1));
-    return false;
-  }
-
-  can_run_tasks_ = false;
-  return true;
-}
-
-void ScopedTaskEnvironment::TestTaskTracker::RunOrSkipTask(
-    internal::Task task,
-    internal::Sequence* sequence,
-    bool can_run_task) {
-  {
-    AutoLock auto_lock(lock_);
-
-    while (!can_run_tasks_)
-      can_run_tasks_cv_.Wait();
-
-    ++num_tasks_running_;
-  }
-
-  internal::TaskSchedulerImpl::TaskTrackerImpl::RunOrSkipTask(
-      std::move(task), sequence, can_run_task);
-
-  {
-    AutoLock auto_lock(lock_);
-
-    CHECK_GT(num_tasks_running_, 0);
-    CHECK(can_run_tasks_);
-
-    --num_tasks_running_;
-
-    task_completed_.Broadcast();
-  }
-}
-
-}  // namespace test
-}  // namespace base
diff --git a/base/test/scoped_task_environment.h b/base/test/scoped_task_environment.h
deleted file mode 100644
index 038cca3..0000000
--- a/base/test/scoped_task_environment.h
+++ /dev/null
@@ -1,177 +0,0 @@
-// Copyright 2017 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_SCOPED_TASK_ENVIRONMENT_H_
-#define BASE_TEST_SCOPED_TASK_ENVIRONMENT_H_
-
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/single_thread_task_runner.h"
-#include "base/task_scheduler/lazy_task_runner.h"
-#include "build_config.h"
-
-namespace base {
-
-namespace internal {
-class ScopedSetSequenceLocalStorageMapForCurrentThread;
-class SequenceLocalStorageMap;
-}  // namespace internal
-
-class FileDescriptorWatcher;
-class MessageLoop;
-class TaskScheduler;
-class TestMockTimeTaskRunner;
-class TickClock;
-
-namespace test {
-
-// ScopedTaskEnvironment allows usage of these APIs within its scope:
-// - (Thread|Sequenced)TaskRunnerHandle, on the thread where it lives
-// - base/task_scheduler/post_task.h, on any thread
-//
-// Tests that need either of these APIs should instantiate a
-// ScopedTaskEnvironment.
-//
-// Tasks posted to the (Thread|Sequenced)TaskRunnerHandle run synchronously when
-// RunLoop::Run(UntilIdle) or ScopedTaskEnvironment::RunUntilIdle is called on
-// the thread where the ScopedTaskEnvironment lives.
-//
-// Tasks posted through base/task_scheduler/post_task.h run on dedicated
-// threads. If ExecutionMode is QUEUED, they run when RunUntilIdle() or
-// ~ScopedTaskEnvironment is called. If ExecutionMode is ASYNC, they run
-// as they are posted.
-//
-// All methods of ScopedTaskEnvironment must be called from the same thread.
-//
-// Usage:
-//
-//   class MyTestFixture : public testing::Test {
-//    public:
-//     (...)
-//
-//    protected:
-//     // Must be the first member (or at least before any member that cares
-//     // about tasks) to be initialized first and destroyed last. protected
-//     // instead of private visibility will allow controlling the task
-//     // environment (e.g. clock) once such features are added (see design doc
-//     // below for details), until then it at least doesn't hurt :).
-//     base::test::ScopedTaskEnvironment scoped_task_environment_;
-//
-//     // Other members go here (or further below in private section.)
-//   };
-//
-// Design and future improvements documented in
-// https://docs.google.com/document/d/1QabRo8c7D9LsYY3cEcaPQbOCLo8Tu-6VLykYXyl3Pkk/edit
-class ScopedTaskEnvironment {
- public:
-  enum class MainThreadType {
-    // The main thread doesn't pump system messages.
-    DEFAULT,
-    // The main thread doesn't pump system messages and uses a mock clock for
-    // delayed tasks (controllable via FastForward*() methods).
-    // TODO(gab): Make this the default |main_thread_type|.
-    // TODO(gab): Also mock the TaskScheduler's clock simultaneously (this
-    // currently only mocks the main thread's clock).
-    MOCK_TIME,
-    // The main thread pumps UI messages.
-    UI,
-    // The main thread pumps asynchronous IO messages and supports the
-    // FileDescriptorWatcher API on POSIX.
-    IO,
-  };
-
-  enum class ExecutionMode {
-    // Tasks are queued and only executed when RunUntilIdle() is explicitly
-    // called.
-    QUEUED,
-    // Tasks run as they are posted. RunUntilIdle() can still be used to block
-    // until done.
-    ASYNC,
-  };
-
-  ScopedTaskEnvironment(
-      MainThreadType main_thread_type = MainThreadType::DEFAULT,
-      ExecutionMode execution_control_mode = ExecutionMode::ASYNC);
-
-  // Waits until no undelayed TaskScheduler tasks remain. Then, unregisters the
-  // TaskScheduler and the (Thread|Sequenced)TaskRunnerHandle.
-  ~ScopedTaskEnvironment();
-
-  // Returns a TaskRunner that schedules tasks on the main thread.
-  scoped_refptr<base::SingleThreadTaskRunner> GetMainThreadTaskRunner();
-
-  // Returns whether the main thread's TaskRunner has pending tasks.
-  bool MainThreadHasPendingTask() const;
-
-  // Runs tasks until both the (Thread|Sequenced)TaskRunnerHandle and the
-  // TaskScheduler's non-delayed queues are empty.
-  void RunUntilIdle();
-
-  // Only valid for instances with a MOCK_TIME MainThreadType. Fast-forwards
-  // virtual time by |delta|, causing all tasks on the main thread with a
-  // remaining delay less than or equal to |delta| to be executed before this
-  // returns. |delta| must be non-negative.
-  // TODO(gab): Make this apply to TaskScheduler delayed tasks as well
-  // (currently only main thread time is mocked).
-  void FastForwardBy(TimeDelta delta);
-
-  // Only valid for instances with a MOCK_TIME MainThreadType.
-  // Short for FastForwardBy(TimeDelta::Max()).
-  void FastForwardUntilNoTasksRemain();
-
-  // Only valid for instances with a MOCK_TIME MainThreadType.  Returns a
-  // TickClock whose time is updated by FastForward(By|UntilNoTasksRemain).
-  const TickClock* GetMockTickClock();
-  std::unique_ptr<TickClock> DeprecatedGetMockTickClock();
-
-  // Only valid for instances with a MOCK_TIME MainThreadType.
-  // Returns the number of pending tasks of the main thread's TaskRunner.
-  size_t GetPendingMainThreadTaskCount() const;
-
-  // Only valid for instances with a MOCK_TIME MainThreadType.
-  // Returns the delay until the next delayed pending task of the main thread's
-  // TaskRunner.
-  TimeDelta NextMainThreadPendingTaskDelay() const;
-
- private:
-  class TestTaskTracker;
-
-  const ExecutionMode execution_control_mode_;
-
-  // Exactly one of these will be non-null to provide the task environment on
-  // the main thread. Users of this class should NOT rely on the presence of a
-  // MessageLoop beyond (Thread|Sequenced)TaskRunnerHandle and RunLoop as
-  // the backing implementation of each MainThreadType may change over time.
-  const std::unique_ptr<MessageLoop> message_loop_;
-  const scoped_refptr<TestMockTimeTaskRunner> mock_time_task_runner_;
-
-  // Non-null in MOCK_TIME, where an explicit SequenceLocalStorageMap needs to
-  // be provided. TODO(gab): This can be removed once mock time support is added
-  // to MessageLoop directly.
-  const std::unique_ptr<internal::SequenceLocalStorageMap> slsm_for_mock_time_;
-  const std::unique_ptr<
-      internal::ScopedSetSequenceLocalStorageMapForCurrentThread>
-      slsm_registration_for_mock_time_;
-
-#if defined(OS_POSIX)
-  // Enables the FileDescriptorWatcher API iff running a MainThreadType::IO.
-  const std::unique_ptr<FileDescriptorWatcher> file_descriptor_watcher_;
-#endif
-
-  const TaskScheduler* task_scheduler_ = nullptr;
-
-  // Owned by |task_scheduler_|.
-  TestTaskTracker* const task_tracker_;
-
-  // Ensures destruction of lazy TaskRunners when this is destroyed.
-  internal::ScopedLazyTaskRunnerListForTesting
-      scoped_lazy_task_runner_list_for_testing_;
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedTaskEnvironment);
-};
-
-}  // namespace test
-}  // namespace base
-
-#endif  // BASE_TEST_SCOPED_ASYNC_TASK_SCHEDULER_H_
diff --git a/base/test/test_mock_time_task_runner.cc b/base/test/test_mock_time_task_runner.cc
deleted file mode 100644
index c74d14e..0000000
--- a/base/test/test_mock_time_task_runner.cc
+++ /dev/null
@@ -1,448 +0,0 @@
-// Copyright 2015 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/test/test_mock_time_task_runner.h"
-
-#include <utility>
-
-#include "base/containers/circular_deque.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/ptr_util.h"
-#include "base/memory/ref_counted.h"
-#include "base/threading/thread_task_runner_handle.h"
-
-namespace base {
-namespace {
-
-// LegacyMockTickClock and LegacyMockClock are used by deprecated APIs of
-// TestMockTimeTaskRunner. They will be removed after updating callers of
-// GetMockClock() and GetMockTickClock() to GetMockClockPtr() and
-// GetMockTickClockPtr().
-class LegacyMockTickClock : public TickClock {
- public:
-  explicit LegacyMockTickClock(
-      scoped_refptr<const TestMockTimeTaskRunner> task_runner)
-      : task_runner_(std::move(task_runner)) {}
-
-  // TickClock:
-  TimeTicks NowTicks() const override { return task_runner_->NowTicks(); }
-
- private:
-  scoped_refptr<const TestMockTimeTaskRunner> task_runner_;
-
-  DISALLOW_COPY_AND_ASSIGN(LegacyMockTickClock);
-};
-
-class LegacyMockClock : public Clock {
- public:
-  explicit LegacyMockClock(
-      scoped_refptr<const TestMockTimeTaskRunner> task_runner)
-      : task_runner_(std::move(task_runner)) {}
-
-  // Clock:
-  Time Now() const override { return task_runner_->Now(); }
-
- private:
-  scoped_refptr<const TestMockTimeTaskRunner> task_runner_;
-
-  DISALLOW_COPY_AND_ASSIGN(LegacyMockClock);
-};
-
-// A SingleThreadTaskRunner which forwards everything to its |target_|. This is
-// useful to break ownership chains when it is known that |target_| will outlive
-// the NonOwningProxyTaskRunner it's injected into. In particular,
-// TestMockTimeTaskRunner is forced to be ref-counted by virtue of being a
-// SingleThreadTaskRunner. As such it is impossible for it to have a
-// ThreadTaskRunnerHandle member that points back to itself as the
-// ThreadTaskRunnerHandle which it owns would hold a ref back to it. To break
-// this dependency cycle, the ThreadTaskRunnerHandle is instead handed a
-// NonOwningProxyTaskRunner which allows the TestMockTimeTaskRunner to not hand
-// a ref to its ThreadTaskRunnerHandle while promising in return that it will
-// outlive that ThreadTaskRunnerHandle instance.
-class NonOwningProxyTaskRunner : public SingleThreadTaskRunner {
- public:
-  explicit NonOwningProxyTaskRunner(SingleThreadTaskRunner* target)
-      : target_(target) {
-    DCHECK(target_);
-  }
-
-  // SingleThreadTaskRunner:
-  bool RunsTasksInCurrentSequence() const override {
-    return target_->RunsTasksInCurrentSequence();
-  }
-  bool PostDelayedTask(const Location& from_here,
-                       OnceClosure task,
-                       TimeDelta delay) override {
-    return target_->PostDelayedTask(from_here, std::move(task), delay);
-  }
-  bool PostNonNestableDelayedTask(const Location& from_here,
-                                  OnceClosure task,
-                                  TimeDelta delay) override {
-    return target_->PostNonNestableDelayedTask(from_here, std::move(task),
-                                               delay);
-  }
-
- private:
-  friend class RefCountedThreadSafe<NonOwningProxyTaskRunner>;
-  ~NonOwningProxyTaskRunner() override = default;
-
-  SingleThreadTaskRunner* const target_;
-
-  DISALLOW_COPY_AND_ASSIGN(NonOwningProxyTaskRunner);
-};
-
-}  // namespace
-
-// TestMockTimeTaskRunner::TestOrderedPendingTask -----------------------------
-
-// Subclass of TestPendingTask which has a strictly monotonically increasing ID
-// for every task, so that tasks posted with the same 'time to run' can be run
-// in the order of being posted.
-struct TestMockTimeTaskRunner::TestOrderedPendingTask
-    : public base::TestPendingTask {
-  TestOrderedPendingTask();
-  TestOrderedPendingTask(const Location& location,
-                         OnceClosure task,
-                         TimeTicks post_time,
-                         TimeDelta delay,
-                         size_t ordinal,
-                         TestNestability nestability);
-  TestOrderedPendingTask(TestOrderedPendingTask&&);
-  ~TestOrderedPendingTask();
-
-  TestOrderedPendingTask& operator=(TestOrderedPendingTask&&);
-
-  size_t ordinal;
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(TestOrderedPendingTask);
-};
-
-TestMockTimeTaskRunner::TestOrderedPendingTask::TestOrderedPendingTask()
-    : ordinal(0) {
-}
-
-TestMockTimeTaskRunner::TestOrderedPendingTask::TestOrderedPendingTask(
-    TestOrderedPendingTask&&) = default;
-
-TestMockTimeTaskRunner::TestOrderedPendingTask::TestOrderedPendingTask(
-    const Location& location,
-    OnceClosure task,
-    TimeTicks post_time,
-    TimeDelta delay,
-    size_t ordinal,
-    TestNestability nestability)
-    : base::TestPendingTask(location,
-                            std::move(task),
-                            post_time,
-                            delay,
-                            nestability),
-      ordinal(ordinal) {}
-
-TestMockTimeTaskRunner::TestOrderedPendingTask::~TestOrderedPendingTask() =
-    default;
-
-TestMockTimeTaskRunner::TestOrderedPendingTask&
-TestMockTimeTaskRunner::TestOrderedPendingTask::operator=(
-    TestOrderedPendingTask&&) = default;
-
-// TestMockTimeTaskRunner -----------------------------------------------------
-
-// TODO(gab): This should also set the SequenceToken for the current thread.
-// Ref. TestMockTimeTaskRunner::RunsTasksInCurrentSequence().
-TestMockTimeTaskRunner::ScopedContext::ScopedContext(
-    scoped_refptr<TestMockTimeTaskRunner> scope)
-    : on_destroy_(ThreadTaskRunnerHandle::OverrideForTesting(scope)) {
-  scope->RunUntilIdle();
-}
-
-TestMockTimeTaskRunner::ScopedContext::~ScopedContext() = default;
-
-bool TestMockTimeTaskRunner::TemporalOrder::operator()(
-    const TestOrderedPendingTask& first_task,
-    const TestOrderedPendingTask& second_task) const {
-  if (first_task.GetTimeToRun() == second_task.GetTimeToRun())
-    return first_task.ordinal > second_task.ordinal;
-  return first_task.GetTimeToRun() > second_task.GetTimeToRun();
-}
-
-TestMockTimeTaskRunner::TestMockTimeTaskRunner(Type type)
-    : TestMockTimeTaskRunner(Time::UnixEpoch(), TimeTicks(), type) {}
-
-TestMockTimeTaskRunner::TestMockTimeTaskRunner(Time start_time,
-                                               TimeTicks start_ticks,
-                                               Type type)
-    : now_(start_time),
-      now_ticks_(start_ticks),
-      tasks_lock_cv_(&tasks_lock_),
-      mock_clock_(this) {
-  if (type == Type::kBoundToThread) {
-    RunLoop::RegisterDelegateForCurrentThread(this);
-    thread_task_runner_handle_ = std::make_unique<ThreadTaskRunnerHandle>(
-        MakeRefCounted<NonOwningProxyTaskRunner>(this));
-  }
-}
-
-TestMockTimeTaskRunner::~TestMockTimeTaskRunner() = default;
-
-void TestMockTimeTaskRunner::FastForwardBy(TimeDelta delta) {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  DCHECK_GE(delta, TimeDelta());
-
-  const TimeTicks original_now_ticks = NowTicks();
-  ProcessAllTasksNoLaterThan(delta);
-  ForwardClocksUntilTickTime(original_now_ticks + delta);
-}
-
-void TestMockTimeTaskRunner::AdvanceMockTickClock(TimeDelta delta) {
-  ForwardClocksUntilTickTime(NowTicks() + delta);
-}
-
-void TestMockTimeTaskRunner::RunUntilIdle() {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  ProcessAllTasksNoLaterThan(TimeDelta());
-}
-
-void TestMockTimeTaskRunner::FastForwardUntilNoTasksRemain() {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  ProcessAllTasksNoLaterThan(TimeDelta::Max());
-}
-
-void TestMockTimeTaskRunner::ClearPendingTasks() {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  AutoLock scoped_lock(tasks_lock_);
-  while (!tasks_.empty())
-    tasks_.pop();
-}
-
-Time TestMockTimeTaskRunner::Now() const {
-  AutoLock scoped_lock(tasks_lock_);
-  return now_;
-}
-
-TimeTicks TestMockTimeTaskRunner::NowTicks() const {
-  AutoLock scoped_lock(tasks_lock_);
-  return now_ticks_;
-}
-
-std::unique_ptr<Clock> TestMockTimeTaskRunner::DeprecatedGetMockClock() const {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  return std::make_unique<LegacyMockClock>(this);
-}
-
-Clock* TestMockTimeTaskRunner::GetMockClock() const {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  return &mock_clock_;
-}
-
-std::unique_ptr<TickClock> TestMockTimeTaskRunner::DeprecatedGetMockTickClock()
-    const {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  return std::make_unique<LegacyMockTickClock>(this);
-}
-
-const TickClock* TestMockTimeTaskRunner::GetMockTickClock() const {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  return &mock_clock_;
-}
-
-base::circular_deque<TestPendingTask>
-TestMockTimeTaskRunner::TakePendingTasks() {
-  AutoLock scoped_lock(tasks_lock_);
-  base::circular_deque<TestPendingTask> tasks;
-  while (!tasks_.empty()) {
-    // It's safe to remove const and consume |task| here, since |task| is not
-    // used for ordering the item.
-    if (!tasks_.top().task.IsCancelled()) {
-      tasks.push_back(
-          std::move(const_cast<TestOrderedPendingTask&>(tasks_.top())));
-    }
-    tasks_.pop();
-  }
-  return tasks;
-}
-
-bool TestMockTimeTaskRunner::HasPendingTask() {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  AutoLock scoped_lock(tasks_lock_);
-  while (!tasks_.empty() && tasks_.top().task.IsCancelled())
-    tasks_.pop();
-  return !tasks_.empty();
-}
-
-size_t TestMockTimeTaskRunner::GetPendingTaskCount() {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  AutoLock scoped_lock(tasks_lock_);
-  TaskPriorityQueue preserved_tasks;
-  while (!tasks_.empty()) {
-    if (!tasks_.top().task.IsCancelled()) {
-      preserved_tasks.push(
-          std::move(const_cast<TestOrderedPendingTask&>(tasks_.top())));
-    }
-    tasks_.pop();
-  }
-  tasks_.swap(preserved_tasks);
-  return tasks_.size();
-}
-
-TimeDelta TestMockTimeTaskRunner::NextPendingTaskDelay() {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  AutoLock scoped_lock(tasks_lock_);
-  while (!tasks_.empty() && tasks_.top().task.IsCancelled())
-    tasks_.pop();
-  return tasks_.empty() ? TimeDelta::Max()
-                        : tasks_.top().GetTimeToRun() - now_ticks_;
-}
-
-// TODO(gab): Combine |thread_checker_| with a SequenceToken to differentiate
-// between tasks running in the scope of this TestMockTimeTaskRunner and other
-// task runners sharing this thread. http://crbug.com/631186
-bool TestMockTimeTaskRunner::RunsTasksInCurrentSequence() const {
-  return thread_checker_.CalledOnValidThread();
-}
-
-bool TestMockTimeTaskRunner::PostDelayedTask(const Location& from_here,
-                                             OnceClosure task,
-                                             TimeDelta delay) {
-  AutoLock scoped_lock(tasks_lock_);
-  tasks_.push(TestOrderedPendingTask(from_here, std::move(task), now_ticks_,
-                                     delay, next_task_ordinal_++,
-                                     TestPendingTask::NESTABLE));
-  tasks_lock_cv_.Signal();
-  return true;
-}
-
-bool TestMockTimeTaskRunner::PostNonNestableDelayedTask(
-    const Location& from_here,
-    OnceClosure task,
-    TimeDelta delay) {
-  return PostDelayedTask(from_here, std::move(task), delay);
-}
-
-void TestMockTimeTaskRunner::OnBeforeSelectingTask() {
-  // Empty default implementation.
-}
-
-void TestMockTimeTaskRunner::OnAfterTimePassed() {
-  // Empty default implementation.
-}
-
-void TestMockTimeTaskRunner::OnAfterTaskRun() {
-  // Empty default implementation.
-}
-
-void TestMockTimeTaskRunner::ProcessAllTasksNoLaterThan(TimeDelta max_delta) {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  DCHECK_GE(max_delta, TimeDelta());
-
-  // Multiple test task runners can share the same thread for determinism in
-  // unit tests. Make sure this TestMockTimeTaskRunner's tasks run in its scope.
-  ScopedClosureRunner undo_override;
-  if (!ThreadTaskRunnerHandle::IsSet() ||
-      ThreadTaskRunnerHandle::Get() != this) {
-    undo_override = ThreadTaskRunnerHandle::OverrideForTesting(this);
-  }
-
-  const TimeTicks original_now_ticks = NowTicks();
-  while (!quit_run_loop_) {
-    OnBeforeSelectingTask();
-    TestPendingTask task_info;
-    if (!DequeueNextTask(original_now_ticks, max_delta, &task_info))
-      break;
-    if (task_info.task.IsCancelled())
-      continue;
-    // If tasks were posted with a negative delay, task_info.GetTimeToRun() will
-    // be less than |now_ticks_|. ForwardClocksUntilTickTime() takes care of not
-    // moving the clock backwards in this case.
-    ForwardClocksUntilTickTime(task_info.GetTimeToRun());
-    std::move(task_info.task).Run();
-    OnAfterTaskRun();
-  }
-}
-
-void TestMockTimeTaskRunner::ForwardClocksUntilTickTime(TimeTicks later_ticks) {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  {
-    AutoLock scoped_lock(tasks_lock_);
-    if (later_ticks <= now_ticks_)
-      return;
-
-    now_ += later_ticks - now_ticks_;
-    now_ticks_ = later_ticks;
-  }
-  OnAfterTimePassed();
-}
-
-bool TestMockTimeTaskRunner::DequeueNextTask(const TimeTicks& reference,
-                                             const TimeDelta& max_delta,
-                                             TestPendingTask* next_task) {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  AutoLock scoped_lock(tasks_lock_);
-  if (!tasks_.empty() &&
-      (tasks_.top().GetTimeToRun() - reference) <= max_delta) {
-    // It's safe to remove const and consume |task| here, since |task| is not
-    // used for ordering the item.
-    *next_task = std::move(const_cast<TestOrderedPendingTask&>(tasks_.top()));
-    tasks_.pop();
-    return true;
-  }
-  return false;
-}
-
-void TestMockTimeTaskRunner::Run(bool application_tasks_allowed) {
-  DCHECK(thread_checker_.CalledOnValidThread());
-
-  // Since TestMockTimeTaskRunner doesn't process system messages: there's no
-  // hope for anything but an application task to call Quit(). If this RunLoop
-  // can't process application tasks (i.e. disallowed by default in nested
-  // RunLoops) it's guaranteed to hang...
-  DCHECK(application_tasks_allowed)
-      << "This is a nested RunLoop instance and needs to be of "
-         "Type::kNestableTasksAllowed.";
-
-  while (!quit_run_loop_) {
-    RunUntilIdle();
-    if (quit_run_loop_ || ShouldQuitWhenIdle())
-      break;
-
-    // Peek into |tasks_| to perform one of two things:
-    //   A) If there are no remaining tasks, wait until one is posted and
-    //      restart from the top.
-    //   B) If there is a remaining delayed task. Fast-forward to reach the next
-    //      round of tasks.
-    TimeDelta auto_fast_forward_by;
-    {
-      AutoLock scoped_lock(tasks_lock_);
-      if (tasks_.empty()) {
-        while (tasks_.empty())
-          tasks_lock_cv_.Wait();
-        continue;
-      }
-      auto_fast_forward_by = tasks_.top().GetTimeToRun() - now_ticks_;
-    }
-    FastForwardBy(auto_fast_forward_by);
-  }
-  quit_run_loop_ = false;
-}
-
-void TestMockTimeTaskRunner::Quit() {
-  DCHECK(thread_checker_.CalledOnValidThread());
-  quit_run_loop_ = true;
-}
-
-void TestMockTimeTaskRunner::EnsureWorkScheduled() {
-  // Nothing to do: TestMockTimeTaskRunner::Run() will always process tasks and
-  // doesn't need an extra kick on nested runs.
-}
-
-TimeTicks TestMockTimeTaskRunner::MockClock::NowTicks() const {
-  return task_runner_->NowTicks();
-}
-
-Time TestMockTimeTaskRunner::MockClock::Now() const {
-  return task_runner_->Now();
-}
-
-}  // namespace base
diff --git a/base/test/test_mock_time_task_runner.h b/base/test/test_mock_time_task_runner.h
deleted file mode 100644
index 993db05..0000000
--- a/base/test/test_mock_time_task_runner.h
+++ /dev/null
@@ -1,294 +0,0 @@
-// Copyright 2015 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_MOCK_TIME_TASK_RUNNER_H_
-#define BASE_TEST_TEST_MOCK_TIME_TASK_RUNNER_H_
-
-#include <stddef.h>
-
-#include <memory>
-#include <queue>
-#include <vector>
-
-#include "base/callback.h"
-#include "base/callback_helpers.h"
-#include "base/containers/circular_deque.h"
-#include "base/macros.h"
-#include "base/run_loop.h"
-#include "base/single_thread_task_runner.h"
-#include "base/synchronization/condition_variable.h"
-#include "base/synchronization/lock.h"
-#include "base/test/test_pending_task.h"
-#include "base/threading/thread_checker_impl.h"
-#include "base/time/clock.h"
-#include "base/time/tick_clock.h"
-#include "base/time/time.h"
-
-namespace base {
-
-class ThreadTaskRunnerHandle;
-
-// Runs pending tasks in the order of the tasks' post time + delay, and keeps
-// track of a mock (virtual) tick clock time that can be fast-forwarded.
-//
-// TestMockTimeTaskRunner has the following properties:
-//
-//   - Methods RunsTasksInCurrentSequence() and Post[Delayed]Task() can be
-//     called from any thread, but the rest of the methods must be called on
-//     the same thread the TestMockTimeTaskRunner was created on.
-//   - It allows for reentrancy, in that it handles the running of tasks that in
-//     turn call back into it (e.g., to post more tasks).
-//   - Tasks are stored in a priority queue, and executed in the increasing
-//     order of post time + delay, but ignoring nestability.
-//   - It does not check for overflow when doing time arithmetic. A sufficient
-//     condition for preventing overflows is to make sure that the sum of all
-//     posted task delays and fast-forward increments is still representable by
-//     a TimeDelta, and that adding this delta to the starting values of Time
-//     and TickTime is still within their respective range.
-//
-// A TestMockTimeTaskRunner of Type::kBoundToThread has the following additional
-// properties:
-//   - Thread/SequencedTaskRunnerHandle refers to it on its thread.
-//   - It can be driven by a RunLoop on the thread it was created on.
-//     RunLoop::Run() will result in running non-delayed tasks until idle and
-//     then, if RunLoop::QuitWhenIdle() wasn't invoked, fast-forwarding time to
-//     the next delayed task and looping again. And so on, until either
-//     RunLoop::Quit() is invoked (quits immediately after the current task) or
-//     RunLoop::QuitWhenIdle() is invoked (quits before having to fast forward
-//     time once again). Should RunLoop::Run() process all tasks (including
-//     delayed ones), it will block until more are posted. As usual,
-//     RunLoop::RunUntilIdle() is equivalent to RunLoop::Run() followed by an
-//     immediate RunLoop::QuitWhenIdle().
-//    -
-//
-// This is a slightly more sophisticated version of TestSimpleTaskRunner, in
-// that it supports running delayed tasks in the correct temporal order.
-class TestMockTimeTaskRunner : public SingleThreadTaskRunner,
-                               public RunLoop::Delegate {
- public:
-  // Everything that is executed in the scope of a ScopedContext will behave as
-  // though it ran under |scope| (i.e. ThreadTaskRunnerHandle,
-  // RunsTasksInCurrentSequence, etc.). This allows the test body to be all in
-  // one block when multiple TestMockTimeTaskRunners share the main thread.
-  // Note: RunLoop isn't supported: will DCHECK if used inside a ScopedContext.
-  //
-  // For example:
-  //
-  //   class ExampleFixture {
-  //    protected:
-  //     DoBarOnFoo() {
-  //       DCHECK(foo_task_runner_->RunsOnCurrentThread());
-  //       EXPECT_EQ(foo_task_runner_, ThreadTaskRunnerHandle::Get());
-  //       DoBar();
-  //     }
-  //
-  //     // Mock main task runner.
-  //     base::MessageLoop message_loop_;
-  //     base::ScopedMockTimeMessageLoopTaskRunner main_task_runner_;
-  //
-  //     // Mock foo task runner.
-  //     scoped_refptr<TestMockTimeTaskRunner> foo_task_runner_ =
-  //         new TestMockTimeTaskRunner();
-  //   };
-  //
-  //   TEST_F(ExampleFixture, DoBarOnFoo) {
-  //     DoThingsOnMain();
-  //     {
-  //       TestMockTimeTaskRunner::ScopedContext scoped_context(
-  //           foo_task_runner_.get());
-  //       DoBarOnFoo();
-  //     }
-  //     DoMoreThingsOnMain();
-  //   }
-  //
-  class ScopedContext {
-   public:
-    // Note: |scope| is ran until idle as part of this constructor to ensure
-    // that anything which runs in the underlying scope runs after any already
-    // pending tasks (the contrary would break the SequencedTaskRunner
-    // contract).
-    explicit ScopedContext(scoped_refptr<TestMockTimeTaskRunner> scope);
-    ~ScopedContext();
-
-   private:
-    ScopedClosureRunner on_destroy_;
-    DISALLOW_COPY_AND_ASSIGN(ScopedContext);
-  };
-
-  enum class Type {
-    // A TestMockTimeTaskRunner which can only be driven directly through its
-    // API. Thread/SequencedTaskRunnerHandle will refer to it only in the scope
-    // of its tasks.
-    kStandalone,
-    // A TestMockTimeTaskRunner which will associate to the thread it is created
-    // on, enabling RunLoop to drive it and making
-    // Thread/SequencedTaskRunnerHandle refer to it on that thread.
-    kBoundToThread,
-  };
-
-  // Constructs an instance whose virtual time will start at the Unix epoch, and
-  // whose time ticks will start at zero.
-  TestMockTimeTaskRunner(Type type = Type::kStandalone);
-
-  // Constructs an instance starting at the given virtual time and time ticks.
-  TestMockTimeTaskRunner(Time start_time,
-                         TimeTicks start_ticks,
-                         Type type = Type::kStandalone);
-
-  // Fast-forwards virtual time by |delta|, causing all tasks with a remaining
-  // delay less than or equal to |delta| to be executed. |delta| must be
-  // non-negative.
-  void FastForwardBy(TimeDelta delta);
-
-  // Fast-forwards virtual time by |delta| but not causing any task execution.
-  void AdvanceMockTickClock(TimeDelta delta);
-
-  // Fast-forwards virtual time just until all tasks are executed.
-  void FastForwardUntilNoTasksRemain();
-
-  // Executes all tasks that have no remaining delay. Tasks with a remaining
-  // delay greater than zero will remain enqueued, and no virtual time will
-  // elapse.
-  void RunUntilIdle();
-
-  // Clears the queue of pending tasks without running them.
-  void ClearPendingTasks();
-
-  // Returns the current virtual time (initially starting at the Unix epoch).
-  Time Now() const;
-
-  // Returns the current virtual tick time (initially starting at 0).
-  TimeTicks NowTicks() const;
-
-  // Returns a Clock that uses the virtual time of |this| as its time source.
-  // The returned Clock will hold a reference to |this|.
-  // TODO(tzik): Remove DeprecatedGetMockClock() after updating all callers to
-  // use non-owning Clock.
-  std::unique_ptr<Clock> DeprecatedGetMockClock() const;
-  Clock* GetMockClock() const;
-
-  // Returns a TickClock that uses the virtual time ticks of |this| as its tick
-  // source. The returned TickClock will hold a reference to |this|.
-  // TODO(tzik): Replace Remove DeprecatedGetMockTickClock() after updating all
-  // callers to use non-owning TickClock.
-  std::unique_ptr<TickClock> DeprecatedGetMockTickClock() const;
-  const TickClock* GetMockTickClock() const;
-
-  // Cancelled pending tasks get pruned automatically.
-  base::circular_deque<TestPendingTask> TakePendingTasks();
-  bool HasPendingTask();
-  size_t GetPendingTaskCount();
-  TimeDelta NextPendingTaskDelay();
-
-  // SingleThreadTaskRunner:
-  bool RunsTasksInCurrentSequence() const override;
-  bool PostDelayedTask(const Location& from_here,
-                       OnceClosure task,
-                       TimeDelta delay) override;
-  bool PostNonNestableDelayedTask(const Location& from_here,
-                                  OnceClosure task,
-                                  TimeDelta delay) override;
-
- protected:
-  ~TestMockTimeTaskRunner() override;
-
-  // Called before the next task to run is selected, so that subclasses have a
-  // last chance to make sure all tasks are posted.
-  virtual void OnBeforeSelectingTask();
-
-  // Called after the current mock time has been incremented so that subclasses
-  // can react to the passing of time.
-  virtual void OnAfterTimePassed();
-
-  // Called after each task is run so that subclasses may perform additional
-  // activities, e.g., pump additional task runners.
-  virtual void OnAfterTaskRun();
-
- private:
-  // MockClock implements TickClock and Clock. Always returns the then-current
-  // mock time of |task_runner| as the current time or time ticks.
-  class MockClock : public TickClock, public Clock {
-   public:
-    explicit MockClock(TestMockTimeTaskRunner* task_runner)
-        : task_runner_(task_runner) {}
-
-    // TickClock:
-    TimeTicks NowTicks() const override;
-
-    // Clock:
-    Time Now() const override;
-
-   private:
-    TestMockTimeTaskRunner* task_runner_;
-
-    DISALLOW_COPY_AND_ASSIGN(MockClock);
-  };
-
-  struct TestOrderedPendingTask;
-
-  // Predicate that defines a strict weak temporal ordering of tasks.
-  class TemporalOrder {
-   public:
-    bool operator()(const TestOrderedPendingTask& first_task,
-                    const TestOrderedPendingTask& second_task) const;
-  };
-
-  typedef std::priority_queue<TestOrderedPendingTask,
-                              std::vector<TestOrderedPendingTask>,
-                              TemporalOrder> TaskPriorityQueue;
-
-  // Core of the implementation for all flavors of fast-forward methods. Given a
-  // non-negative |max_delta|, runs all tasks with a remaining delay less than
-  // or equal to |max_delta|, and moves virtual time forward as needed for each
-  // processed task. Pass in TimeDelta::Max() as |max_delta| to run all tasks.
-  void ProcessAllTasksNoLaterThan(TimeDelta max_delta);
-
-  // Forwards |now_ticks_| until it equals |later_ticks|, and forwards |now_| by
-  // the same amount. Calls OnAfterTimePassed() if |later_ticks| > |now_ticks_|.
-  // Does nothing if |later_ticks| <= |now_ticks_|.
-  void ForwardClocksUntilTickTime(TimeTicks later_ticks);
-
-  // Returns the |next_task| to run if there is any with a running time that is
-  // at most |reference| + |max_delta|. This additional complexity is required
-  // so that |max_delta| == TimeDelta::Max() can be supported.
-  bool DequeueNextTask(const TimeTicks& reference,
-                       const TimeDelta& max_delta,
-                       TestPendingTask* next_task);
-
-  // RunLoop::Delegate:
-  void Run(bool application_tasks_allowed) override;
-  void Quit() override;
-  void EnsureWorkScheduled() override;
-
-  // Also used for non-dcheck logic (RunsTasksInCurrentSequence()) and as such
-  // needs to be a ThreadCheckerImpl.
-  ThreadCheckerImpl thread_checker_;
-
-  Time now_;
-  TimeTicks now_ticks_;
-
-  // Temporally ordered heap of pending tasks. Must only be accessed while the
-  // |tasks_lock_| is held.
-  TaskPriorityQueue tasks_;
-
-  // The ordinal to use for the next task. Must only be accessed while the
-  // |tasks_lock_| is held.
-  size_t next_task_ordinal_ = 0;
-
-  mutable Lock tasks_lock_;
-  ConditionVariable tasks_lock_cv_;
-  std::unique_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
-
-  // Set to true in RunLoop::Delegate::Quit() to signal the topmost
-  // RunLoop::Delegate::Run() instance to stop, reset to false when it does.
-  bool quit_run_loop_ = false;
-
-  mutable MockClock mock_clock_;
-
-  DISALLOW_COPY_AND_ASSIGN(TestMockTimeTaskRunner);
-};
-
-}  // namespace base
-
-#endif  // BASE_TEST_TEST_MOCK_TIME_TASK_RUNNER_H_
diff --git a/base/test/test_pending_task.cc b/base/test/test_pending_task.cc
deleted file mode 100644
index bb81eaa..0000000
--- a/base/test/test_pending_task.cc
+++ /dev/null
@@ -1,41 +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 "base/test/test_pending_task.h"
-
-#include <string>
-#include <utility>
-
-namespace base {
-
-TestPendingTask::TestPendingTask() : nestability(NESTABLE) {}
-
-TestPendingTask::TestPendingTask(const Location& location,
-                                 OnceClosure task,
-                                 TimeTicks post_time,
-                                 TimeDelta delay,
-                                 TestNestability nestability)
-    : location(location),
-      task(std::move(task)),
-      post_time(post_time),
-      delay(delay),
-      nestability(nestability) {}
-
-TestPendingTask::TestPendingTask(TestPendingTask&& other) = default;
-
-TestPendingTask& TestPendingTask::operator=(TestPendingTask&& other) = default;
-
-TimeTicks TestPendingTask::GetTimeToRun() const {
-  return post_time + delay;
-}
-
-bool TestPendingTask::ShouldRunBefore(const TestPendingTask& other) const {
-  if (nestability != other.nestability)
-    return (nestability == NESTABLE);
-  return GetTimeToRun() < other.GetTimeToRun();
-}
-
-TestPendingTask::~TestPendingTask() = default;
-
-}  // namespace base
diff --git a/base/test/test_pending_task.h b/base/test/test_pending_task.h
deleted file mode 100644
index 5e607ac..0000000
--- a/base/test/test_pending_task.h
+++ /dev/null
@@ -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_PENDING_TASK_H_
-#define BASE_TEST_TEST_PENDING_TASK_H_
-
-#include <string>
-
-#include "base/callback.h"
-#include "base/location.h"
-#include "base/time/time.h"
-
-namespace base {
-
-// TestPendingTask is a helper class for test TaskRunner
-// implementations.  See test_simple_task_runner.h for example usage.
-
-struct TestPendingTask {
-  enum TestNestability { NESTABLE, NON_NESTABLE };
-
-  TestPendingTask();
-  TestPendingTask(TestPendingTask&& other);
-  TestPendingTask(const Location& location,
-                  OnceClosure task,
-                  TimeTicks post_time,
-                  TimeDelta delay,
-                  TestNestability nestability);
-  ~TestPendingTask();
-
-  TestPendingTask& operator=(TestPendingTask&& other);
-
-  // Returns post_time + delay.
-  TimeTicks GetTimeToRun() const;
-
-  // Returns true if this task is nestable and |other| isn't, or if
-  // this task's time to run is strictly earlier than |other|'s time
-  // to run.
-  //
-  // Note that two tasks may both have the same nestability and delay.
-  // In that case, the caller must use some other criterion (probably
-  // the position in some queue) to break the tie.  Conveniently, the
-  // following STL functions already do so:
-  //
-  //   - std::min_element
-  //   - std::stable_sort
-  //
-  // but the following STL functions don't:
-  //
-  //   - std::max_element
-  //   - std::sort.
-  bool ShouldRunBefore(const TestPendingTask& other) const;
-
-  Location location;
-  OnceClosure task;
-  TimeTicks post_time;
-  TimeDelta delay;
-  TestNestability nestability;
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(TestPendingTask);
-};
-
-}  // namespace base
-
-#endif  // BASE_TEST_TEST_PENDING_TASK_H_
diff --git a/base/third_party/dmg_fp/LICENSE b/base/third_party/dmg_fp/LICENSE
deleted file mode 100644
index 716f1ef..0000000
--- a/base/third_party/dmg_fp/LICENSE
+++ /dev/null
@@ -1,18 +0,0 @@
-/****************************************************************
- *
- * The author of this software is David M. Gay.
- *
- * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose without fee is hereby granted, provided that this entire notice
- * is included in all copies of any software which is or includes a copy
- * or modification of this software and in all copies of the supporting
- * documentation for such software.
- *
- * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
- * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
- * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
- * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
- *
- ***************************************************************/
diff --git a/base/third_party/dmg_fp/README.chromium b/base/third_party/dmg_fp/README.chromium
deleted file mode 100644
index 13d5fb2..0000000
--- a/base/third_party/dmg_fp/README.chromium
+++ /dev/null
@@ -1,22 +0,0 @@
-Name: David M. Gay's floating point routines
-URL: http://www.netlib.org/fp/
-License: MIT-like
-
-Original dtoa.c file can be found at <http://www.netlib.org/fp/dtoa.c>.
-Original g_fmt.c file can be found at <http://www.netlib.org/fp/g_fmt.c>.
-
-List of changes made to original code:
-  - wrapped functions in dmg_fp namespace
-  - renamed .c files to .cc
-  - added dmg_fp.h header
-  - added #define IEEE_8087 to dtoa.cc
-  - added #define NO_HEX_FP to dtoa.cc
-  - made some minor changes to allow clean compilation under g++ -Wall, see
-    gcc_warnings.patch.
-  - made some minor changes to build on 64-bit, see gcc_64_bit.patch.
-  - made minor changes for -Wextra for Mac build, see mac_wextra.patch
-  - fixed warnings under msvc, see msvc_warnings.patch
-  - fixed parsing of long exponents, see exp_length.patch and crbug.com/542881
-  - made hexdig array const
-  - removed deprecated `register` keyword
-  - #undef Long so that it won't change Long in other files in jumbo builds
diff --git a/base/third_party/dmg_fp/const_hexdig.patch b/base/third_party/dmg_fp/const_hexdig.patch
deleted file mode 100644
index 1a3145a..0000000
--- a/base/third_party/dmg_fp/const_hexdig.patch
+++ /dev/null
@@ -1,13 +0,0 @@
-diff --git a/base/third_party/dmg_fp/dtoa.cc b/base/third_party/dmg_fp/dtoa.cc
-index d7e6826..be560bc 100644
---- a/base/third_party/dmg_fp/dtoa.cc
-+++ b/base/third_party/dmg_fp/dtoa.cc
-@@ -1533,7 +1533,7 @@ hexdig_init(void)	/* Use of hexdig_init omitted 20121220 to avoid a */
- 	htinit(hexdig, USC "ABCDEF", 0x10 + 10);
- 	}
- #else
--static unsigned char hexdig[256] = {
-+static const unsigned char hexdig[256] = {
- 	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
- 	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
- 	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
diff --git a/base/third_party/dmg_fp/dmg_fp.h b/base/third_party/dmg_fp/dmg_fp.h
deleted file mode 100644
index 4795397..0000000
--- a/base/third_party/dmg_fp/dmg_fp.h
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (c) 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 THIRD_PARTY_DMG_FP_H_
-#define THIRD_PARTY_DMG_FP_H_
-
-namespace dmg_fp {
-
-// Return a nearest machine number to the input decimal
-// string (or set errno to ERANGE). With IEEE arithmetic, ties are
-// broken by the IEEE round-even rule.  Otherwise ties are broken by
-// biased rounding (add half and chop).
-double strtod(const char* s00, char** se);
-
-// Convert double to ASCII string. For meaning of parameters
-// see dtoa.cc file.
-char* dtoa(double d, int mode, int ndigits,
-           int* decpt, int* sign, char** rve);
-
-// Must be used to free values returned by dtoa.
-void freedtoa(char* s);
-
-// Store the closest decimal approximation to x in b (null terminated).
-// Returns a pointer to b.  It is sufficient for |b| to be 32 characters.
-char* g_fmt(char* b, double x);
-
-}  // namespace dmg_fp
-
-#endif  // THIRD_PARTY_DMG_FP_H_
diff --git a/base/third_party/dmg_fp/dtoa.cc b/base/third_party/dmg_fp/dtoa.cc
deleted file mode 100644
index e846ee3..0000000
--- a/base/third_party/dmg_fp/dtoa.cc
+++ /dev/null
@@ -1,4400 +0,0 @@
-/****************************************************************
- *
- * The author of this software is David M. Gay.
- *
- * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose without fee is hereby granted, provided that this entire notice
- * is included in all copies of any software which is or includes a copy
- * or modification of this software and in all copies of the supporting
- * documentation for such software.
- *
- * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
- * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
- * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
- * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
- *
- ***************************************************************/
-
-/* Please send bug reports to David M. Gay (dmg at acm dot org,
- * with " at " changed at "@" and " dot " changed to ".").	*/
-
-/* On a machine with IEEE extended-precision registers, it is
- * necessary to specify double-precision (53-bit) rounding precision
- * before invoking strtod or dtoa.  If the machine uses (the equivalent
- * of) Intel 80x87 arithmetic, the call
- *	_control87(PC_53, MCW_PC);
- * does this with many compilers.  Whether this or another call is
- * appropriate depends on the compiler; for this to work, it may be
- * necessary to #include "float.h" or another system-dependent header
- * file.
- */
-
-/* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
- * (Note that IEEE arithmetic is disabled by gcc's -ffast-math flag.)
- *
- * This strtod returns a nearest machine number to the input decimal
- * string (or sets errno to ERANGE).  With IEEE arithmetic, ties are
- * broken by the IEEE round-even rule.  Otherwise ties are broken by
- * biased rounding (add half and chop).
- *
- * Inspired loosely by William D. Clinger's paper "How to Read Floating
- * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
- *
- * Modifications:
- *
- *	1. We only require IEEE, IBM, or VAX double-precision
- *		arithmetic (not IEEE double-extended).
- *	2. We get by with floating-point arithmetic in a case that
- *		Clinger missed -- when we're computing d * 10^n
- *		for a small integer d and the integer n is not too
- *		much larger than 22 (the maximum integer k for which
- *		we can represent 10^k exactly), we may be able to
- *		compute (d*10^k) * 10^(e-k) with just one roundoff.
- *	3. Rather than a bit-at-a-time adjustment of the binary
- *		result in the hard case, we use floating-point
- *		arithmetic to determine the adjustment to within
- *		one bit; only in really hard cases do we need to
- *		compute a second residual.
- *	4. Because of 3., we don't need a large table of powers of 10
- *		for ten-to-e (just some small tables, e.g. of 10^k
- *		for 0 <= k <= 22).
- */
-
-/*
- * #define IEEE_8087 for IEEE-arithmetic machines where the least
- *	significant byte has the lowest address.
- * #define IEEE_MC68k for IEEE-arithmetic machines where the most
- *	significant byte has the lowest address.
- * #define Long int on machines with 32-bit ints and 64-bit longs.
- * #define IBM for IBM mainframe-style floating-point arithmetic.
- * #define VAX for VAX-style floating-point arithmetic (D_floating).
- * #define No_leftright to omit left-right logic in fast floating-point
- *	computation of dtoa.  This will cause dtoa modes 4 and 5 to be
- *	treated the same as modes 2 and 3 for some inputs.
- * #define Honor_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
- *	and strtod and dtoa should round accordingly.  Unless Trust_FLT_ROUNDS
- *	is also #defined, fegetround() will be queried for the rounding mode.
- *	Note that both FLT_ROUNDS and fegetround() are specified by the C99
- *	standard (and are specified to be consistent, with fesetround()
- *	affecting the value of FLT_ROUNDS), but that some (Linux) systems
- *	do not work correctly in this regard, so using fegetround() is more
- *	portable than using FLT_ROUNDS directly.
- * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
- *	and Honor_FLT_ROUNDS is not #defined.
- * #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
- *	that use extended-precision instructions to compute rounded
- *	products and quotients) with IBM.
- * #define ROUND_BIASED for IEEE-format with biased rounding and arithmetic
- *	that rounds toward +Infinity.
- * #define ROUND_BIASED_without_Round_Up for IEEE-format with biased
- *	rounding when the underlying floating-point arithmetic uses
- *	unbiased rounding.  This prevent using ordinary floating-point
- *	arithmetic when the result could be computed with one rounding error.
- * #define Inaccurate_Divide for IEEE-format with correctly rounded
- *	products but inaccurate quotients, e.g., for Intel i860.
- * #define NO_LONG_LONG on machines that do not have a "long long"
- *	integer type (of >= 64 bits).  On such machines, you can
- *	#define Just_16 to store 16 bits per 32-bit Long when doing
- *	high-precision integer arithmetic.  Whether this speeds things
- *	up or slows things down depends on the machine and the number
- *	being converted.  If long long is available and the name is
- *	something other than "long long", #define Llong to be the name,
- *	and if "unsigned Llong" does not work as an unsigned version of
- *	Llong, #define #ULLong to be the corresponding unsigned type.
- * #define KR_headers for old-style C function headers.
- * #define Bad_float_h if your system lacks a float.h or if it does not
- *	define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
- *	FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
- * #define MALLOC your_malloc, where your_malloc(n) acts like malloc(n)
- *	if memory is available and otherwise does something you deem
- *	appropriate.  If MALLOC is undefined, malloc will be invoked
- *	directly -- and assumed always to succeed.  Similarly, if you
- *	want something other than the system's free() to be called to
- *	recycle memory acquired from MALLOC, #define FREE to be the
- *	name of the alternate routine.  (FREE or free is only called in
- *	pathological cases, e.g., in a dtoa call after a dtoa return in
- *	mode 3 with thousands of digits requested.)
- * #define Omit_Private_Memory to omit logic (added Jan. 1998) for making
- *	memory allocations from a private pool of memory when possible.
- *	When used, the private pool is PRIVATE_MEM bytes long:  2304 bytes,
- *	unless #defined to be a different length.  This default length
- *	suffices to get rid of MALLOC calls except for unusual cases,
- *	such as decimal-to-binary conversion of a very long string of
- *	digits.  The longest string dtoa can return is about 751 bytes
- *	long.  For conversions by strtod of strings of 800 digits and
- *	all dtoa conversions in single-threaded executions with 8-byte
- *	pointers, PRIVATE_MEM >= 7400 appears to suffice; with 4-byte
- *	pointers, PRIVATE_MEM >= 7112 appears adequate.
- * #define NO_INFNAN_CHECK if you do not wish to have INFNAN_CHECK
- *	#defined automatically on IEEE systems.  On such systems,
- *	when INFNAN_CHECK is #defined, strtod checks
- *	for Infinity and NaN (case insensitively).  On some systems
- *	(e.g., some HP systems), it may be necessary to #define NAN_WORD0
- *	appropriately -- to the most significant word of a quiet NaN.
- *	(On HP Series 700/800 machines, -DNAN_WORD0=0x7ff40000 works.)
- *	When INFNAN_CHECK is #defined and No_Hex_NaN is not #defined,
- *	strtod also accepts (case insensitively) strings of the form
- *	NaN(x), where x is a string of hexadecimal digits and spaces;
- *	if there is only one string of hexadecimal digits, it is taken
- *	for the 52 fraction bits of the resulting NaN; if there are two
- *	or more strings of hex digits, the first is for the high 20 bits,
- *	the second and subsequent for the low 32 bits, with intervening
- *	white space ignored; but if this results in none of the 52
- *	fraction bits being on (an IEEE Infinity symbol), then NAN_WORD0
- *	and NAN_WORD1 are used instead.
- * #define MULTIPLE_THREADS if the system offers preemptively scheduled
- *	multiple threads.  In this case, you must provide (or suitably
- *	#define) two locks, acquired by ACQUIRE_DTOA_LOCK(n) and freed
- *	by FREE_DTOA_LOCK(n) for n = 0 or 1.  (The second lock, accessed
- *	in pow5mult, ensures lazy evaluation of only one copy of high
- *	powers of 5; omitting this lock would introduce a small
- *	probability of wasting memory, but would otherwise be harmless.)
- *	You must also invoke freedtoa(s) to free the value s returned by
- *	dtoa.  You may do so whether or not MULTIPLE_THREADS is #defined.
- * #define NO_IEEE_Scale to disable new (Feb. 1997) logic in strtod that
- *	avoids underflows on inputs whose result does not underflow.
- *	If you #define NO_IEEE_Scale on a machine that uses IEEE-format
- *	floating-point numbers and flushes underflows to zero rather
- *	than implementing gradual underflow, then you must also #define
- *	Sudden_Underflow.
- * #define USE_LOCALE to use the current locale's decimal_point value.
- * #define SET_INEXACT if IEEE arithmetic is being used and extra
- *	computation should be done to set the inexact flag when the
- *	result is inexact and avoid setting inexact when the result
- *	is exact.  In this case, dtoa.c must be compiled in
- *	an environment, perhaps provided by #include "dtoa.c" in a
- *	suitable wrapper, that defines two functions,
- *		int get_inexact(void);
- *		void clear_inexact(void);
- *	such that get_inexact() returns a nonzero value if the
- *	inexact bit is already set, and clear_inexact() sets the
- *	inexact bit to 0.  When SET_INEXACT is #defined, strtod
- *	also does extra computations to set the underflow and overflow
- *	flags when appropriate (i.e., when the result is tiny and
- *	inexact or when it is a numeric value rounded to +-infinity).
- * #define NO_ERRNO if strtod should not assign errno = ERANGE when
- *	the result overflows to +-Infinity or underflows to 0.
- * #define NO_HEX_FP to omit recognition of hexadecimal floating-point
- *	values by strtod.
- * #define NO_STRTOD_BIGCOMP (on IEEE-arithmetic systems only for now)
- *	to disable logic for "fast" testing of very long input strings
- *	to strtod.  This testing proceeds by initially truncating the
- *	input string, then if necessary comparing the whole string with
- *	a decimal expansion to decide close cases. This logic is only
- *	used for input more than STRTOD_DIGLIM digits long (default 40).
- */
-
-#define IEEE_8087
-#define NO_HEX_FP
-
-#ifndef Long
-#if __LP64__
-#define Long int
-#else
-#define Long long
-#endif
-#endif
-#ifndef ULong
-typedef unsigned Long ULong;
-#endif
-
-#ifdef DEBUG
-#include "stdio.h"
-#define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
-#endif
-
-#include "stdlib.h"
-#include "string.h"
-
-#ifdef USE_LOCALE
-#include "locale.h"
-#endif
-
-#ifdef Honor_FLT_ROUNDS
-#ifndef Trust_FLT_ROUNDS
-#include <fenv.h>
-#endif
-#endif
-
-#ifdef MALLOC
-#ifdef KR_headers
-extern char *MALLOC();
-#else
-extern void *MALLOC(size_t);
-#endif
-#else
-#define MALLOC malloc
-#endif
-
-#ifndef Omit_Private_Memory
-#ifndef PRIVATE_MEM
-#define PRIVATE_MEM 2304
-#endif
-#define PRIVATE_mem ((unsigned)((PRIVATE_MEM+sizeof(double)-1)/sizeof(double)))
-static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
-#endif
-
-#undef IEEE_Arith
-#undef Avoid_Underflow
-#ifdef IEEE_MC68k
-#define IEEE_Arith
-#endif
-#ifdef IEEE_8087
-#define IEEE_Arith
-#endif
-
-#ifdef IEEE_Arith
-#ifndef NO_INFNAN_CHECK
-#undef INFNAN_CHECK
-#define INFNAN_CHECK
-#endif
-#else
-#undef INFNAN_CHECK
-#define NO_STRTOD_BIGCOMP
-#endif
-
-#include "errno.h"
-
-#ifdef Bad_float_h
-
-#ifdef IEEE_Arith
-#define DBL_DIG 15
-#define DBL_MAX_10_EXP 308
-#define DBL_MAX_EXP 1024
-#define FLT_RADIX 2
-#endif /*IEEE_Arith*/
-
-#ifdef IBM
-#define DBL_DIG 16
-#define DBL_MAX_10_EXP 75
-#define DBL_MAX_EXP 63
-#define FLT_RADIX 16
-#define DBL_MAX 7.2370055773322621e+75
-#endif
-
-#ifdef VAX
-#define DBL_DIG 16
-#define DBL_MAX_10_EXP 38
-#define DBL_MAX_EXP 127
-#define FLT_RADIX 2
-#define DBL_MAX 1.7014118346046923e+38
-#endif
-
-#ifndef LONG_MAX
-#define LONG_MAX 2147483647
-#endif
-
-#else /* ifndef Bad_float_h */
-#include "float.h"
-#endif /* Bad_float_h */
-
-#ifndef __MATH_H__
-#include "math.h"
-#endif
-
-namespace dmg_fp {
-
-#ifndef CONST
-#ifdef KR_headers
-#define CONST /* blank */
-#else
-#define CONST const
-#endif
-#endif
-
-#if defined(IEEE_8087) + defined(IEEE_MC68k) + defined(VAX) + defined(IBM) != 1
-Exactly one of IEEE_8087, IEEE_MC68k, VAX, or IBM should be defined.
-#endif
-
-typedef union { double d; ULong L[2]; } U;
-
-#ifdef IEEE_8087
-#define word0(x) (x)->L[1]
-#define word1(x) (x)->L[0]
-#else
-#define word0(x) (x)->L[0]
-#define word1(x) (x)->L[1]
-#endif
-#define dval(x) (x)->d
-
-#ifndef STRTOD_DIGLIM
-#define STRTOD_DIGLIM 40
-#endif
-
-#ifdef DIGLIM_DEBUG
-extern int strtod_diglim;
-#else
-#define strtod_diglim STRTOD_DIGLIM
-#endif
-
-/* The following definition of Storeinc is appropriate for MIPS processors.
- * An alternative that might be better on some machines is
- * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
- */
-#if defined(IEEE_8087) + defined(VAX)
-#define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
-((unsigned short *)a)[0] = (unsigned short)c, a++)
-#else
-#define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
-((unsigned short *)a)[1] = (unsigned short)c, a++)
-#endif
-
-/* #define P DBL_MANT_DIG */
-/* Ten_pmax = floor(P*log(2)/log(5)) */
-/* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
-/* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
-/* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
-
-#ifdef IEEE_Arith
-#define Exp_shift  20
-#define Exp_shift1 20
-#define Exp_msk1    0x100000
-#define Exp_msk11   0x100000
-#define Exp_mask  0x7ff00000
-#define P 53
-#define Nbits 53
-#define Bias 1023
-#define Emax 1023
-#define Emin (-1022)
-#define Exp_1  0x3ff00000
-#define Exp_11 0x3ff00000
-#define Ebits 11
-#define Frac_mask  0xfffff
-#define Frac_mask1 0xfffff
-#define Ten_pmax 22
-#define Bletch 0x10
-#define Bndry_mask  0xfffff
-#define Bndry_mask1 0xfffff
-#define LSB 1
-#define Sign_bit 0x80000000
-#define Log2P 1
-#define Tiny0 0
-#define Tiny1 1
-#define Quick_max 14
-#define Int_max 14
-#ifndef NO_IEEE_Scale
-#define Avoid_Underflow
-#ifdef Flush_Denorm	/* debugging option */
-#undef Sudden_Underflow
-#endif
-#endif
-
-#ifndef Flt_Rounds
-#ifdef FLT_ROUNDS
-#define Flt_Rounds FLT_ROUNDS
-#else
-#define Flt_Rounds 1
-#endif
-#endif /*Flt_Rounds*/
-
-#ifdef Honor_FLT_ROUNDS
-#undef Check_FLT_ROUNDS
-#define Check_FLT_ROUNDS
-#else
-#define Rounding Flt_Rounds
-#endif
-
-#else /* ifndef IEEE_Arith */
-#undef Check_FLT_ROUNDS
-#undef Honor_FLT_ROUNDS
-#undef SET_INEXACT
-#undef  Sudden_Underflow
-#define Sudden_Underflow
-#ifdef IBM
-#undef Flt_Rounds
-#define Flt_Rounds 0
-#define Exp_shift  24
-#define Exp_shift1 24
-#define Exp_msk1   0x1000000
-#define Exp_msk11  0x1000000
-#define Exp_mask  0x7f000000
-#define P 14
-#define Nbits 56
-#define Bias 65
-#define Emax 248
-#define Emin (-260)
-#define Exp_1  0x41000000
-#define Exp_11 0x41000000
-#define Ebits 8	/* exponent has 7 bits, but 8 is the right value in b2d */
-#define Frac_mask  0xffffff
-#define Frac_mask1 0xffffff
-#define Bletch 4
-#define Ten_pmax 22
-#define Bndry_mask  0xefffff
-#define Bndry_mask1 0xffffff
-#define LSB 1
-#define Sign_bit 0x80000000
-#define Log2P 4
-#define Tiny0 0x100000
-#define Tiny1 0
-#define Quick_max 14
-#define Int_max 15
-#else /* VAX */
-#undef Flt_Rounds
-#define Flt_Rounds 1
-#define Exp_shift  23
-#define Exp_shift1 7
-#define Exp_msk1    0x80
-#define Exp_msk11   0x800000
-#define Exp_mask  0x7f80
-#define P 56
-#define Nbits 56
-#define Bias 129
-#define Emax 126
-#define Emin (-129)
-#define Exp_1  0x40800000
-#define Exp_11 0x4080
-#define Ebits 8
-#define Frac_mask  0x7fffff
-#define Frac_mask1 0xffff007f
-#define Ten_pmax 24
-#define Bletch 2
-#define Bndry_mask  0xffff007f
-#define Bndry_mask1 0xffff007f
-#define LSB 0x10000
-#define Sign_bit 0x8000
-#define Log2P 1
-#define Tiny0 0x80
-#define Tiny1 0
-#define Quick_max 15
-#define Int_max 15
-#endif /* IBM, VAX */
-#endif /* IEEE_Arith */
-
-#ifndef IEEE_Arith
-#define ROUND_BIASED
-#else
-#ifdef ROUND_BIASED_without_Round_Up
-#undef  ROUND_BIASED
-#define ROUND_BIASED
-#endif
-#endif
-
-#ifdef RND_PRODQUOT
-#define rounded_product(a,b) a = rnd_prod(a, b)
-#define rounded_quotient(a,b) a = rnd_quot(a, b)
-#ifdef KR_headers
-extern double rnd_prod(), rnd_quot();
-#else
-extern double rnd_prod(double, double), rnd_quot(double, double);
-#endif
-#else
-#define rounded_product(a,b) a *= b
-#define rounded_quotient(a,b) a /= b
-#endif
-
-#define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
-#define Big1 0xffffffff
-
-#ifndef Pack_32
-#define Pack_32
-#endif
-
-typedef struct BCinfo BCinfo;
- struct
-BCinfo { int dp0, dp1, dplen, dsign, e0, inexact, nd, nd0, rounding, scale, uflchk; };
-
-#ifdef KR_headers
-#define FFFFFFFF ((((unsigned long)0xffff)<<16)|(unsigned long)0xffff)
-#else
-#define FFFFFFFF 0xffffffffUL
-#endif
-
-#ifdef NO_LONG_LONG
-#undef ULLong
-#ifdef Just_16
-#undef Pack_32
-/* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
- * This makes some inner loops simpler and sometimes saves work
- * during multiplications, but it often seems to make things slightly
- * slower.  Hence the default is now to store 32 bits per Long.
- */
-#endif
-#else	/* long long available */
-#ifndef Llong
-#define Llong long long
-#endif
-#ifndef ULLong
-#define ULLong unsigned Llong
-#endif
-#endif /* NO_LONG_LONG */
-
-#ifndef MULTIPLE_THREADS
-#define ACQUIRE_DTOA_LOCK(n)	/*nothing*/
-#define FREE_DTOA_LOCK(n)	/*nothing*/
-#endif
-
-#define Kmax 7
-
-double strtod(const char *s00, char **se);
-char *dtoa(double d, int mode, int ndigits,
-			int *decpt, int *sign, char **rve);
-
- struct
-Bigint {
-	struct Bigint *next;
-	int k, maxwds, sign, wds;
-	ULong x[1];
-	};
-
- typedef struct Bigint Bigint;
-
- static Bigint *freelist[Kmax+1];
-
- static Bigint *
-Balloc
-#ifdef KR_headers
-	(k) int k;
-#else
-	(int k)
-#endif
-{
-	int x;
-	Bigint *rv;
-#ifndef Omit_Private_Memory
-	unsigned int len;
-#endif
-
-	ACQUIRE_DTOA_LOCK(0);
-	/* The k > Kmax case does not need ACQUIRE_DTOA_LOCK(0), */
-	/* but this case seems very unlikely. */
-	if (k <= Kmax && freelist[k]) {
-		rv = freelist[k];
-		freelist[k] = rv->next;
-		}
-	else {
-		x = 1 << k;
-#ifdef Omit_Private_Memory
-		rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
-#else
-		len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
-			/sizeof(double);
-		if (k <= Kmax && pmem_next - private_mem + len <= PRIVATE_mem) {
-			rv = (Bigint*)pmem_next;
-			pmem_next += len;
-			}
-		else
-			rv = (Bigint*)MALLOC(len*sizeof(double));
-#endif
-		rv->k = k;
-		rv->maxwds = x;
-		}
-	FREE_DTOA_LOCK(0);
-	rv->sign = rv->wds = 0;
-	return rv;
-	}
-
- static void
-Bfree
-#ifdef KR_headers
-	(v) Bigint *v;
-#else
-	(Bigint *v)
-#endif
-{
-	if (v) {
-		if (v->k > Kmax)
-#ifdef FREE
-			FREE((void*)v);
-#else
-			free((void*)v);
-#endif
-		else {
-			ACQUIRE_DTOA_LOCK(0);
-			v->next = freelist[v->k];
-			freelist[v->k] = v;
-			FREE_DTOA_LOCK(0);
-			}
-		}
-	}
-
-#define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
-y->wds*sizeof(Long) + 2*sizeof(int))
-
- static Bigint *
-multadd
-#ifdef KR_headers
-	(b, m, a) Bigint *b; int m, a;
-#else
-	(Bigint *b, int m, int a)	/* multiply by m and add a */
-#endif
-{
-	int i, wds;
-#ifdef ULLong
-	ULong *x;
-	ULLong carry, y;
-#else
-	ULong carry, *x, y;
-#ifdef Pack_32
-	ULong xi, z;
-#endif
-#endif
-	Bigint *b1;
-
-	wds = b->wds;
-	x = b->x;
-	i = 0;
-	carry = a;
-	do {
-#ifdef ULLong
-		y = *x * (ULLong)m + carry;
-		carry = y >> 32;
-		*x++ = y & FFFFFFFF;
-#else
-#ifdef Pack_32
-		xi = *x;
-		y = (xi & 0xffff) * m + carry;
-		z = (xi >> 16) * m + (y >> 16);
-		carry = z >> 16;
-		*x++ = (z << 16) + (y & 0xffff);
-#else
-		y = *x * m + carry;
-		carry = y >> 16;
-		*x++ = y & 0xffff;
-#endif
-#endif
-		}
-		while(++i < wds);
-	if (carry) {
-		if (wds >= b->maxwds) {
-			b1 = Balloc(b->k+1);
-			Bcopy(b1, b);
-			Bfree(b);
-			b = b1;
-			}
-		b->x[wds++] = (ULong)carry;
-		b->wds = wds;
-		}
-	return b;
-	}
-
- static Bigint *
-s2b
-#ifdef KR_headers
-	(s, nd0, nd, y9, dplen) CONST char *s; int nd0, nd, dplen; ULong y9;
-#else
-	(const char *s, int nd0, int nd, ULong y9, int dplen)
-#endif
-{
-	Bigint *b;
-	int i, k;
-	Long x, y;
-
-	x = (nd + 8) / 9;
-	for(k = 0, y = 1; x > y; y <<= 1, k++) ;
-#ifdef Pack_32
-	b = Balloc(k);
-	b->x[0] = y9;
-	b->wds = 1;
-#else
-	b = Balloc(k+1);
-	b->x[0] = y9 & 0xffff;
-	b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
-#endif
-
-	i = 9;
-	if (9 < nd0) {
-		s += 9;
-		do b = multadd(b, 10, *s++ - '0');
-			while(++i < nd0);
-		s += dplen;
-		}
-	else
-		s += dplen + 9;
-	for(; i < nd; i++)
-		b = multadd(b, 10, *s++ - '0');
-	return b;
-	}
-
- static int
-hi0bits
-#ifdef KR_headers
-	(x) ULong x;
-#else
-	(ULong x)
-#endif
-{
-	int k = 0;
-
-	if (!(x & 0xffff0000)) {
-		k = 16;
-		x <<= 16;
-		}
-	if (!(x & 0xff000000)) {
-		k += 8;
-		x <<= 8;
-		}
-	if (!(x & 0xf0000000)) {
-		k += 4;
-		x <<= 4;
-		}
-	if (!(x & 0xc0000000)) {
-		k += 2;
-		x <<= 2;
-		}
-	if (!(x & 0x80000000)) {
-		k++;
-		if (!(x & 0x40000000))
-			return 32;
-		}
-	return k;
-	}
-
- static int
-lo0bits
-#ifdef KR_headers
-	(y) ULong *y;
-#else
-	(ULong *y)
-#endif
-{
-	int k;
-	ULong x = *y;
-
-	if (x & 7) {
-		if (x & 1)
-			return 0;
-		if (x & 2) {
-			*y = x >> 1;
-			return 1;
-			}
-		*y = x >> 2;
-		return 2;
-		}
-	k = 0;
-	if (!(x & 0xffff)) {
-		k = 16;
-		x >>= 16;
-		}
-	if (!(x & 0xff)) {
-		k += 8;
-		x >>= 8;
-		}
-	if (!(x & 0xf)) {
-		k += 4;
-		x >>= 4;
-		}
-	if (!(x & 0x3)) {
-		k += 2;
-		x >>= 2;
-		}
-	if (!(x & 1)) {
-		k++;
-		x >>= 1;
-		if (!x)
-			return 32;
-		}
-	*y = x;
-	return k;
-	}
-
- static Bigint *
-i2b
-#ifdef KR_headers
-	(i) int i;
-#else
-	(int i)
-#endif
-{
-	Bigint *b;
-
-	b = Balloc(1);
-	b->x[0] = i;
-	b->wds = 1;
-	return b;
-	}
-
- static Bigint *
-mult
-#ifdef KR_headers
-	(a, b) Bigint *a, *b;
-#else
-	(Bigint *a, Bigint *b)
-#endif
-{
-	Bigint *c;
-	int k, wa, wb, wc;
-	ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
-	ULong y;
-#ifdef ULLong
-	ULLong carry, z;
-#else
-	ULong carry, z;
-#ifdef Pack_32
-	ULong z2;
-#endif
-#endif
-
-	if (a->wds < b->wds) {
-		c = a;
-		a = b;
-		b = c;
-		}
-	k = a->k;
-	wa = a->wds;
-	wb = b->wds;
-	wc = wa + wb;
-	if (wc > a->maxwds)
-		k++;
-	c = Balloc(k);
-	for(x = c->x, xa = x + wc; x < xa; x++)
-		*x = 0;
-	xa = a->x;
-	xae = xa + wa;
-	xb = b->x;
-	xbe = xb + wb;
-	xc0 = c->x;
-#ifdef ULLong
-	for(; xb < xbe; xc0++) {
-		y = *xb++;
-		if (y) {
-			x = xa;
-			xc = xc0;
-			carry = 0;
-			do {
-				z = *x++ * (ULLong)y + *xc + carry;
-				carry = z >> 32;
-				*xc++ = z & FFFFFFFF;
-				}
-				while(x < xae);
-			*xc = (ULong)carry;
-			}
-		}
-#else
-#ifdef Pack_32
-	for(; xb < xbe; xb++, xc0++) {
-		if (y = *xb & 0xffff) {
-			x = xa;
-			xc = xc0;
-			carry = 0;
-			do {
-				z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
-				carry = z >> 16;
-				z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
-				carry = z2 >> 16;
-				Storeinc(xc, z2, z);
-				}
-				while(x < xae);
-			*xc = carry;
-			}
-		if (y = *xb >> 16) {
-			x = xa;
-			xc = xc0;
-			carry = 0;
-			z2 = *xc;
-			do {
-				z = (*x & 0xffff) * y + (*xc >> 16) + carry;
-				carry = z >> 16;
-				Storeinc(xc, z, z2);
-				z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
-				carry = z2 >> 16;
-				}
-				while(x < xae);
-			*xc = z2;
-			}
-		}
-#else
-	for(; xb < xbe; xc0++) {
-		if (y = *xb++) {
-			x = xa;
-			xc = xc0;
-			carry = 0;
-			do {
-				z = *x++ * y + *xc + carry;
-				carry = z >> 16;
-				*xc++ = z & 0xffff;
-				}
-				while(x < xae);
-			*xc = carry;
-			}
-		}
-#endif
-#endif
-	for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
-	c->wds = wc;
-	return c;
-	}
-
- static Bigint *p5s;
-
- static Bigint *
-pow5mult
-#ifdef KR_headers
-	(b, k) Bigint *b; int k;
-#else
-	(Bigint *b, int k)
-#endif
-{
-	Bigint *b1, *p5, *p51;
-	int i;
-	static int p05[3] = { 5, 25, 125 };
-
-	i = k & 3;
-	if (i)
-		b = multadd(b, p05[i-1], 0);
-
-	if (!(k >>= 2))
-		return b;
-	p5 = p5s;
-	if (!p5) {
-		/* first time */
-#ifdef MULTIPLE_THREADS
-		ACQUIRE_DTOA_LOCK(1);
-		p5 = p5s;
-		if (!p5) {
-			p5 = p5s = i2b(625);
-			p5->next = 0;
-			}
-		FREE_DTOA_LOCK(1);
-#else
-		p5 = p5s = i2b(625);
-		p5->next = 0;
-#endif
-		}
-	for(;;) {
-		if (k & 1) {
-			b1 = mult(b, p5);
-			Bfree(b);
-			b = b1;
-			}
-		if (!(k >>= 1))
-			break;
-		p51 = p5->next;
-		if (!p51) {
-#ifdef MULTIPLE_THREADS
-			ACQUIRE_DTOA_LOCK(1);
-			p51 = p5->next;
-			if (!p51) {
-				p51 = p5->next = mult(p5,p5);
-				p51->next = 0;
-				}
-			FREE_DTOA_LOCK(1);
-#else
-			p51 = p5->next = mult(p5,p5);
-			p51->next = 0;
-#endif
-			}
-		p5 = p51;
-		}
-	return b;
-	}
-
- static Bigint *
-lshift
-#ifdef KR_headers
-	(b, k) Bigint *b; int k;
-#else
-	(Bigint *b, int k)
-#endif
-{
-	int i, k1, n, n1;
-	Bigint *b1;
-	ULong *x, *x1, *xe, z;
-
-#ifdef Pack_32
-	n = k >> 5;
-#else
-	n = k >> 4;
-#endif
-	k1 = b->k;
-	n1 = n + b->wds + 1;
-	for(i = b->maxwds; n1 > i; i <<= 1)
-		k1++;
-	b1 = Balloc(k1);
-	x1 = b1->x;
-	for(i = 0; i < n; i++)
-		*x1++ = 0;
-	x = b->x;
-	xe = x + b->wds;
-#ifdef Pack_32
-	if (k &= 0x1f) {
-		k1 = 32 - k;
-		z = 0;
-		do {
-			*x1++ = *x << k | z;
-			z = *x++ >> k1;
-			}
-			while(x < xe);
-		*x1 = z;
-		if (*x1)
-			++n1;
-		}
-#else
-	if (k &= 0xf) {
-		k1 = 16 - k;
-		z = 0;
-		do {
-			*x1++ = *x << k  & 0xffff | z;
-			z = *x++ >> k1;
-			}
-			while(x < xe);
-		if (*x1 = z)
-			++n1;
-		}
-#endif
-	else do
-		*x1++ = *x++;
-		while(x < xe);
-	b1->wds = n1 - 1;
-	Bfree(b);
-	return b1;
-	}
-
- static int
-cmp
-#ifdef KR_headers
-	(a, b) Bigint *a, *b;
-#else
-	(Bigint *a, Bigint *b)
-#endif
-{
-	ULong *xa, *xa0, *xb, *xb0;
-	int i, j;
-
-	i = a->wds;
-	j = b->wds;
-#ifdef DEBUG
-	if (i > 1 && !a->x[i-1])
-		Bug("cmp called with a->x[a->wds-1] == 0");
-	if (j > 1 && !b->x[j-1])
-		Bug("cmp called with b->x[b->wds-1] == 0");
-#endif
-	if (i -= j)
-		return i;
-	xa0 = a->x;
-	xa = xa0 + j;
-	xb0 = b->x;
-	xb = xb0 + j;
-	for(;;) {
-		if (*--xa != *--xb)
-			return *xa < *xb ? -1 : 1;
-		if (xa <= xa0)
-			break;
-		}
-	return 0;
-	}
-
- static Bigint *
-diff
-#ifdef KR_headers
-	(a, b) Bigint *a, *b;
-#else
-	(Bigint *a, Bigint *b)
-#endif
-{
-	Bigint *c;
-	int i, wa, wb;
-	ULong *xa, *xae, *xb, *xbe, *xc;
-#ifdef ULLong
-	ULLong borrow, y;
-#else
-	ULong borrow, y;
-#ifdef Pack_32
-	ULong z;
-#endif
-#endif
-
-	i = cmp(a,b);
-	if (!i) {
-		c = Balloc(0);
-		c->wds = 1;
-		c->x[0] = 0;
-		return c;
-		}
-	if (i < 0) {
-		c = a;
-		a = b;
-		b = c;
-		i = 1;
-		}
-	else
-		i = 0;
-	c = Balloc(a->k);
-	c->sign = i;
-	wa = a->wds;
-	xa = a->x;
-	xae = xa + wa;
-	wb = b->wds;
-	xb = b->x;
-	xbe = xb + wb;
-	xc = c->x;
-	borrow = 0;
-#ifdef ULLong
-	do {
-		y = (ULLong)*xa++ - *xb++ - borrow;
-		borrow = y >> 32 & (ULong)1;
-		*xc++ = y & FFFFFFFF;
-		}
-		while(xb < xbe);
-	while(xa < xae) {
-		y = *xa++ - borrow;
-		borrow = y >> 32 & (ULong)1;
-		*xc++ = y & FFFFFFFF;
-		}
-#else
-#ifdef Pack_32
-	do {
-		y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
-		borrow = (y & 0x10000) >> 16;
-		z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
-		borrow = (z & 0x10000) >> 16;
-		Storeinc(xc, z, y);
-		}
-		while(xb < xbe);
-	while(xa < xae) {
-		y = (*xa & 0xffff) - borrow;
-		borrow = (y & 0x10000) >> 16;
-		z = (*xa++ >> 16) - borrow;
-		borrow = (z & 0x10000) >> 16;
-		Storeinc(xc, z, y);
-		}
-#else
-	do {
-		y = *xa++ - *xb++ - borrow;
-		borrow = (y & 0x10000) >> 16;
-		*xc++ = y & 0xffff;
-		}
-		while(xb < xbe);
-	while(xa < xae) {
-		y = *xa++ - borrow;
-		borrow = (y & 0x10000) >> 16;
-		*xc++ = y & 0xffff;
-		}
-#endif
-#endif
-	while(!*--xc)
-		wa--;
-	c->wds = wa;
-	return c;
-	}
-
- static double
-ulp
-#ifdef KR_headers
-	(x) U *x;
-#else
-	(U *x)
-#endif
-{
-	Long L;
-	U u;
-
-	L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
-#ifndef Avoid_Underflow
-#ifndef Sudden_Underflow
-	if (L > 0) {
-#endif
-#endif
-#ifdef IBM
-		L |= Exp_msk1 >> 4;
-#endif
-		word0(&u) = L;
-		word1(&u) = 0;
-#ifndef Avoid_Underflow
-#ifndef Sudden_Underflow
-		}
-	else {
-		L = -L >> Exp_shift;
-		if (L < Exp_shift) {
-			word0(&u) = 0x80000 >> L;
-			word1(&u) = 0;
-			}
-		else {
-			word0(&u) = 0;
-			L -= Exp_shift;
-			word1(&u) = L >= 31 ? 1 : 1 << 31 - L;
-			}
-		}
-#endif
-#endif
-	return dval(&u);
-	}
-
- static double
-b2d
-#ifdef KR_headers
-	(a, e) Bigint *a; int *e;
-#else
-	(Bigint *a, int *e)
-#endif
-{
-	ULong *xa, *xa0, w, y, z;
-	int k;
-	U d;
-#ifdef VAX
-	ULong d0, d1;
-#else
-#define d0 word0(&d)
-#define d1 word1(&d)
-#endif
-
-	xa0 = a->x;
-	xa = xa0 + a->wds;
-	y = *--xa;
-#ifdef DEBUG
-	if (!y) Bug("zero y in b2d");
-#endif
-	k = hi0bits(y);
-	*e = 32 - k;
-#ifdef Pack_32
-	if (k < Ebits) {
-		d0 = Exp_1 | y >> (Ebits - k);
-		w = xa > xa0 ? *--xa : 0;
-		d1 = y << ((32-Ebits) + k) | w >> (Ebits - k);
-		goto ret_d;
-		}
-	z = xa > xa0 ? *--xa : 0;
-	if (k -= Ebits) {
-		d0 = Exp_1 | y << k | z >> (32 - k);
-		y = xa > xa0 ? *--xa : 0;
-		d1 = z << k | y >> (32 - k);
-		}
-	else {
-		d0 = Exp_1 | y;
-		d1 = z;
-		}
-#else
-	if (k < Ebits + 16) {
-		z = xa > xa0 ? *--xa : 0;
-		d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
-		w = xa > xa0 ? *--xa : 0;
-		y = xa > xa0 ? *--xa : 0;
-		d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
-		goto ret_d;
-		}
-	z = xa > xa0 ? *--xa : 0;
-	w = xa > xa0 ? *--xa : 0;
-	k -= Ebits + 16;
-	d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
-	y = xa > xa0 ? *--xa : 0;
-	d1 = w << k + 16 | y << k;
-#endif
- ret_d:
-#ifdef VAX
-	word0(&d) = d0 >> 16 | d0 << 16;
-	word1(&d) = d1 >> 16 | d1 << 16;
-#else
-#undef d0
-#undef d1
-#endif
-	return dval(&d);
-	}
-
- static Bigint *
-d2b
-#ifdef KR_headers
-	(d, e, bits) U *d; int *e, *bits;
-#else
-	(U *d, int *e, int *bits)
-#endif
-{
-	Bigint *b;
-	int de, k;
-	ULong *x, y, z;
-#ifndef Sudden_Underflow
-	int i;
-#endif
-#ifdef VAX
-	ULong d0, d1;
-	d0 = word0(d) >> 16 | word0(d) << 16;
-	d1 = word1(d) >> 16 | word1(d) << 16;
-#else
-#define d0 word0(d)
-#define d1 word1(d)
-#endif
-
-#ifdef Pack_32
-	b = Balloc(1);
-#else
-	b = Balloc(2);
-#endif
-	x = b->x;
-
-	z = d0 & Frac_mask;
-	d0 &= 0x7fffffff;	/* clear sign bit, which we ignore */
-#ifdef Sudden_Underflow
-	de = (int)(d0 >> Exp_shift);
-#ifndef IBM
-	z |= Exp_msk11;
-#endif
-#else
-	de = (int)(d0 >> Exp_shift);
-	if (de)
-		z |= Exp_msk1;
-#endif
-#ifdef Pack_32
-	y = d1;
-	if (y) {
-		k = lo0bits(&y);
-		if (k) {
-			x[0] = y | z << (32 - k);
-			z >>= k;
-			}
-		else
-			x[0] = y;
-		x[1] = z;
-		b->wds = x[1] ? 2 : 1;
-#ifndef Sudden_Underflow
-		i = b->wds;
-#endif
-		}
-	else {
-		k = lo0bits(&z);
-		x[0] = z;
-#ifndef Sudden_Underflow
-		i =
-#endif
-		    b->wds = 1;
-		k += 32;
-		}
-#else
-	if (y = d1) {
-		if (k = lo0bits(&y))
-			if (k >= 16) {
-				x[0] = y | z << 32 - k & 0xffff;
-				x[1] = z >> k - 16 & 0xffff;
-				x[2] = z >> k;
-				i = 2;
-				}
-			else {
-				x[0] = y & 0xffff;
-				x[1] = y >> 16 | z << 16 - k & 0xffff;
-				x[2] = z >> k & 0xffff;
-				x[3] = z >> k+16;
-				i = 3;
-				}
-		else {
-			x[0] = y & 0xffff;
-			x[1] = y >> 16;
-			x[2] = z & 0xffff;
-			x[3] = z >> 16;
-			i = 3;
-			}
-		}
-	else {
-#ifdef DEBUG
-		if (!z)
-			Bug("Zero passed to d2b");
-#endif
-		k = lo0bits(&z);
-		if (k >= 16) {
-			x[0] = z;
-			i = 0;
-			}
-		else {
-			x[0] = z & 0xffff;
-			x[1] = z >> 16;
-			i = 1;
-			}
-		k += 32;
-		}
-	while(!x[i])
-		--i;
-	b->wds = i + 1;
-#endif
-#ifndef Sudden_Underflow
-	if (de) {
-#endif
-#ifdef IBM
-		*e = (de - Bias - (P-1) << 2) + k;
-		*bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
-#else
-		*e = de - Bias - (P-1) + k;
-		*bits = P - k;
-#endif
-#ifndef Sudden_Underflow
-		}
-	else {
-		*e = de - Bias - (P-1) + 1 + k;
-#ifdef Pack_32
-		*bits = 32*i - hi0bits(x[i-1]);
-#else
-		*bits = (i+2)*16 - hi0bits(x[i]);
-#endif
-		}
-#endif
-	return b;
-	}
-#undef d0
-#undef d1
-
- static double
-ratio
-#ifdef KR_headers
-	(a, b) Bigint *a, *b;
-#else
-	(Bigint *a, Bigint *b)
-#endif
-{
-	U da, db;
-	int k, ka, kb;
-
-	dval(&da) = b2d(a, &ka);
-	dval(&db) = b2d(b, &kb);
-#ifdef Pack_32
-	k = ka - kb + 32*(a->wds - b->wds);
-#else
-	k = ka - kb + 16*(a->wds - b->wds);
-#endif
-#ifdef IBM
-	if (k > 0) {
-		word0(&da) += (k >> 2)*Exp_msk1;
-		if (k &= 3)
-			dval(&da) *= 1 << k;
-		}
-	else {
-		k = -k;
-		word0(&db) += (k >> 2)*Exp_msk1;
-		if (k &= 3)
-			dval(&db) *= 1 << k;
-		}
-#else
-	if (k > 0)
-		word0(&da) += k*Exp_msk1;
-	else {
-		k = -k;
-		word0(&db) += k*Exp_msk1;
-		}
-#endif
-	return dval(&da) / dval(&db);
-	}
-
- static CONST double
-tens[] = {
-		1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
-		1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
-		1e20, 1e21, 1e22
-#ifdef VAX
-		, 1e23, 1e24
-#endif
-		};
-
- static CONST double
-#ifdef IEEE_Arith
-bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
-static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
-#ifdef Avoid_Underflow
-		9007199254740992.*9007199254740992.e-256
-		/* = 2^106 * 1e-256 */
-#else
-		1e-256
-#endif
-		};
-/* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
-/* flag unnecessarily.  It leads to a song and dance at the end of strtod. */
-#define Scale_Bit 0x10
-#define n_bigtens 5
-#else
-#ifdef IBM
-bigtens[] = { 1e16, 1e32, 1e64 };
-static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64 };
-#define n_bigtens 3
-#else
-bigtens[] = { 1e16, 1e32 };
-static CONST double tinytens[] = { 1e-16, 1e-32 };
-#define n_bigtens 2
-#endif
-#endif
-
-#undef Need_Hexdig
-#ifdef INFNAN_CHECK
-#ifndef No_Hex_NaN
-#define Need_Hexdig
-#endif
-#endif
-
-#ifndef Need_Hexdig
-#ifndef NO_HEX_FP
-#define Need_Hexdig
-#endif
-#endif
-
-#ifdef Need_Hexdig /*{*/
-#if 0
-static unsigned char hexdig[256];
-
- static void
-htinit(unsigned char *h, unsigned char *s, int inc)
-{
-	int i, j;
-	for(i = 0; (j = s[i]) !=0; i++)
-		h[j] = (unsigned char)(i + inc);
-	}
-
- static void
-hexdig_init(void)	/* Use of hexdig_init omitted 20121220 to avoid a */
-			/* race condition when multiple threads are used. */
-{
-#define USC (unsigned char *)
-	htinit(hexdig, USC "0123456789", 0x10);
-	htinit(hexdig, USC "abcdef", 0x10 + 10);
-	htinit(hexdig, USC "ABCDEF", 0x10 + 10);
-	}
-#else
-static const unsigned char hexdig[256] = {
-	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-	16,17,18,19,20,21,22,23,24,25,0,0,0,0,0,0,
-	0,26,27,28,29,30,31,0,0,0,0,0,0,0,0,0,
-	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-	0,26,27,28,29,30,31,0,0,0,0,0,0,0,0,0,
-	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
-	};
-#endif
-#endif /* } Need_Hexdig */
-
-#ifdef INFNAN_CHECK
-
-#ifndef NAN_WORD0
-#define NAN_WORD0 0x7ff80000
-#endif
-
-#ifndef NAN_WORD1
-#define NAN_WORD1 0
-#endif
-
- static int
-match
-#ifdef KR_headers
-	(sp, t) char **sp, *t;
-#else
-	(const char **sp, const char *t)
-#endif
-{
-	int c, d;
-	CONST char *s = *sp;
-
-	for(d = *t++; d; d = *t++) {
-		if ((c = *++s) >= 'A' && c <= 'Z')
-			c += 'a' - 'A';
-		if (c != d)
-			return 0;
-		}
-	*sp = s + 1;
-	return 1;
-	}
-
-#ifndef No_Hex_NaN
- static void
-hexnan
-#ifdef KR_headers
-	(rvp, sp) U *rvp; CONST char **sp;
-#else
-	(U *rvp, const char **sp)
-#endif
-{
-	ULong c, x[2];
-	CONST char *s;
-	int c1, havedig, udx0, xshift;
-
-	/**** if (!hexdig['0']) hexdig_init(); ****/
-	x[0] = x[1] = 0;
-	havedig = xshift = 0;
-	udx0 = 1;
-	s = *sp;
-	/* allow optional initial 0x or 0X */
-	for(c = *(CONST unsigned char*)(s+1); c && c <= ' '; c = *(CONST unsigned char*)(s+1))
-		++s;
-	if (s[1] == '0' && (s[2] == 'x' || s[2] == 'X'))
-		s += 2;
-	for(c = *(CONST unsigned char*)++s; c; c = *(CONST unsigned char*)++s) {
-		c1 = hexdig[c];
-		if (c1)
-			c  = c1 & 0xf;
-		else if (c <= ' ') {
-			if (udx0 && havedig) {
-				udx0 = 0;
-				xshift = 1;
-				}
-			continue;
-			}
-#ifdef GDTOA_NON_PEDANTIC_NANCHECK
-		else if (/*(*/ c == ')' && havedig) {
-			*sp = s + 1;
-			break;
-			}
-		else
-			return;	/* invalid form: don't change *sp */
-#else
-		else {
-			do {
-				if (/*(*/ c == ')') {
-					*sp = s + 1;
-					break;
-					}
-				c = *++s;
-				} while(c);
-			break;
-			}
-#endif
-		havedig = 1;
-		if (xshift) {
-			xshift = 0;
-			x[0] = x[1];
-			x[1] = 0;
-			}
-		if (udx0)
-			x[0] = (x[0] << 4) | (x[1] >> 28);
-		x[1] = (x[1] << 4) | c;
-		}
-	if ((x[0] &= 0xfffff) || x[1]) {
-		word0(rvp) = Exp_mask | x[0];
-		word1(rvp) = x[1];
-		}
-	}
-#endif /*No_Hex_NaN*/
-#endif /* INFNAN_CHECK */
-
-#ifdef Pack_32
-#define ULbits 32
-#define kshift 5
-#define kmask 31
-#else
-#define ULbits 16
-#define kshift 4
-#define kmask 15
-#endif
-
-#if !defined(NO_HEX_FP) || defined(Honor_FLT_ROUNDS) /*{*/
- static Bigint *
-#ifdef KR_headers
-increment(b) Bigint *b;
-#else
-increment(Bigint *b)
-#endif
-{
-	ULong *x, *xe;
-	Bigint *b1;
-
-	x = b->x;
-	xe = x + b->wds;
-	do {
-		if (*x < (ULong)0xffffffffL) {
-			++*x;
-			return b;
-			}
-		*x++ = 0;
-		} while(x < xe);
-	{
-		if (b->wds >= b->maxwds) {
-			b1 = Balloc(b->k+1);
-			Bcopy(b1,b);
-			Bfree(b);
-			b = b1;
-			}
-		b->x[b->wds++] = 1;
-		}
-	return b;
-	}
-
-#endif /*}*/
-
-#ifndef NO_HEX_FP /*{*/
-
- static void
-#ifdef KR_headers
-rshift(b, k) Bigint *b; int k;
-#else
-rshift(Bigint *b, int k)
-#endif
-{
-	ULong *x, *x1, *xe, y;
-	int n;
-
-	x = x1 = b->x;
-	n = k >> kshift;
-	if (n < b->wds) {
-		xe = x + b->wds;
-		x += n;
-		if (k &= kmask) {
-			n = 32 - k;
-			y = *x++ >> k;
-			while(x < xe) {
-				*x1++ = (y | (*x << n)) & 0xffffffff;
-				y = *x++ >> k;
-				}
-			if ((*x1 = y) !=0)
-				x1++;
-			}
-		else
-			while(x < xe)
-				*x1++ = *x++;
-		}
-	if ((b->wds = x1 - b->x) == 0)
-		b->x[0] = 0;
-	}
-
- static ULong
-#ifdef KR_headers
-any_on(b, k) Bigint *b; int k;
-#else
-any_on(Bigint *b, int k)
-#endif
-{
-	int n, nwds;
-	ULong *x, *x0, x1, x2;
-
-	x = b->x;
-	nwds = b->wds;
-	n = k >> kshift;
-	if (n > nwds)
-		n = nwds;
-	else if (n < nwds && (k &= kmask)) {
-		x1 = x2 = x[n];
-		x1 >>= k;
-		x1 <<= k;
-		if (x1 != x2)
-			return 1;
-		}
-	x0 = x;
-	x += n;
-	while(x > x0)
-		if (*--x)
-			return 1;
-	return 0;
-	}
-
-enum {	/* rounding values: same as FLT_ROUNDS */
-	Round_zero = 0,
-	Round_near = 1,
-	Round_up = 2,
-	Round_down = 3
-	};
-
- void
-#ifdef KR_headers
-gethex(sp, rvp, rounding, sign)
-	CONST char **sp; U *rvp; int rounding, sign;
-#else
-gethex( CONST char **sp, U *rvp, int rounding, int sign)
-#endif
-{
-	Bigint *b;
-	CONST unsigned char *decpt, *s0, *s, *s1;
-	Long e, e1;
-	ULong L, lostbits, *x;
-	int big, denorm, esign, havedig, k, n, nbits, up, zret;
-#ifdef IBM
-	int j;
-#endif
-	enum {
-#ifdef IEEE_Arith /*{{*/
-		emax = 0x7fe - Bias - P + 1,
-		emin = Emin - P + 1
-#else /*}{*/
-		emin = Emin - P,
-#ifdef VAX
-		emax = 0x7ff - Bias - P + 1
-#endif
-#ifdef IBM
-		emax = 0x7f - Bias - P
-#endif
-#endif /*}}*/
-		};
-#ifdef USE_LOCALE
-	int i;
-#ifdef NO_LOCALE_CACHE
-	const unsigned char *decimalpoint = (unsigned char*)
-		localeconv()->decimal_point;
-#else
-	const unsigned char *decimalpoint;
-	static unsigned char *decimalpoint_cache;
-	if (!(s0 = decimalpoint_cache)) {
-		s0 = (unsigned char*)localeconv()->decimal_point;
-		if ((decimalpoint_cache = (unsigned char*)
-				MALLOC(strlen((CONST char*)s0) + 1))) {
-			strcpy((char*)decimalpoint_cache, (CONST char*)s0);
-			s0 = decimalpoint_cache;
-			}
-		}
-	decimalpoint = s0;
-#endif
-#endif
-
-	/**** if (!hexdig['0']) hexdig_init(); ****/
-	havedig = 0;
-	s0 = *(CONST unsigned char **)sp + 2;
-	while(s0[havedig] == '0')
-		havedig++;
-	s0 += havedig;
-	s = s0;
-	decpt = 0;
-	zret = 0;
-	e = 0;
-	if (hexdig[*s])
-		havedig++;
-	else {
-		zret = 1;
-#ifdef USE_LOCALE
-		for(i = 0; decimalpoint[i]; ++i) {
-			if (s[i] != decimalpoint[i])
-				goto pcheck;
-			}
-		decpt = s += i;
-#else
-		if (*s != '.')
-			goto pcheck;
-		decpt = ++s;
-#endif
-		if (!hexdig[*s])
-			goto pcheck;
-		while(*s == '0')
-			s++;
-		if (hexdig[*s])
-			zret = 0;
-		havedig = 1;
-		s0 = s;
-		}
-	while(hexdig[*s])
-		s++;
-#ifdef USE_LOCALE
-	if (*s == *decimalpoint && !decpt) {
-		for(i = 1; decimalpoint[i]; ++i) {
-			if (s[i] != decimalpoint[i])
-				goto pcheck;
-			}
-		decpt = s += i;
-#else
-	if (*s == '.' && !decpt) {
-		decpt = ++s;
-#endif
-		while(hexdig[*s])
-			s++;
-		}/*}*/
-	if (decpt)
-		e = -(((Long)(s-decpt)) << 2);
- pcheck:
-	s1 = s;
-	big = esign = 0;
-	switch(*s) {
-	  case 'p':
-	  case 'P':
-		switch(*++s) {
-		  case '-':
-			esign = 1;
-			FALLTHROUGH;
-		  case '+':
-			s++;
-		  }
-		if ((n = hexdig[*s]) == 0 || n > 0x19) {
-			s = s1;
-			break;
-			}
-		e1 = n - 0x10;
-		while((n = hexdig[*++s]) !=0 && n <= 0x19) {
-			if (e1 & 0xf8000000)
-				big = 1;
-			e1 = 10*e1 + n - 0x10;
-			}
-		if (esign)
-			e1 = -e1;
-		e += e1;
-	  }
-	*sp = (char*)s;
-	if (!havedig)
-		*sp = (char*)s0 - 1;
-	if (zret)
-		goto retz1;
-	if (big) {
-		if (esign) {
-#ifdef IEEE_Arith
-			switch(rounding) {
-			  case Round_up:
-				if (sign)
-					break;
-				goto ret_tiny;
-			  case Round_down:
-				if (!sign)
-					break;
-				goto ret_tiny;
-			  }
-#endif
-			goto retz;
-#ifdef IEEE_Arith
- ret_tinyf:
-			Bfree(b);
- ret_tiny:
-#ifndef NO_ERRNO
-			errno = ERANGE;
-#endif
-			word0(rvp) = 0;
-			word1(rvp) = 1;
-			return;
-#endif /* IEEE_Arith */
-			}
-		switch(rounding) {
-		  case Round_near:
-			goto ovfl1;
-		  case Round_up:
-			if (!sign)
-				goto ovfl1;
-			goto ret_big;
-		  case Round_down:
-			if (sign)
-				goto ovfl1;
-			goto ret_big;
-		  }
- ret_big:
-		word0(rvp) = Big0;
-		word1(rvp) = Big1;
-		return;
-		}
-	n = s1 - s0 - 1;
-	for(k = 0; n > (1 << (kshift-2)) - 1; n >>= 1)
-		k++;
-	b = Balloc(k);
-	x = b->x;
-	n = 0;
-	L = 0;
-#ifdef USE_LOCALE
-	for(i = 0; decimalpoint[i+1]; ++i);
-#endif
-	while(s1 > s0) {
-#ifdef USE_LOCALE
-		if (*--s1 == decimalpoint[i]) {
-			s1 -= i;
-			continue;
-			}
-#else
-		if (*--s1 == '.')
-			continue;
-#endif
-		if (n == ULbits) {
-			*x++ = L;
-			L = 0;
-			n = 0;
-			}
-		L |= (hexdig[*s1] & 0x0f) << n;
-		n += 4;
-		}
-	*x++ = L;
-	b->wds = n = x - b->x;
-	n = ULbits*n - hi0bits(L);
-	nbits = Nbits;
-	lostbits = 0;
-	x = b->x;
-	if (n > nbits) {
-		n -= nbits;
-		if (any_on(b,n)) {
-			lostbits = 1;
-			k = n - 1;
-			if (x[k>>kshift] & 1 << (k & kmask)) {
-				lostbits = 2;
-				if (k > 0 && any_on(b,k))
-					lostbits = 3;
-				}
-			}
-		rshift(b, n);
-		e += n;
-		}
-	else if (n < nbits) {
-		n = nbits - n;
-		b = lshift(b, n);
-		e -= n;
-		x = b->x;
-		}
-	if (e > Emax) {
- ovfl:
-		Bfree(b);
- ovfl1:
-#ifndef NO_ERRNO
-		errno = ERANGE;
-#endif
-		word0(rvp) = Exp_mask;
-		word1(rvp) = 0;
-		return;
-		}
-	denorm = 0;
-	if (e < emin) {
-		denorm = 1;
-		n = emin - e;
-		if (n >= nbits) {
-#ifdef IEEE_Arith /*{*/
-			switch (rounding) {
-			  case Round_near:
-				if (n == nbits && (n < 2 || any_on(b,n-1)))
-					goto ret_tinyf;
-				break;
-			  case Round_up:
-				if (!sign)
-					goto ret_tinyf;
-				break;
-			  case Round_down:
-				if (sign)
-					goto ret_tinyf;
-			  }
-#endif /* } IEEE_Arith */
-			Bfree(b);
- retz:
-#ifndef NO_ERRNO
-			errno = ERANGE;
-#endif
- retz1:
-			rvp->d = 0.;
-			return;
-			}
-		k = n - 1;
-		if (lostbits)
-			lostbits = 1;
-		else if (k > 0)
-			lostbits = any_on(b,k);
-		if (x[k>>kshift] & 1 << (k & kmask))
-			lostbits |= 2;
-		nbits -= n;
-		rshift(b,n);
-		e = emin;
-		}
-	if (lostbits) {
-		up = 0;
-		switch(rounding) {
-		  case Round_zero:
-			break;
-		  case Round_near:
-			if (lostbits & 2
-			 && (lostbits & 1) | (x[0] & 1))
-				up = 1;
-			break;
-		  case Round_up:
-			up = 1 - sign;
-			break;
-		  case Round_down:
-			up = sign;
-		  }
-		if (up) {
-			k = b->wds;
-			b = increment(b);
-			x = b->x;
-			if (denorm) {
-#if 0
-				if (nbits == Nbits - 1
-				 && x[nbits >> kshift] & 1 << (nbits & kmask))
-					denorm = 0; /* not currently used */
-#endif
-				}
-			else if (b->wds > k
-			 || ((n = nbits & kmask) !=0
-			     && hi0bits(x[k-1]) < 32-n)) {
-				rshift(b,1);
-				if (++e > Emax)
-					goto ovfl;
-				}
-			}
-		}
-#ifdef IEEE_Arith
-	if (denorm)
-		word0(rvp) = b->wds > 1 ? b->x[1] & ~0x100000 : 0;
-	else
-		word0(rvp) = (b->x[1] & ~0x100000) | ((e + 0x3ff + 52) << 20);
-	word1(rvp) = b->x[0];
-#endif
-#ifdef IBM
-	if ((j = e & 3)) {
-		k = b->x[0] & ((1 << j) - 1);
-		rshift(b,j);
-		if (k) {
-			switch(rounding) {
-			  case Round_up:
-				if (!sign)
-					increment(b);
-				break;
-			  case Round_down:
-				if (sign)
-					increment(b);
-				break;
-			  case Round_near:
-				j = 1 << (j-1);
-				if (k & j && ((k & (j-1)) | lostbits))
-					increment(b);
-			  }
-			}
-		}
-	e >>= 2;
-	word0(rvp) = b->x[1] | ((e + 65 + 13) << 24);
-	word1(rvp) = b->x[0];
-#endif
-#ifdef VAX
-	/* The next two lines ignore swap of low- and high-order 2 bytes. */
-	/* word0(rvp) = (b->x[1] & ~0x800000) | ((e + 129 + 55) << 23); */
-	/* word1(rvp) = b->x[0]; */
-	word0(rvp) = ((b->x[1] & ~0x800000) >> 16) | ((e + 129 + 55) << 7) | (b->x[1] << 16);
-	word1(rvp) = (b->x[0] >> 16) | (b->x[0] << 16);
-#endif
-	Bfree(b);
-	}
-#endif /*!NO_HEX_FP}*/
-
- static int
-#ifdef KR_headers
-dshift(b, p2) Bigint *b; int p2;
-#else
-dshift(Bigint *b, int p2)
-#endif
-{
-	int rv = hi0bits(b->x[b->wds-1]) - 4;
-	if (p2 > 0)
-		rv -= p2;
-	return rv & kmask;
-	}
-
- static int
-quorem
-#ifdef KR_headers
-	(b, S) Bigint *b, *S;
-#else
-	(Bigint *b, Bigint *S)
-#endif
-{
-	int n;
-	ULong *bx, *bxe, q, *sx, *sxe;
-#ifdef ULLong
-	ULLong borrow, carry, y, ys;
-#else
-	ULong borrow, carry, y, ys;
-#ifdef Pack_32
-	ULong si, z, zs;
-#endif
-#endif
-
-	n = S->wds;
-#ifdef DEBUG
-	/*debug*/ if (b->wds > n)
-	/*debug*/	Bug("oversize b in quorem");
-#endif
-	if (b->wds < n)
-		return 0;
-	sx = S->x;
-	sxe = sx + --n;
-	bx = b->x;
-	bxe = bx + n;
-	q = *bxe / (*sxe + 1);	/* ensure q <= true quotient */
-#ifdef DEBUG
-#ifdef NO_STRTOD_BIGCOMP
-	/*debug*/ if (q > 9)
-#else
-	/* An oversized q is possible when quorem is called from bigcomp and */
-	/* the input is near, e.g., twice the smallest denormalized number. */
-	/*debug*/ if (q > 15)
-#endif
-	/*debug*/	Bug("oversized quotient in quorem");
-#endif
-	if (q) {
-		borrow = 0;
-		carry = 0;
-		do {
-#ifdef ULLong
-			ys = *sx++ * (ULLong)q + carry;
-			carry = ys >> 32;
-			y = *bx - (ys & FFFFFFFF) - borrow;
-			borrow = y >> 32 & (ULong)1;
-			*bx++ = y & FFFFFFFF;
-#else
-#ifdef Pack_32
-			si = *sx++;
-			ys = (si & 0xffff) * q + carry;
-			zs = (si >> 16) * q + (ys >> 16);
-			carry = zs >> 16;
-			y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
-			borrow = (y & 0x10000) >> 16;
-			z = (*bx >> 16) - (zs & 0xffff) - borrow;
-			borrow = (z & 0x10000) >> 16;
-			Storeinc(bx, z, y);
-#else
-			ys = *sx++ * q + carry;
-			carry = ys >> 16;
-			y = *bx - (ys & 0xffff) - borrow;
-			borrow = (y & 0x10000) >> 16;
-			*bx++ = y & 0xffff;
-#endif
-#endif
-			}
-			while(sx <= sxe);
-		if (!*bxe) {
-			bx = b->x;
-			while(--bxe > bx && !*bxe)
-				--n;
-			b->wds = n;
-			}
-		}
-	if (cmp(b, S) >= 0) {
-		q++;
-		borrow = 0;
-		carry = 0;
-		bx = b->x;
-		sx = S->x;
-		do {
-#ifdef ULLong
-			ys = *sx++ + carry;
-			carry = ys >> 32;
-			y = *bx - (ys & FFFFFFFF) - borrow;
-			borrow = y >> 32 & (ULong)1;
-			*bx++ = y & FFFFFFFF;
-#else
-#ifdef Pack_32
-			si = *sx++;
-			ys = (si & 0xffff) + carry;
-			zs = (si >> 16) + (ys >> 16);
-			carry = zs >> 16;
-			y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
-			borrow = (y & 0x10000) >> 16;
-			z = (*bx >> 16) - (zs & 0xffff) - borrow;
-			borrow = (z & 0x10000) >> 16;
-			Storeinc(bx, z, y);
-#else
-			ys = *sx++ + carry;
-			carry = ys >> 16;
-			y = *bx - (ys & 0xffff) - borrow;
-			borrow = (y & 0x10000) >> 16;
-			*bx++ = y & 0xffff;
-#endif
-#endif
-			}
-			while(sx <= sxe);
-		bx = b->x;
-		bxe = bx + n;
-		if (!*bxe) {
-			while(--bxe > bx && !*bxe)
-				--n;
-			b->wds = n;
-			}
-		}
-	return q;
-	}
-
-#if defined(Avoid_Underflow) || !defined(NO_STRTOD_BIGCOMP) /*{*/
- static double
-sulp
-#ifdef KR_headers
-	(x, bc) U *x; BCinfo *bc;
-#else
-	(U *x, BCinfo *bc)
-#endif
-{
-	U u;
-	double rv;
-	int i;
-
-	rv = ulp(x);
-	if (!bc->scale || (i = 2*P + 1 - ((word0(x) & Exp_mask) >> Exp_shift)) <= 0)
-		return rv; /* Is there an example where i <= 0 ? */
-	word0(&u) = Exp_1 + (i << Exp_shift);
-	word1(&u) = 0;
-	return rv * u.d;
-	}
-#endif /*}*/
-
-#ifndef NO_STRTOD_BIGCOMP
- static void
-bigcomp
-#ifdef KR_headers
-	(rv, s0, bc)
-	U *rv; CONST char *s0; BCinfo *bc;
-#else
-	(U *rv, const char *s0, BCinfo *bc)
-#endif
-{
-	Bigint *b, *d;
-	int b2, bbits, d2, dd, dig, dsign, i, j, nd, nd0, p2, p5, speccase;
-
-	dsign = bc->dsign;
-	nd = bc->nd;
-	nd0 = bc->nd0;
-	p5 = nd + bc->e0 - 1;
-	dd = speccase = 0;
-#ifndef Sudden_Underflow
-	if (rv->d == 0.) {	/* special case: value near underflow-to-zero */
-				/* threshold was rounded to zero */
-		b = i2b(1);
-		p2 = Emin - P + 1;
-		bbits = 1;
-#ifdef Avoid_Underflow
-		word0(rv) = (P+2) << Exp_shift;
-#else
-		word1(rv) = 1;
-#endif
-		i = 0;
-#ifdef Honor_FLT_ROUNDS
-		if (bc->rounding == 1)
-#endif
-			{
-			speccase = 1;
-			--p2;
-			dsign = 0;
-			goto have_i;
-			}
-		}
-	else
-#endif
-		b = d2b(rv, &p2, &bbits);
-#ifdef Avoid_Underflow
-	p2 -= bc->scale;
-#endif
-	/* floor(log2(rv)) == bbits - 1 + p2 */
-	/* Check for denormal case. */
-	i = P - bbits;
-	if (i > (j = P - Emin - 1 + p2)) {
-#ifdef Sudden_Underflow
-		Bfree(b);
-		b = i2b(1);
-		p2 = Emin;
-		i = P - 1;
-#ifdef Avoid_Underflow
-		word0(rv) = (1 + bc->scale) << Exp_shift;
-#else
-		word0(rv) = Exp_msk1;
-#endif
-		word1(rv) = 0;
-#else
-		i = j;
-#endif
-		}
-#ifdef Honor_FLT_ROUNDS
-	if (bc->rounding != 1) {
-		if (i > 0)
-			b = lshift(b, i);
-		if (dsign)
-			b = increment(b);
-		}
-	else
-#endif
-		{
-		b = lshift(b, ++i);
-		b->x[0] |= 1;
-		}
-#ifndef Sudden_Underflow
- have_i:
-#endif
-	p2 -= p5 + i;
-	d = i2b(1);
-	/* Arrange for convenient computation of quotients:
-	 * shift left if necessary so divisor has 4 leading 0 bits.
-	 */
-	if (p5 > 0)
-		d = pow5mult(d, p5);
-	else if (p5 < 0)
-		b = pow5mult(b, -p5);
-	if (p2 > 0) {
-		b2 = p2;
-		d2 = 0;
-		}
-	else {
-		b2 = 0;
-		d2 = -p2;
-		}
-	i = dshift(d, d2);
-	if ((b2 += i) > 0)
-		b = lshift(b, b2);
-	if ((d2 += i) > 0)
-		d = lshift(d, d2);
-
-	/* Now b/d = exactly half-way between the two floating-point values */
-	/* on either side of the input string.  Compute first digit of b/d. */
-
-	dig = quorem(b,d);
-	if (!dig) {
-		b = multadd(b, 10, 0);	/* very unlikely */
-		dig = quorem(b,d);
-		}
-
-	/* Compare b/d with s0 */
-
-	for(i = 0; i < nd0; ) {
-		dd = s0[i++] - '0' - dig;
-		if (dd)
-			goto ret;
-		if (!b->x[0] && b->wds == 1) {
-			if (i < nd)
-				dd = 1;
-			goto ret;
-			}
-		b = multadd(b, 10, 0);
-		dig = quorem(b,d);
-		}
-	for(j = bc->dp1; i++ < nd;) {
-		dd = s0[j++] - '0' - dig;
-		if (dd)
-			goto ret;
-		if (!b->x[0] && b->wds == 1) {
-			if (i < nd)
-				dd = 1;
-			goto ret;
-			}
-		b = multadd(b, 10, 0);
-		dig = quorem(b,d);
-		}
-	if (dig > 0 || b->x[0] || b->wds > 1)
-		dd = -1;
- ret:
-	Bfree(b);
-	Bfree(d);
-#ifdef Honor_FLT_ROUNDS
-	if (bc->rounding != 1) {
-		if (dd < 0) {
-			if (bc->rounding == 0) {
-				if (!dsign)
-					goto retlow1;
-				}
-			else if (dsign)
-				goto rethi1;
-			}
-		else if (dd > 0) {
-			if (bc->rounding == 0) {
-				if (dsign)
-					goto rethi1;
-				goto ret1;
-				}
-			if (!dsign)
-				goto rethi1;
-			dval(rv) += 2.*sulp(rv,bc);
-			}
-		else {
-			bc->inexact = 0;
-			if (dsign)
-				goto rethi1;
-			}
-		}
-	else
-#endif
-	if (speccase) {
-		if (dd <= 0)
-			rv->d = 0.;
-		}
-	else if (dd < 0) {
-		if (!dsign)	/* does not happen for round-near */
-retlow1:
-			dval(rv) -= sulp(rv,bc);
-		}
-	else if (dd > 0) {
-		if (dsign) {
- rethi1:
-			dval(rv) += sulp(rv,bc);
-			}
-		}
-	else {
-		/* Exact half-way case:  apply round-even rule. */
-		if ((j = ((word0(rv) & Exp_mask) >> Exp_shift) - bc->scale) <= 0) {
-			i = 1 - j;
-			if (i <= 31) {
-				if (word1(rv) & (0x1 << i))
-					goto odd;
-				}
-			else if (word0(rv) & (0x1 << (i-32)))
-				goto odd;
-			}
-		else if (word1(rv) & 1) {
- odd:
-			if (dsign)
-				goto rethi1;
-			goto retlow1;
-			}
-		}
-
-#ifdef Honor_FLT_ROUNDS
- ret1:
-#endif
-	return;
-	}
-#endif /* NO_STRTOD_BIGCOMP */
-
- double
-strtod
-#ifdef KR_headers
-	(s00, se) CONST char *s00; char **se;
-#else
-	(const char *s00, char **se)
-#endif
-{
-	int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, e, e1;
-	int esign, i, j, k, nd, nd0, nf, nz, nz0, nz1, sign;
-	CONST char *s, *s0, *s1;
-	double aadj, aadj1;
-	Long L;
-	U aadj2, adj, rv, rv0;
-	ULong y, z;
-	BCinfo bc;
-	Bigint *bb = nullptr, *bb1, *bd = nullptr, *bd0, *bs = nullptr, *delta = nullptr;
-#ifdef Avoid_Underflow
-	ULong Lsb, Lsb1;
-#endif
-#ifdef SET_INEXACT
-	int oldinexact;
-#endif
-#ifndef NO_STRTOD_BIGCOMP
-	int req_bigcomp = 0;
-#endif
-#ifdef Honor_FLT_ROUNDS /*{*/
-#ifdef Trust_FLT_ROUNDS /*{{ only define this if FLT_ROUNDS really works! */
-	bc.rounding = Flt_Rounds;
-#else /*}{*/
-	bc.rounding = 1;
-	switch(fegetround()) {
-	  case FE_TOWARDZERO:	bc.rounding = 0; break;
-	  case FE_UPWARD:	bc.rounding = 2; break;
-	  case FE_DOWNWARD:	bc.rounding = 3;
-	  }
-#endif /*}}*/
-#endif /*}*/
-#ifdef USE_LOCALE
-	CONST char *s2;
-#endif
-
-	sign = nz0 = nz1 = nz = bc.dplen = bc.uflchk = 0;
-	dval(&rv) = 0.;
-	for(s = s00;;s++) switch(*s) {
-		case '-':
-			sign = 1;
-			FALLTHROUGH;
-		case '+':
-			if (*++s)
-				goto break2;
-			FALLTHROUGH;
-		case 0:
-			goto ret0;
-		case '\t':
-		case '\n':
-		case '\v':
-		case '\f':
-		case '\r':
-		case ' ':
-			continue;
-		default:
-			goto break2;
-		}
- break2:
-	if (*s == '0') {
-#ifndef NO_HEX_FP /*{*/
-		switch(s[1]) {
-		  case 'x':
-		  case 'X':
-#ifdef Honor_FLT_ROUNDS
-			gethex(&s, &rv, bc.rounding, sign);
-#else
-			gethex(&s, &rv, 1, sign);
-#endif
-			goto ret;
-		  }
-#endif /*}*/
-		nz0 = 1;
-		while(*++s == '0') ;
-		if (!*s)
-			goto ret;
-		}
-	s0 = s;
-	y = z = 0;
-	for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
-		if (nd < 9)
-			y = 10*y + c - '0';
-		else if (nd < DBL_DIG + 2)
-			z = 10*z + c - '0';
-	nd0 = nd;
-	bc.dp0 = bc.dp1 = s - s0;
-	for(s1 = s; s1 > s0 && *--s1 == '0'; )
-		++nz1;
-#ifdef USE_LOCALE
-	s1 = localeconv()->decimal_point;
-	if (c == *s1) {
-		c = '.';
-		if (*++s1) {
-			s2 = s;
-			for(;;) {
-				if (*++s2 != *s1) {
-					c = 0;
-					break;
-					}
-				if (!*++s1) {
-					s = s2;
-					break;
-					}
-				}
-			}
-		}
-#endif
-	if (c == '.') {
-		c = *++s;
-		bc.dp1 = s - s0;
-		bc.dplen = bc.dp1 - bc.dp0;
-		if (!nd) {
-			for(; c == '0'; c = *++s)
-				nz++;
-			if (c > '0' && c <= '9') {
-				bc.dp0 = s0 - s;
-				bc.dp1 = bc.dp0 + bc.dplen;
-				s0 = s;
-				nf += nz;
-				nz = 0;
-				goto have_dig;
-				}
-			goto dig_done;
-			}
-		for(; c >= '0' && c <= '9'; c = *++s) {
- have_dig:
-			nz++;
-			if (c -= '0') {
-				nf += nz;
-				for(i = 1; i < nz; i++)
-					if (nd++ < 9)
-						y *= 10;
-					else if (nd <= DBL_DIG + 2)
-						z *= 10;
-				if (nd++ < 9)
-					y = 10*y + c;
-				else if (nd <= DBL_DIG + 2)
-					z = 10*z + c;
-				nz = nz1 = 0;
-				}
-			}
-		}
- dig_done:
-	e = 0;
-	if (c == 'e' || c == 'E') {
-		if (!nd && !nz && !nz0) {
-			goto ret0;
-			}
-		s00 = s;
-		esign = 0;
-		switch(c = *++s) {
-			case '-':
-				esign = 1;
-				FALLTHROUGH;
-			case '+':
-				c = *++s;
-			}
-		if (c >= '0' && c <= '9') {
-			while(c == '0')
-				c = *++s;
-			if (c > '0' && c <= '9') {
-				L = c - '0';
-				s1 = s;
-				while((c = *++s) >= '0' && c <= '9') {
-					if (L < (INT_MAX - 10) / 10) {
-						L = 10*L + (c - '0');
-					}
-				}
-				if (s - s1 > 8 || L > 19999)
-					/* Avoid confusion from exponents
-					 * so large that e might overflow.
-					 */
-					e = 19999; /* safe for 16 bit ints */
-				else
-					e = (int)L;
-				if (esign)
-					e = -e;
-				}
-			else
-				e = 0;
-			}
-		else
-			s = s00;
-		}
-	if (!nd) {
-		if (!nz && !nz0) {
-#ifdef INFNAN_CHECK
-			/* Check for Nan and Infinity */
-			if (!bc.dplen)
-			 switch(c) {
-			  case 'i':
-			  case 'I':
-				if (match(&s,"nf")) {
-					--s;
-					if (!match(&s,"inity"))
-						++s;
-					word0(&rv) = 0x7ff00000;
-					word1(&rv) = 0;
-					goto ret;
-					}
-				break;
-			  case 'n':
-			  case 'N':
-				if (match(&s, "an")) {
-					word0(&rv) = NAN_WORD0;
-					word1(&rv) = NAN_WORD1;
-#ifndef No_Hex_NaN
-					if (*s == '(') /*)*/
-						hexnan(&rv, &s);
-#endif
-					goto ret;
-					}
-			  }
-#endif /* INFNAN_CHECK */
- ret0:
-			s = s00;
-			sign = 0;
-			}
-		goto ret;
-		}
-	bc.e0 = e1 = e -= nf;
-
-	/* Now we have nd0 digits, starting at s0, followed by a
-	 * decimal point, followed by nd-nd0 digits.  The number we're
-	 * after is the integer represented by those digits times
-	 * 10**e */
-
-	if (!nd0)
-		nd0 = nd;
-	k = nd < DBL_DIG + 2 ? nd : DBL_DIG + 2;
-	dval(&rv) = y;
-	if (k > 9) {
-#ifdef SET_INEXACT
-		if (k > DBL_DIG)
-			oldinexact = get_inexact();
-#endif
-		dval(&rv) = tens[k - 9] * dval(&rv) + z;
-		}
-	bd0 = 0;
-	if (nd <= DBL_DIG
-#ifndef RND_PRODQUOT
-#ifndef Honor_FLT_ROUNDS
-		&& Flt_Rounds == 1
-#endif
-#endif
-			) {
-		if (!e)
-			goto ret;
-#ifndef ROUND_BIASED_without_Round_Up
-		if (e > 0) {
-			if (e <= Ten_pmax) {
-#ifdef VAX
-				goto vax_ovfl_check;
-#else
-#ifdef Honor_FLT_ROUNDS
-				/* round correctly FLT_ROUNDS = 2 or 3 */
-				if (sign) {
-					rv.d = -rv.d;
-					sign = 0;
-					}
-#endif
-				/* rv = */ rounded_product(dval(&rv), tens[e]);
-				goto ret;
-#endif
-				}
-			i = DBL_DIG - nd;
-			if (e <= Ten_pmax + i) {
-				/* A fancier test would sometimes let us do
-				 * this for larger i values.
-				 */
-#ifdef Honor_FLT_ROUNDS
-				/* round correctly FLT_ROUNDS = 2 or 3 */
-				if (sign) {
-					rv.d = -rv.d;
-					sign = 0;
-					}
-#endif
-				e -= i;
-				dval(&rv) *= tens[i];
-#ifdef VAX
-				/* VAX exponent range is so narrow we must
-				 * worry about overflow here...
-				 */
- vax_ovfl_check:
-				word0(&rv) -= P*Exp_msk1;
-				/* rv = */ rounded_product(dval(&rv), tens[e]);
-				if ((word0(&rv) & Exp_mask)
-				 > Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
-					goto ovfl;
-				word0(&rv) += P*Exp_msk1;
-#else
-				/* rv = */ rounded_product(dval(&rv), tens[e]);
-#endif
-				goto ret;
-				}
-			}
-#ifndef Inaccurate_Divide
-		else if (e >= -Ten_pmax) {
-#ifdef Honor_FLT_ROUNDS
-			/* round correctly FLT_ROUNDS = 2 or 3 */
-			if (sign) {
-				rv.d = -rv.d;
-				sign = 0;
-				}
-#endif
-			/* rv = */ rounded_quotient(dval(&rv), tens[-e]);
-			goto ret;
-			}
-#endif
-#endif /* ROUND_BIASED_without_Round_Up */
-		}
-	e1 += nd - k;
-
-#ifdef IEEE_Arith
-#ifdef SET_INEXACT
-	bc.inexact = 1;
-	if (k <= DBL_DIG)
-		oldinexact = get_inexact();
-#endif
-#ifdef Avoid_Underflow
-	bc.scale = 0;
-#endif
-#ifdef Honor_FLT_ROUNDS
-	if (bc.rounding >= 2) {
-		if (sign)
-			bc.rounding = bc.rounding == 2 ? 0 : 2;
-		else
-			if (bc.rounding != 2)
-				bc.rounding = 0;
-		}
-#endif
-#endif /*IEEE_Arith*/
-
-	/* Get starting approximation = rv * 10**e1 */
-
-	if (e1 > 0) {
-		i = e1 & 15;
-		if (i)
-			dval(&rv) *= tens[i];
-		if (e1 &= ~15) {
-			if (e1 > DBL_MAX_10_EXP) {
- ovfl:
-				/* Can't trust HUGE_VAL */
-#ifdef IEEE_Arith
-#ifdef Honor_FLT_ROUNDS
-				switch(bc.rounding) {
-				  case 0: /* toward 0 */
-				  case 3: /* toward -infinity */
-					word0(&rv) = Big0;
-					word1(&rv) = Big1;
-					break;
-				  default:
-					word0(&rv) = Exp_mask;
-					word1(&rv) = 0;
-				  }
-#else /*Honor_FLT_ROUNDS*/
-				word0(&rv) = Exp_mask;
-				word1(&rv) = 0;
-#endif /*Honor_FLT_ROUNDS*/
-#ifdef SET_INEXACT
-				/* set overflow bit */
-				dval(&rv0) = 1e300;
-				dval(&rv0) *= dval(&rv0);
-#endif
-#else /*IEEE_Arith*/
-				word0(&rv) = Big0;
-				word1(&rv) = Big1;
-#endif /*IEEE_Arith*/
- range_err:
-				if (bd0) {
-					Bfree(bb);
-					Bfree(bd);
-					Bfree(bs);
-					Bfree(bd0);
-					Bfree(delta);
-					}
-#ifndef NO_ERRNO
-				errno = ERANGE;
-#endif
-				goto ret;
-				}
-			e1 >>= 4;
-			for(j = 0; e1 > 1; j++, e1 >>= 1)
-				if (e1 & 1)
-					dval(&rv) *= bigtens[j];
-		/* The last multiplication could overflow. */
-			word0(&rv) -= P*Exp_msk1;
-			dval(&rv) *= bigtens[j];
-			if ((z = word0(&rv) & Exp_mask)
-			 > Exp_msk1*(DBL_MAX_EXP+Bias-P))
-				goto ovfl;
-			if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
-				/* set to largest number */
-				/* (Can't trust DBL_MAX) */
-				word0(&rv) = Big0;
-				word1(&rv) = Big1;
-				}
-			else
-				word0(&rv) += P*Exp_msk1;
-			}
-		}
-	else if (e1 < 0) {
-		e1 = -e1;
-		i = e1 & 15;
-		if (i)
-			dval(&rv) /= tens[i];
-		if (e1 >>= 4) {
-			if (e1 >= 1 << n_bigtens)
-				goto undfl;
-#ifdef Avoid_Underflow
-			if (e1 & Scale_Bit)
-				bc.scale = 2*P;
-			for(j = 0; e1 > 0; j++, e1 >>= 1)
-				if (e1 & 1)
-					dval(&rv) *= tinytens[j];
-			if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask)
-						>> Exp_shift)) > 0) {
-				/* scaled rv is denormal; clear j low bits */
-				if (j >= 32) {
-					if (j > 54)
-						goto undfl;
-					word1(&rv) = 0;
-					if (j >= 53)
-					 word0(&rv) = (P+2)*Exp_msk1;
-					else
-					 word0(&rv) &= 0xffffffff << (j-32);
-					}
-				else
-					word1(&rv) &= 0xffffffff << j;
-				}
-#else
-			for(j = 0; e1 > 1; j++, e1 >>= 1)
-				if (e1 & 1)
-					dval(&rv) *= tinytens[j];
-			/* The last multiplication could underflow. */
-			dval(&rv0) = dval(&rv);
-			dval(&rv) *= tinytens[j];
-			if (!dval(&rv)) {
-				dval(&rv) = 2.*dval(&rv0);
-				dval(&rv) *= tinytens[j];
-#endif
-				if (!dval(&rv)) {
- undfl:
-					dval(&rv) = 0.;
-					goto range_err;
-					}
-#ifndef Avoid_Underflow
-				word0(&rv) = Tiny0;
-				word1(&rv) = Tiny1;
-				/* The refinement below will clean
-				 * this approximation up.
-				 */
-				}
-#endif
-			}
-		}
-
-	/* Now the hard part -- adjusting rv to the correct value.*/
-
-	/* Put digits into bd: true value = bd * 10^e */
-
-	bc.nd = nd - nz1;
-#ifndef NO_STRTOD_BIGCOMP
-	bc.nd0 = nd0;	/* Only needed if nd > strtod_diglim, but done here */
-			/* to silence an erroneous warning about bc.nd0 */
-			/* possibly not being initialized. */
-	if (nd > strtod_diglim) {
-		/* ASSERT(strtod_diglim >= 18); 18 == one more than the */
-		/* minimum number of decimal digits to distinguish double values */
-		/* in IEEE arithmetic. */
-		i = j = 18;
-		if (i > nd0)
-			j += bc.dplen;
-		for(;;) {
-			if (--j < bc.dp1 && j >= bc.dp0)
-				j = bc.dp0 - 1;
-			if (s0[j] != '0')
-				break;
-			--i;
-			}
-		e += nd - i;
-		nd = i;
-		if (nd0 > nd)
-			nd0 = nd;
-		if (nd < 9) { /* must recompute y */
-			y = 0;
-			for(i = 0; i < nd0; ++i)
-				y = 10*y + s0[i] - '0';
-			for(j = bc.dp1; i < nd; ++i)
-				y = 10*y + s0[j++] - '0';
-			}
-		}
-#endif
-	bd0 = s2b(s0, nd0, nd, y, bc.dplen);
-
-	for(;;) {
-		bd = Balloc(bd0->k);
-		Bcopy(bd, bd0);
-		bb = d2b(&rv, &bbe, &bbbits);	/* rv = bb * 2^bbe */
-		bs = i2b(1);
-
-		if (e >= 0) {
-			bb2 = bb5 = 0;
-			bd2 = bd5 = e;
-			}
-		else {
-			bb2 = bb5 = -e;
-			bd2 = bd5 = 0;
-			}
-		if (bbe >= 0)
-			bb2 += bbe;
-		else
-			bd2 -= bbe;
-		bs2 = bb2;
-#ifdef Honor_FLT_ROUNDS
-		if (bc.rounding != 1)
-			bs2++;
-#endif
-#ifdef Avoid_Underflow
-		Lsb = LSB;
-		Lsb1 = 0;
-		j = bbe - bc.scale;
-		i = j + bbbits - 1;	/* logb(rv) */
-		j = P + 1 - bbbits;
-		if (i < Emin) {	/* denormal */
-			i = Emin - i;
-			j -= i;
-			if (i < 32)
-				Lsb <<= i;
-			else if (i < 52)
-				Lsb1 = Lsb << (i-32);
-			else
-				Lsb1 = Exp_mask;
-			}
-#else /*Avoid_Underflow*/
-#ifdef Sudden_Underflow
-#ifdef IBM
-		j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
-#else
-		j = P + 1 - bbbits;
-#endif
-#else /*Sudden_Underflow*/
-		j = bbe;
-		i = j + bbbits - 1;	/* logb(rv) */
-		if (i < Emin)	/* denormal */
-			j += P - Emin;
-		else
-			j = P + 1 - bbbits;
-#endif /*Sudden_Underflow*/
-#endif /*Avoid_Underflow*/
-		bb2 += j;
-		bd2 += j;
-#ifdef Avoid_Underflow
-		bd2 += bc.scale;
-#endif
-		i = bb2 < bd2 ? bb2 : bd2;
-		if (i > bs2)
-			i = bs2;
-		if (i > 0) {
-			bb2 -= i;
-			bd2 -= i;
-			bs2 -= i;
-			}
-		if (bb5 > 0) {
-			bs = pow5mult(bs, bb5);
-			bb1 = mult(bs, bb);
-			Bfree(bb);
-			bb = bb1;
-			}
-		if (bb2 > 0)
-			bb = lshift(bb, bb2);
-		if (bd5 > 0)
-			bd = pow5mult(bd, bd5);
-		if (bd2 > 0)
-			bd = lshift(bd, bd2);
-		if (bs2 > 0)
-			bs = lshift(bs, bs2);
-		delta = diff(bb, bd);
-		bc.dsign = delta->sign;
-		delta->sign = 0;
-		i = cmp(delta, bs);
-#ifndef NO_STRTOD_BIGCOMP /*{*/
-		if (bc.nd > nd && i <= 0) {
-			if (bc.dsign) {
-				/* Must use bigcomp(). */
-				req_bigcomp = 1;
-				break;
-				}
-#ifdef Honor_FLT_ROUNDS
-			if (bc.rounding != 1) {
-				if (i < 0) {
-					req_bigcomp = 1;
-					break;
-					}
-				}
-			else
-#endif
-				i = -1;	/* Discarded digits make delta smaller. */
-			}
-#endif /*}*/
-#ifdef Honor_FLT_ROUNDS /*{*/
-		if (bc.rounding != 1) {
-			if (i < 0) {
-				/* Error is less than an ulp */
-				if (!delta->x[0] && delta->wds <= 1) {
-					/* exact */
-#ifdef SET_INEXACT
-					bc.inexact = 0;
-#endif
-					break;
-					}
-				if (bc.rounding) {
-					if (bc.dsign) {
-						adj.d = 1.;
-						goto apply_adj;
-						}
-					}
-				else if (!bc.dsign) {
-					adj.d = -1.;
-					if (!word1(&rv)
-					 && !(word0(&rv) & Frac_mask)) {
-						y = word0(&rv) & Exp_mask;
-#ifdef Avoid_Underflow
-						if (!bc.scale || y > 2*P*Exp_msk1)
-#else
-						if (y)
-#endif
-						  {
-						  delta = lshift(delta,Log2P);
-						  if (cmp(delta, bs) <= 0)
-							adj.d = -0.5;
-						  }
-						}
- apply_adj:
-#ifdef Avoid_Underflow /*{*/
-					if (bc.scale && (y = word0(&rv) & Exp_mask)
-						<= 2*P*Exp_msk1)
-					  word0(&adj) += (2*P+1)*Exp_msk1 - y;
-#else
-#ifdef Sudden_Underflow
-					if ((word0(&rv) & Exp_mask) <=
-							P*Exp_msk1) {
-						word0(&rv) += P*Exp_msk1;
-						dval(&rv) += adj.d*ulp(dval(&rv));
-						word0(&rv) -= P*Exp_msk1;
-						}
-					else
-#endif /*Sudden_Underflow*/
-#endif /*Avoid_Underflow}*/
-					dval(&rv) += adj.d*ulp(&rv);
-					}
-				break;
-				}
-			adj.d = ratio(delta, bs);
-			if (adj.d < 1.)
-				adj.d = 1.;
-			if (adj.d <= 0x7ffffffe) {
-				/* adj = rounding ? ceil(adj) : floor(adj); */
-				y = adj.d;
-				if (y != adj.d) {
-					if (!((bc.rounding>>1) ^ bc.dsign))
-						y++;
-					adj.d = y;
-					}
-				}
-#ifdef Avoid_Underflow /*{*/
-			if (bc.scale && (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1)
-				word0(&adj) += (2*P+1)*Exp_msk1 - y;
-#else
-#ifdef Sudden_Underflow
-			if ((word0(&rv) & Exp_mask) <= P*Exp_msk1) {
-				word0(&rv) += P*Exp_msk1;
-				adj.d *= ulp(dval(&rv));
-				if (bc.dsign)
-					dval(&rv) += adj.d;
-				else
-					dval(&rv) -= adj.d;
-				word0(&rv) -= P*Exp_msk1;
-				goto cont;
-				}
-#endif /*Sudden_Underflow*/
-#endif /*Avoid_Underflow}*/
-			adj.d *= ulp(&rv);
-			if (bc.dsign) {
-				if (word0(&rv) == Big0 && word1(&rv) == Big1)
-					goto ovfl;
-				dval(&rv) += adj.d;
-				}
-			else
-				dval(&rv) -= adj.d;
-			goto cont;
-			}
-#endif /*}Honor_FLT_ROUNDS*/
-
-		if (i < 0) {
-			/* Error is less than half an ulp -- check for
-			 * special case of mantissa a power of two.
-			 */
-			if (bc.dsign || word1(&rv) || word0(&rv) & Bndry_mask
-#ifdef IEEE_Arith /*{*/
-#ifdef Avoid_Underflow
-			 || (word0(&rv) & Exp_mask) <= (2*P+1)*Exp_msk1
-#else
-			 || (word0(&rv) & Exp_mask) <= Exp_msk1
-#endif
-#endif /*}*/
-				) {
-#ifdef SET_INEXACT
-				if (!delta->x[0] && delta->wds <= 1)
-					bc.inexact = 0;
-#endif
-				break;
-				}
-			if (!delta->x[0] && delta->wds <= 1) {
-				/* exact result */
-#ifdef SET_INEXACT
-				bc.inexact = 0;
-#endif
-				break;
-				}
-			delta = lshift(delta,Log2P);
-			if (cmp(delta, bs) > 0)
-				goto drop_down;
-			break;
-			}
-		if (i == 0) {
-			/* exactly half-way between */
-			if (bc.dsign) {
-				if ((word0(&rv) & Bndry_mask1) == Bndry_mask1
-				 &&  word1(&rv) == (
-#ifdef Avoid_Underflow
-			(bc.scale && (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1)
-		? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
-#endif
-						   0xffffffff)) {
-					/*boundary case -- increment exponent*/
-					if (word0(&rv) == Big0 && word1(&rv) == Big1)
-						goto ovfl;
-					word0(&rv) = (word0(&rv) & Exp_mask)
-						+ Exp_msk1
-#ifdef IBM
-						| Exp_msk1 >> 4
-#endif
-						;
-					word1(&rv) = 0;
-#ifdef Avoid_Underflow
-					bc.dsign = 0;
-#endif
-					break;
-					}
-				}
-			else if (!(word0(&rv) & Bndry_mask) && !word1(&rv)) {
- drop_down:
-				/* boundary case -- decrement exponent */
-#ifdef Sudden_Underflow /*{{*/
-				L = word0(&rv) & Exp_mask;
-#ifdef IBM
-				if (L <  Exp_msk1)
-#else
-#ifdef Avoid_Underflow
-				if (L <= (bc.scale ? (2*P+1)*Exp_msk1 : Exp_msk1))
-#else
-				if (L <= Exp_msk1)
-#endif /*Avoid_Underflow*/
-#endif /*IBM*/
-					{
-					if (bc.nd >nd) {
-						bc.uflchk = 1;
-						break;
-						}
-					goto undfl;
-					}
-				L -= Exp_msk1;
-#else /*Sudden_Underflow}{*/
-#ifdef Avoid_Underflow
-				if (bc.scale) {
-					L = word0(&rv) & Exp_mask;
-					if (L <= (2*P+1)*Exp_msk1) {
-						if (L > (P+2)*Exp_msk1)
-							/* round even ==> */
-							/* accept rv */
-							break;
-						/* rv = smallest denormal */
-						if (bc.nd >nd) {
-							bc.uflchk = 1;
-							break;
-							}
-						goto undfl;
-						}
-					}
-#endif /*Avoid_Underflow*/
-				L = (word0(&rv) & Exp_mask) - Exp_msk1;
-#endif /*Sudden_Underflow}}*/
-				word0(&rv) = L | Bndry_mask1;
-				word1(&rv) = 0xffffffff;
-#ifdef IBM
-				goto cont;
-#else
-#ifndef NO_STRTOD_BIGCOMP
-				if (bc.nd > nd)
-					goto cont;
-#endif
-				break;
-#endif
-				}
-#ifndef ROUND_BIASED
-#ifdef Avoid_Underflow
-			if (Lsb1) {
-				if (!(word0(&rv) & Lsb1))
-					break;
-				}
-			else if (!(word1(&rv) & Lsb))
-				break;
-#else
-			if (!(word1(&rv) & LSB))
-				break;
-#endif
-#endif
-			if (bc.dsign)
-#ifdef Avoid_Underflow
-				dval(&rv) += sulp(&rv, &bc);
-#else
-				dval(&rv) += ulp(&rv);
-#endif
-#ifndef ROUND_BIASED
-			else {
-#ifdef Avoid_Underflow
-				dval(&rv) -= sulp(&rv, &bc);
-#else
-				dval(&rv) -= ulp(&rv);
-#endif
-#ifndef Sudden_Underflow
-				if (!dval(&rv)) {
-					if (bc.nd >nd) {
-						bc.uflchk = 1;
-						break;
-						}
-					goto undfl;
-					}
-#endif
-				}
-#ifdef Avoid_Underflow
-			bc.dsign = 1 - bc.dsign;
-#endif
-#endif
-			break;
-			}
-		if ((aadj = ratio(delta, bs)) <= 2.) {
-			if (bc.dsign)
-				aadj = aadj1 = 1.;
-			else if (word1(&rv) || word0(&rv) & Bndry_mask) {
-#ifndef Sudden_Underflow
-				if (word1(&rv) == Tiny1 && !word0(&rv)) {
-					if (bc.nd >nd) {
-						bc.uflchk = 1;
-						break;
-						}
-					goto undfl;
-					}
-#endif
-				aadj = 1.;
-				aadj1 = -1.;
-				}
-			else {
-				/* special case -- power of FLT_RADIX to be */
-				/* rounded down... */
-
-				if (aadj < 2./FLT_RADIX)
-					aadj = 1./FLT_RADIX;
-				else
-					aadj *= 0.5;
-				aadj1 = -aadj;
-				}
-			}
-		else {
-			aadj *= 0.5;
-			aadj1 = bc.dsign ? aadj : -aadj;
-#ifdef Check_FLT_ROUNDS
-			switch(bc.rounding) {
-				case 2: /* towards +infinity */
-					aadj1 -= 0.5;
-					break;
-				case 0: /* towards 0 */
-				case 3: /* towards -infinity */
-					aadj1 += 0.5;
-				}
-#else
-			if (Flt_Rounds == 0)
-				aadj1 += 0.5;
-#endif /*Check_FLT_ROUNDS*/
-			}
-		y = word0(&rv) & Exp_mask;
-
-		/* Check for overflow */
-
-		if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
-			dval(&rv0) = dval(&rv);
-			word0(&rv) -= P*Exp_msk1;
-			adj.d = aadj1 * ulp(&rv);
-			dval(&rv) += adj.d;
-			if ((word0(&rv) & Exp_mask) >=
-					Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
-				if (word0(&rv0) == Big0 && word1(&rv0) == Big1)
-					goto ovfl;
-				word0(&rv) = Big0;
-				word1(&rv) = Big1;
-				goto cont;
-				}
-			else
-				word0(&rv) += P*Exp_msk1;
-			}
-		else {
-#ifdef Avoid_Underflow
-			if (bc.scale && y <= 2*P*Exp_msk1) {
-				if (aadj <= 0x7fffffff) {
-					if ((z = (ULong)aadj) <= 0)
-						z = 1;
-					aadj = z;
-					aadj1 = bc.dsign ? aadj : -aadj;
-					}
-				dval(&aadj2) = aadj1;
-				word0(&aadj2) += (2*P+1)*Exp_msk1 - y;
-				aadj1 = dval(&aadj2);
-				adj.d = aadj1 * ulp(&rv);
-				dval(&rv) += adj.d;
-				if (rv.d == 0.)
-#ifdef NO_STRTOD_BIGCOMP
-					goto undfl;
-#else
-					{
-					req_bigcomp = 1;
-					break;
-					}
-#endif
-				}
-			else {
-				adj.d = aadj1 * ulp(&rv);
-				dval(&rv) += adj.d;
-				}
-#else
-#ifdef Sudden_Underflow
-			if ((word0(&rv) & Exp_mask) <= P*Exp_msk1) {
-				dval(&rv0) = dval(&rv);
-				word0(&rv) += P*Exp_msk1;
-				adj.d = aadj1 * ulp(&rv);
-				dval(&rv) += adj.d;
-#ifdef IBM
-				if ((word0(&rv) & Exp_mask) <  P*Exp_msk1)
-#else
-				if ((word0(&rv) & Exp_mask) <= P*Exp_msk1)
-#endif
-					{
-					if (word0(&rv0) == Tiny0
-					 && word1(&rv0) == Tiny1) {
-						if (bc.nd >nd) {
-							bc.uflchk = 1;
-							break;
-							}
-						goto undfl;
-						}
-					word0(&rv) = Tiny0;
-					word1(&rv) = Tiny1;
-					goto cont;
-					}
-				else
-					word0(&rv) -= P*Exp_msk1;
-				}
-			else {
-				adj.d = aadj1 * ulp(&rv);
-				dval(&rv) += adj.d;
-				}
-#else /*Sudden_Underflow*/
-			/* Compute adj so that the IEEE rounding rules will
-			 * correctly round rv + adj in some half-way cases.
-			 * If rv * ulp(rv) is denormalized (i.e.,
-			 * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
-			 * trouble from bits lost to denormalization;
-			 * example: 1.2e-307 .
-			 */
-			if (y <= (P-1)*Exp_msk1 && aadj > 1.) {
-				aadj1 = (double)(int)(aadj + 0.5);
-				if (!bc.dsign)
-					aadj1 = -aadj1;
-				}
-			adj.d = aadj1 * ulp(&rv);
-			dval(&rv) += adj.d;
-#endif /*Sudden_Underflow*/
-#endif /*Avoid_Underflow*/
-			}
-		z = word0(&rv) & Exp_mask;
-#ifndef SET_INEXACT
-		if (bc.nd == nd) {
-#ifdef Avoid_Underflow
-		if (!bc.scale)
-#endif
-		if (y == z) {
-			/* Can we stop now? */
-			L = (Long)aadj;
-			aadj -= L;
-			/* The tolerances below are conservative. */
-			if (bc.dsign || word1(&rv) || word0(&rv) & Bndry_mask) {
-				if (aadj < .4999999 || aadj > .5000001)
-					break;
-				}
-			else if (aadj < .4999999/FLT_RADIX)
-				break;
-			}
-		}
-#endif
- cont:
-		Bfree(bb);
-		Bfree(bd);
-		Bfree(bs);
-		Bfree(delta);
-		}
-	Bfree(bb);
-	Bfree(bd);
-	Bfree(bs);
-	Bfree(bd0);
-	Bfree(delta);
-#ifndef NO_STRTOD_BIGCOMP
-	if (req_bigcomp) {
-		bd0 = 0;
-		bc.e0 += nz1;
-		bigcomp(&rv, s0, &bc);
-		y = word0(&rv) & Exp_mask;
-		if (y == Exp_mask)
-			goto ovfl;
-		if (y == 0 && rv.d == 0.)
-			goto undfl;
-		}
-#endif
-#ifdef SET_INEXACT
-	if (bc.inexact) {
-		if (!oldinexact) {
-			word0(&rv0) = Exp_1 + (70 << Exp_shift);
-			word1(&rv0) = 0;
-			dval(&rv0) += 1.;
-			}
-		}
-	else if (!oldinexact)
-		clear_inexact();
-#endif
-#ifdef Avoid_Underflow
-	if (bc.scale) {
-		word0(&rv0) = Exp_1 - 2*P*Exp_msk1;
-		word1(&rv0) = 0;
-		dval(&rv) *= dval(&rv0);
-#ifndef NO_ERRNO
-		/* try to avoid the bug of testing an 8087 register value */
-#ifdef IEEE_Arith
-		if (!(word0(&rv) & Exp_mask))
-#else
-		if (word0(&rv) == 0 && word1(&rv) == 0)
-#endif
-			errno = ERANGE;
-#endif
-		}
-#endif /* Avoid_Underflow */
-#ifdef SET_INEXACT
-	if (bc.inexact && !(word0(&rv) & Exp_mask)) {
-		/* set underflow bit */
-		dval(&rv0) = 1e-300;
-		dval(&rv0) *= dval(&rv0);
-		}
-#endif
- ret:
-	if (se)
-		*se = (char *)s;
-	return sign ? -dval(&rv) : dval(&rv);
-	}
-
-#ifndef MULTIPLE_THREADS
- static char *dtoa_result;
-#endif
-
- static char *
-#ifdef KR_headers
-rv_alloc(i) int i;
-#else
-rv_alloc(int i)
-#endif
-{
-	int j, k, *r;
-
-	j = sizeof(ULong);
-	for(k = 0;
-		sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (size_t)i;
-		j <<= 1)
-			k++;
-	r = (int*)Balloc(k);
-	*r = k;
-	return
-#ifndef MULTIPLE_THREADS
-	dtoa_result =
-#endif
-		(char *)(r+1);
-	}
-
- static char *
-#ifdef KR_headers
-nrv_alloc(s, rve, n) char *s, **rve; int n;
-#else
-nrv_alloc(const char *s, char **rve, int n)
-#endif
-{
-	char *rv, *t;
-
-	t = rv = rv_alloc(n);
-	for(*t = *s++; *t; *t = *s++) t++;
-	if (rve)
-		*rve = t;
-	return rv;
-	}
-
-/* freedtoa(s) must be used to free values s returned by dtoa
- * when MULTIPLE_THREADS is #defined.  It should be used in all cases,
- * but for consistency with earlier versions of dtoa, it is optional
- * when MULTIPLE_THREADS is not defined.
- */
-
- void
-#ifdef KR_headers
-freedtoa(s) char *s;
-#else
-freedtoa(char *s)
-#endif
-{
-	Bigint *b = (Bigint *)((int *)s - 1);
-	b->maxwds = 1 << (b->k = *(int*)b);
-	Bfree(b);
-#ifndef MULTIPLE_THREADS
-	if (s == dtoa_result)
-		dtoa_result = 0;
-#endif
-	}
-
-/* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
- *
- * Inspired by "How to Print Floating-Point Numbers Accurately" by
- * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
- *
- * Modifications:
- *	1. Rather than iterating, we use a simple numeric overestimate
- *	   to determine k = floor(log10(d)).  We scale relevant
- *	   quantities using O(log2(k)) rather than O(k) multiplications.
- *	2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
- *	   try to generate digits strictly left to right.  Instead, we
- *	   compute with fewer bits and propagate the carry if necessary
- *	   when rounding the final digit up.  This is often faster.
- *	3. Under the assumption that input will be rounded nearest,
- *	   mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
- *	   That is, we allow equality in stopping tests when the
- *	   round-nearest rule will give the same floating-point value
- *	   as would satisfaction of the stopping test with strict
- *	   inequality.
- *	4. We remove common factors of powers of 2 from relevant
- *	   quantities.
- *	5. When converting floating-point integers less than 1e16,
- *	   we use floating-point arithmetic rather than resorting
- *	   to multiple-precision integers.
- *	6. When asked to produce fewer than 15 digits, we first try
- *	   to get by with floating-point arithmetic; we resort to
- *	   multiple-precision integer arithmetic only if we cannot
- *	   guarantee that the floating-point calculation has given
- *	   the correctly rounded result.  For k requested digits and
- *	   "uniformly" distributed input, the probability is
- *	   something like 10^(k-15) that we must resort to the Long
- *	   calculation.
- */
-
- char *
-dtoa
-#ifdef KR_headers
-	(dd, mode, ndigits, decpt, sign, rve)
-	double dd; int mode, ndigits, *decpt, *sign; char **rve;
-#else
-	(double dd, int mode, int ndigits, int *decpt, int *sign, char **rve)
-#endif
-{
- /*	Arguments ndigits, decpt, sign are similar to those
-	of ecvt and fcvt; trailing zeros are suppressed from
-	the returned string.  If not null, *rve is set to point
-	to the end of the return value.  If d is +-Infinity or NaN,
-	then *decpt is set to 9999.
-
-	mode:
-		0 ==> shortest string that yields d when read in
-			and rounded to nearest.
-		1 ==> like 0, but with Steele & White stopping rule;
-			e.g. with IEEE P754 arithmetic , mode 0 gives
-			1e23 whereas mode 1 gives 9.999999999999999e22.
-		2 ==> max(1,ndigits) significant digits.  This gives a
-			return value similar to that of ecvt, except
-			that trailing zeros are suppressed.
-		3 ==> through ndigits past the decimal point.  This
-			gives a return value similar to that from fcvt,
-			except that trailing zeros are suppressed, and
-			ndigits can be negative.
-		4,5 ==> similar to 2 and 3, respectively, but (in
-			round-nearest mode) with the tests of mode 0 to
-			possibly return a shorter string that rounds to d.
-			With IEEE arithmetic and compilation with
-			-DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
-			as modes 2 and 3 when FLT_ROUNDS != 1.
-		6-9 ==> Debugging modes similar to mode - 4:  don't try
-			fast floating-point estimate (if applicable).
-
-		Values of mode other than 0-9 are treated as mode 0.
-
-		Sufficient space is allocated to the return value
-		to hold the suppressed trailing zeros.
-	*/
-
-	int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
-		j, j1 = 0, k, k0, k_check, leftright, m2, m5, s2, s5,
-		spec_case, try_quick;
-	Long L;
-#ifndef Sudden_Underflow
-	int denorm;
-	ULong x;
-#endif
-	Bigint *b, *b1, *delta, *mlo = NULL, *mhi, *S;
-	U d2, eps, u;
-	double ds;
-	char *s, *s0;
-#ifndef No_leftright
-#ifdef IEEE_Arith
-	U eps1;
-#endif
-#endif
-#ifdef SET_INEXACT
-	int inexact, oldinexact;
-#endif
-#ifdef Honor_FLT_ROUNDS /*{*/
-	int Rounding;
-#ifdef Trust_FLT_ROUNDS /*{{ only define this if FLT_ROUNDS really works! */
-	Rounding = Flt_Rounds;
-#else /*}{*/
-	Rounding = 1;
-	switch(fegetround()) {
-	  case FE_TOWARDZERO:	Rounding = 0; break;
-	  case FE_UPWARD:	Rounding = 2; break;
-	  case FE_DOWNWARD:	Rounding = 3;
-	  }
-#endif /*}}*/
-#endif /*}*/
-
-#ifndef MULTIPLE_THREADS
-	if (dtoa_result) {
-		freedtoa(dtoa_result);
-		dtoa_result = 0;
-		}
-#endif
-
-	u.d = dd;
-	if (word0(&u) & Sign_bit) {
-		/* set sign for everything, including 0's and NaNs */
-		*sign = 1;
-		word0(&u) &= ~Sign_bit;	/* clear sign bit */
-		}
-	else
-		*sign = 0;
-
-#if defined(IEEE_Arith) + defined(VAX)
-#ifdef IEEE_Arith
-	if ((word0(&u) & Exp_mask) == Exp_mask)
-#else
-	if (word0(&u)  == 0x8000)
-#endif
-		{
-		/* Infinity or NaN */
-		*decpt = 9999;
-#ifdef IEEE_Arith
-		if (!word1(&u) && !(word0(&u) & 0xfffff))
-			return nrv_alloc("Infinity", rve, 8);
-#endif
-		return nrv_alloc("NaN", rve, 3);
-		}
-#endif
-#ifdef IBM
-	dval(&u) += 0; /* normalize */
-#endif
-	if (!dval(&u)) {
-		*decpt = 1;
-		return nrv_alloc("0", rve, 1);
-		}
-
-#ifdef SET_INEXACT
-	try_quick = oldinexact = get_inexact();
-	inexact = 1;
-#endif
-#ifdef Honor_FLT_ROUNDS
-	if (Rounding >= 2) {
-		if (*sign)
-			Rounding = Rounding == 2 ? 0 : 2;
-		else
-			if (Rounding != 2)
-				Rounding = 0;
-		}
-#endif
-
-	b = d2b(&u, &be, &bbits);
-	i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
-#ifndef Sudden_Underflow
-	if (i) {
-#endif
-		dval(&d2) = dval(&u);
-		word0(&d2) &= Frac_mask1;
-		word0(&d2) |= Exp_11;
-#ifdef IBM
-		if (j = 11 - hi0bits(word0(&d2) & Frac_mask))
-			dval(&d2) /= 1 << j;
-#endif
-
-		/* log(x)	~=~ log(1.5) + (x-1.5)/1.5
-		 * log10(x)	 =  log(x) / log(10)
-		 *		~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
-		 * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
-		 *
-		 * This suggests computing an approximation k to log10(d) by
-		 *
-		 * k = (i - Bias)*0.301029995663981
-		 *	+ ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
-		 *
-		 * We want k to be too large rather than too small.
-		 * The error in the first-order Taylor series approximation
-		 * is in our favor, so we just round up the constant enough
-		 * to compensate for any error in the multiplication of
-		 * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
-		 * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
-		 * adding 1e-13 to the constant term more than suffices.
-		 * Hence we adjust the constant term to 0.1760912590558.
-		 * (We could get a more accurate k by invoking log10,
-		 *  but this is probably not worthwhile.)
-		 */
-
-		i -= Bias;
-#ifdef IBM
-		i <<= 2;
-		i += j;
-#endif
-#ifndef Sudden_Underflow
-		denorm = 0;
-		}
-	else {
-		/* d is denormalized */
-
-		i = bbits + be + (Bias + (P-1) - 1);
-		x = i > 32  ? word0(&u) << (64 - i) | word1(&u) >> (i - 32)
-			    : word1(&u) << (32 - i);
-		dval(&d2) = x;
-		word0(&d2) -= 31*Exp_msk1; /* adjust exponent */
-		i -= (Bias + (P-1) - 1) + 1;
-		denorm = 1;
-		}
-#endif
-	ds = (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
-	k = (int)ds;
-	if (ds < 0. && ds != k)
-		k--;	/* want k = floor(ds) */
-	k_check = 1;
-	if (k >= 0 && k <= Ten_pmax) {
-		if (dval(&u) < tens[k])
-			k--;
-		k_check = 0;
-		}
-	j = bbits - i - 1;
-	if (j >= 0) {
-		b2 = 0;
-		s2 = j;
-		}
-	else {
-		b2 = -j;
-		s2 = 0;
-		}
-	if (k >= 0) {
-		b5 = 0;
-		s5 = k;
-		s2 += k;
-		}
-	else {
-		b2 -= k;
-		b5 = -k;
-		s5 = 0;
-		}
-	if (mode < 0 || mode > 9)
-		mode = 0;
-
-#ifndef SET_INEXACT
-#ifdef Check_FLT_ROUNDS
-	try_quick = Rounding == 1;
-#else
-	try_quick = 1;
-#endif
-#endif /*SET_INEXACT*/
-
-	if (mode > 5) {
-		mode -= 4;
-		try_quick = 0;
-		}
-	leftright = 1;
-	ilim = ilim1 = -1;	/* Values for cases 0 and 1; done here to */
-				/* silence erroneous "gcc -Wall" warning. */
-	switch(mode) {
-		case 0:
-		case 1:
-			i = 18;
-			ndigits = 0;
-			break;
-		case 2:
-			leftright = 0;
-			FALLTHROUGH;
-		case 4:
-			if (ndigits <= 0)
-				ndigits = 1;
-			ilim = ilim1 = i = ndigits;
-			break;
-		case 3:
-			leftright = 0;
-			FALLTHROUGH;
-		case 5:
-			i = ndigits + k + 1;
-			ilim = i;
-			ilim1 = i - 1;
-			if (i <= 0)
-				i = 1;
-		}
-	s = s0 = rv_alloc(i);
-
-#ifdef Honor_FLT_ROUNDS
-	if (mode > 1 && Rounding != 1)
-		leftright = 0;
-#endif
-
-	if (ilim >= 0 && ilim <= Quick_max && try_quick) {
-
-		/* Try to get by with floating-point arithmetic. */
-
-		i = 0;
-		dval(&d2) = dval(&u);
-		k0 = k;
-		ilim0 = ilim;
-		ieps = 2; /* conservative */
-		if (k > 0) {
-			ds = tens[k&0xf];
-			j = k >> 4;
-			if (j & Bletch) {
-				/* prevent overflows */
-				j &= Bletch - 1;
-				dval(&u) /= bigtens[n_bigtens-1];
-				ieps++;
-				}
-			for(; j; j >>= 1, i++)
-				if (j & 1) {
-					ieps++;
-					ds *= bigtens[i];
-					}
-			dval(&u) /= ds;
-			}
-		else {
-			j1 = -k;
-			if (j1) {
-				dval(&u) *= tens[j1 & 0xf];
-				for(j = j1 >> 4; j; j >>= 1, i++)
-					if (j & 1) {
-						ieps++;
-						dval(&u) *= bigtens[i];
-						}
-				}
-			}
-		if (k_check && dval(&u) < 1. && ilim > 0) {
-			if (ilim1 <= 0)
-				goto fast_failed;
-			ilim = ilim1;
-			k--;
-			dval(&u) *= 10.;
-			ieps++;
-			}
-		dval(&eps) = ieps*dval(&u) + 7.;
-		word0(&eps) -= (P-1)*Exp_msk1;
-		if (ilim == 0) {
-			S = mhi = 0;
-			dval(&u) -= 5.;
-			if (dval(&u) > dval(&eps))
-				goto one_digit;
-			if (dval(&u) < -dval(&eps))
-				goto no_digits;
-			goto fast_failed;
-			}
-#ifndef No_leftright
-		if (leftright) {
-			/* Use Steele & White method of only
-			 * generating digits needed.
-			 */
-			dval(&eps) = 0.5/tens[ilim-1] - dval(&eps);
-#ifdef IEEE_Arith
-			if (k0 < 0 && j1 >= 307) {
-				eps1.d = 1.01e256; /* 1.01 allows roundoff in the next few lines */
-				word0(&eps1) -= Exp_msk1 * (Bias+P-1);
-				dval(&eps1) *= tens[j1 & 0xf];
-				for(i = 0, j = (j1-256) >> 4; j; j >>= 1, i++)
-					if (j & 1)
-						dval(&eps1) *= bigtens[i];
-				if (eps.d < eps1.d)
-					eps.d = eps1.d;
-				}
-#endif
-			for(i = 0;;) {
-				L = dval(&u);
-				dval(&u) -= L;
-				*s++ = '0' + (int)L;
-				if (1. - dval(&u) < dval(&eps))
-					goto bump_up;
-				if (dval(&u) < dval(&eps))
-					goto ret1;
-				if (++i >= ilim)
-					break;
-				dval(&eps) *= 10.;
-				dval(&u) *= 10.;
-				}
-			}
-		else {
-#endif
-			/* Generate ilim digits, then fix them up. */
-			dval(&eps) *= tens[ilim-1];
-			for(i = 1;; i++, dval(&u) *= 10.) {
-				L = (Long)(dval(&u));
-				if (!(dval(&u) -= L))
-					ilim = i;
-				*s++ = '0' + (char)L;
-				if (i == ilim) {
-					if (dval(&u) > 0.5 + dval(&eps))
-						goto bump_up;
-					else if (dval(&u) < 0.5 - dval(&eps)) {
-						while(*--s == '0') {}
-						s++;
-						goto ret1;
-						}
-					break;
-					}
-				}
-#ifndef No_leftright
-			}
-#endif
- fast_failed:
-		s = s0;
-		dval(&u) = dval(&d2);
-		k = k0;
-		ilim = ilim0;
-		}
-
-	/* Do we have a "small" integer? */
-
-	if (be >= 0 && k <= Int_max) {
-		/* Yes. */
-		ds = tens[k];
-		if (ndigits < 0 && ilim <= 0) {
-			S = mhi = 0;
-			if (ilim < 0 || dval(&u) <= 5*ds)
-				goto no_digits;
-			goto one_digit;
-			}
-		for(i = 1;; i++, dval(&u) *= 10.) {
-			L = (Long)(dval(&u) / ds);
-			dval(&u) -= L*ds;
-#ifdef Check_FLT_ROUNDS
-			/* If FLT_ROUNDS == 2, L will usually be high by 1 */
-			if (dval(&u) < 0) {
-				L--;
-				dval(&u) += ds;
-				}
-#endif
-			*s++ = '0' + (char)L;
-			if (!dval(&u)) {
-#ifdef SET_INEXACT
-				inexact = 0;
-#endif
-				break;
-				}
-			if (i == ilim) {
-#ifdef Honor_FLT_ROUNDS
-				if (mode > 1)
-				switch(Rounding) {
-				  case 0: goto ret1;
-				  case 2: goto bump_up;
-				  }
-#endif
-				dval(&u) += dval(&u);
-#ifdef ROUND_BIASED
-				if (dval(&u) >= ds)
-#else
-				if (dval(&u) > ds || (dval(&u) == ds && L & 1))
-#endif
-					{
- bump_up:
-					while(*--s == '9')
-						if (s == s0) {
-							k++;
-							*s = '0';
-							break;
-							}
-					++*s++;
-					}
-				break;
-				}
-			}
-		goto ret1;
-		}
-
-	m2 = b2;
-	m5 = b5;
-	mhi = mlo = 0;
-	if (leftright) {
-		i =
-#ifndef Sudden_Underflow
-			denorm ? be + (Bias + (P-1) - 1 + 1) :
-#endif
-#ifdef IBM
-			1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3);
-#else
-			1 + P - bbits;
-#endif
-		b2 += i;
-		s2 += i;
-		mhi = i2b(1);
-		}
-	if (m2 > 0 && s2 > 0) {
-		i = m2 < s2 ? m2 : s2;
-		b2 -= i;
-		m2 -= i;
-		s2 -= i;
-		}
-	if (b5 > 0) {
-		if (leftright) {
-			if (m5 > 0) {
-				mhi = pow5mult(mhi, m5);
-				b1 = mult(mhi, b);
-				Bfree(b);
-				b = b1;
-				}
-			j = b5 - m5;
-			if (j)
-				b = pow5mult(b, j);
-			}
-		else
-			b = pow5mult(b, b5);
-		}
-	S = i2b(1);
-	if (s5 > 0)
-		S = pow5mult(S, s5);
-
-	/* Check for special case that d is a normalized power of 2. */
-
-	spec_case = 0;
-	if ((mode < 2 || leftright)
-#ifdef Honor_FLT_ROUNDS
-			&& Rounding == 1
-#endif
-				) {
-		if (!word1(&u) && !(word0(&u) & Bndry_mask)
-#ifndef Sudden_Underflow
-		 && word0(&u) & (Exp_mask & ~Exp_msk1)
-#endif
-				) {
-			/* The special case */
-			b2 += Log2P;
-			s2 += Log2P;
-			spec_case = 1;
-			}
-		}
-
-	/* Arrange for convenient computation of quotients:
-	 * shift left if necessary so divisor has 4 leading 0 bits.
-	 *
-	 * Perhaps we should just compute leading 28 bits of S once
-	 * and for all and pass them and a shift to quorem, so it
-	 * can do shifts and ors to compute the numerator for q.
-	 */
-	i = dshift(S, s2);
-	b2 += i;
-	m2 += i;
-	s2 += i;
-	if (b2 > 0)
-		b = lshift(b, b2);
-	if (s2 > 0)
-		S = lshift(S, s2);
-	if (k_check) {
-		if (cmp(b,S) < 0) {
-			k--;
-			b = multadd(b, 10, 0);	/* we botched the k estimate */
-			if (leftright)
-				mhi = multadd(mhi, 10, 0);
-			ilim = ilim1;
-			}
-		}
-	if (ilim <= 0 && (mode == 3 || mode == 5)) {
-		if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
-			/* no digits, fcvt style */
- no_digits:
-			k = -1 - ndigits;
-			goto ret;
-			}
- one_digit:
-		*s++ = '1';
-		k++;
-		goto ret;
-		}
-	if (leftright) {
-		if (m2 > 0)
-			mhi = lshift(mhi, m2);
-
-		/* Compute mlo -- check for special case
-		 * that d is a normalized power of 2.
-		 */
-
-		mlo = mhi;
-		if (spec_case) {
-			mhi = Balloc(mhi->k);
-			Bcopy(mhi, mlo);
-			mhi = lshift(mhi, Log2P);
-			}
-
-		for(i = 1;;i++) {
-			dig = quorem(b,S) + '0';
-			/* Do we yet have the shortest decimal string
-			 * that will round to d?
-			 */
-			j = cmp(b, mlo);
-			delta = diff(S, mhi);
-			j1 = delta->sign ? 1 : cmp(b, delta);
-			Bfree(delta);
-#ifndef ROUND_BIASED
-			if (j1 == 0 && mode != 1 && !(word1(&u) & 1)
-#ifdef Honor_FLT_ROUNDS
-				&& Rounding >= 1
-#endif
-								   ) {
-				if (dig == '9')
-					goto round_9_up;
-				if (j > 0)
-					dig++;
-#ifdef SET_INEXACT
-				else if (!b->x[0] && b->wds <= 1)
-					inexact = 0;
-#endif
-				*s++ = (char)dig;
-				goto ret;
-				}
-#endif
-			if (j < 0 || (j == 0 && mode != 1
-#ifndef ROUND_BIASED
-							&& !(word1(&u) & 1)
-#endif
-					)) {
-				if (!b->x[0] && b->wds <= 1) {
-#ifdef SET_INEXACT
-					inexact = 0;
-#endif
-					goto accept_dig;
-					}
-#ifdef Honor_FLT_ROUNDS
-				if (mode > 1)
-				 switch(Rounding) {
-				  case 0: goto accept_dig;
-				  case 2: goto keep_dig;
-				  }
-#endif /*Honor_FLT_ROUNDS*/
-				if (j1 > 0) {
-					b = lshift(b, 1);
-					j1 = cmp(b, S);
-#ifdef ROUND_BIASED
-					if (j1 >= 0 /*)*/
-#else
-					if ((j1 > 0 || (j1 == 0 && dig & 1))
-#endif
-					&& dig++ == '9')
-						goto round_9_up;
-					}
- accept_dig:
-				*s++ = (char)dig;
-				goto ret;
-				}
-			if (j1 > 0) {
-#ifdef Honor_FLT_ROUNDS
-				if (!Rounding)
-					goto accept_dig;
-#endif
-				if (dig == '9') { /* possible if i == 1 */
- round_9_up:
-					*s++ = '9';
-					goto roundoff;
-					}
-				*s++ = (char)dig + 1;
-				goto ret;
-				}
-#ifdef Honor_FLT_ROUNDS
- keep_dig:
-#endif
-			*s++ = (char)dig;
-			if (i == ilim)
-				break;
-			b = multadd(b, 10, 0);
-			if (mlo == mhi)
-				mlo = mhi = multadd(mhi, 10, 0);
-			else {
-				mlo = multadd(mlo, 10, 0);
-				mhi = multadd(mhi, 10, 0);
-				}
-			}
-		}
-	else
-		for(i = 1;; i++) {
-			dig = quorem(b,S) + '0';
-			*s++ = (char)dig;
-			if (!b->x[0] && b->wds <= 1) {
-#ifdef SET_INEXACT
-				inexact = 0;
-#endif
-				goto ret;
-				}
-			if (i >= ilim)
-				break;
-			b = multadd(b, 10, 0);
-			}
-
-	/* Round off last digit */
-
-#ifdef Honor_FLT_ROUNDS
-	switch(Rounding) {
-	  case 0: goto trimzeros;
-	  case 2: goto roundoff;
-	  }
-#endif
-	b = lshift(b, 1);
-	j = cmp(b, S);
-#ifdef ROUND_BIASED
-	if (j >= 0)
-#else
-	if (j > 0 || (j == 0 && dig & 1))
-#endif
-		{
- roundoff:
-		while(*--s == '9')
-			if (s == s0) {
-				k++;
-				*s++ = '1';
-				goto ret;
-				}
-		++*s++;
-		}
-	else {
-#ifdef Honor_FLT_ROUNDS
- trimzeros:
-#endif
-		while(*--s == '0') {}
-		s++;
-		}
- ret:
-	Bfree(S);
-	if (mhi) {
-		if (mlo && mlo != mhi)
-			Bfree(mlo);
-		Bfree(mhi);
-		}
- ret1:
-#ifdef SET_INEXACT
-	if (inexact) {
-		if (!oldinexact) {
-			word0(&u) = Exp_1 + (70 << Exp_shift);
-			word1(&u) = 0;
-			dval(&u) += 1.;
-			}
-		}
-	else if (!oldinexact)
-		clear_inexact();
-#endif
-	Bfree(b);
-	*s = 0;
-	*decpt = k + 1;
-	if (rve)
-		*rve = s;
-	return s0;
-	}
-
-}  // namespace dmg_fp
diff --git a/base/third_party/dmg_fp/dtoa_wrapper.cc b/base/third_party/dmg_fp/dtoa_wrapper.cc
deleted file mode 100644
index fb1ac8f..0000000
--- a/base/third_party/dmg_fp/dtoa_wrapper.cc
+++ /dev/null
@@ -1,49 +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.
-//
-// The purpose of this file is to supply the macro definintions necessary
-// to make third_party/dmg_fp/dtoa.cc threadsafe.
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/synchronization/lock.h"
-
-// We need two locks because they're sometimes grabbed at the same time.
-// A single lock would lead to an attempted recursive grab.
-static base::LazyInstance<base::Lock>::Leaky
-    dtoa_lock_0 = LAZY_INSTANCE_INITIALIZER;
-static base::LazyInstance<base::Lock>::Leaky
-    dtoa_lock_1 = LAZY_INSTANCE_INITIALIZER;
-
-/*
- * This define and the code below is to trigger thread-safe behavior
- * in dtoa.cc, per this comment from the file:
- *
- * #define MULTIPLE_THREADS if the system offers preemptively scheduled
- *	multiple threads.  In this case, you must provide (or suitably
- *	#define) two locks, acquired by ACQUIRE_DTOA_LOCK(n) and freed
- *	by FREE_DTOA_LOCK(n) for n = 0 or 1.  (The second lock, accessed
- *	in pow5mult, ensures lazy evaluation of only one copy of high
- *	powers of 5; omitting this lock would introduce a small
- *	probability of wasting memory, but would otherwise be harmless.)
- *	You must also invoke freedtoa(s) to free the value s returned by
- *	dtoa.  You may do so whether or not MULTIPLE_THREADS is #defined.
- */
-#define MULTIPLE_THREADS
-
-inline static void ACQUIRE_DTOA_LOCK(size_t n) {
-  DCHECK(n < 2);
-  base::Lock* lock = n == 0 ? dtoa_lock_0.Pointer() : dtoa_lock_1.Pointer();
-  lock->Acquire();
-}
-
-inline static void FREE_DTOA_LOCK(size_t n) {
-  DCHECK(n < 2);
-  base::Lock* lock = n == 0 ? dtoa_lock_0.Pointer() : dtoa_lock_1.Pointer();
-  lock->Release();
-}
-
-#include "base/third_party/dmg_fp/dtoa.cc"
-
-#undef Bias  // Avoid windows jumbo build breakage.
-#undef Long  // To avoid breaking jni code in jumbo builds
diff --git a/base/third_party/dmg_fp/exp_length.patch b/base/third_party/dmg_fp/exp_length.patch
deleted file mode 100644
index 278ec17..0000000
--- a/base/third_party/dmg_fp/exp_length.patch
+++ /dev/null
@@ -1,18 +0,0 @@
-diff --git a/base/third_party/dmg_fp/dtoa.cc b/base/third_party/dmg_fp/dtoa.cc
-index c0a51c2..ab4e056 100644
---- a/base/third_party/dmg_fp/dtoa.cc
-+++ b/base/third_party/dmg_fp/dtoa.cc
-@@ -2674,8 +2674,11 @@ strtod
- 			if (c > '0' && c <= '9') {
- 				L = c - '0';
- 				s1 = s;
--				while((c = *++s) >= '0' && c <= '9')
--					L = 10*L + c - '0';
-+				while((c = *++s) >= '0' && c <= '9') {
-+					if (L < (INT_MAX - 10) / 10) {
-+						L = 10*L + (c - '0');
-+					}
-+				}
- 				if (s - s1 > 8 || L > 19999)
- 					/* Avoid confusion from exponents
- 					 * so large that e might overflow.
diff --git a/base/third_party/dmg_fp/g_fmt.cc b/base/third_party/dmg_fp/g_fmt.cc
deleted file mode 100644
index 67c9f57..0000000
--- a/base/third_party/dmg_fp/g_fmt.cc
+++ /dev/null
@@ -1,102 +0,0 @@
-/****************************************************************
- *
- * The author of this software is David M. Gay.
- *
- * Copyright (c) 1991, 1996 by Lucent Technologies.
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose without fee is hereby granted, provided that this entire notice
- * is included in all copies of any software which is or includes a copy
- * or modification of this software and in all copies of the supporting
- * documentation for such software.
- *
- * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
- * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
- * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
- * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
- *
- ***************************************************************/
-
-/* g_fmt(buf,x) stores the closest decimal approximation to x in buf;
- * it suffices to declare buf
- *	char buf[32];
- */
-
-#include "dmg_fp.h"
-
-namespace dmg_fp {
-
- char *
-g_fmt(char *b, double x)
-{
-	int i, k;
-	char *s;
-	int decpt, j, sign;
-	char *b0, *s0, *se;
-
-	b0 = b;
-#ifdef IGNORE_ZERO_SIGN
-	if (!x) {
-		*b++ = '0';
-		*b = 0;
-		goto done;
-		}
-#endif
-	s = s0 = dtoa(x, 0, 0, &decpt, &sign, &se);
-	if (sign)
-		*b++ = '-';
-	if (decpt == 9999) /* Infinity or Nan */ {
-		for(*b = *s++; *b++; *b = *s++) {}
-		goto done0;
-		}
-	if (decpt <= -4 || decpt > se - s + 5) {
-		*b++ = *s++;
-		if (*s) {
-			*b++ = '.';
-			for(*b = *s++; *b; *b = *s++)
-				b++;
-			}
-		*b++ = 'e';
-		/* sprintf(b, "%+.2d", decpt - 1); */
-		if (--decpt < 0) {
-			*b++ = '-';
-			decpt = -decpt;
-			}
-		else
-			*b++ = '+';
-		for(j = 2, k = 10; 10*k <= decpt; j++, k *= 10) {}
-		for(;;) {
-			i = decpt / k;
-			*b++ = (char)i + '0';
-			if (--j <= 0)
-				break;
-			decpt -= i*k;
-			decpt *= 10;
-			}
-		*b = 0;
-		}
-	else if (decpt <= 0) {
-		*b++ = '.';
-		for(; decpt < 0; decpt++)
-			*b++ = '0';
-		for(*b = *s++; *b++; *b = *s++) {}
-		}
-	else {
-		for(*b = *s++; *b; *b = *s++) {
-			b++;
-			if (--decpt == 0 && *s)
-				*b++ = '.';
-			}
-		for(; decpt > 0; decpt--)
-			*b++ = '0';
-		*b = 0;
-		}
- done0:
-	freedtoa(s0);
-#ifdef IGNORE_ZERO_SIGN
- done:
-#endif
-	return b0;
-	}
-
-}  // namespace dmg_fp
diff --git a/base/third_party/dmg_fp/gcc_64_bit.patch b/base/third_party/dmg_fp/gcc_64_bit.patch
deleted file mode 100644
index ab943c0..0000000
--- a/base/third_party/dmg_fp/gcc_64_bit.patch
+++ /dev/null
@@ -1,25 +0,0 @@
-Index: dtoa.cc
---- dtoa.cc    (old copy)
-+++ dtoa.cc    (working copy)
-@@ -183,8 +183,12 @@
- #define NO_HEX_FP
- 
- #ifndef Long
-+#if __LP64__
-+#define Long int
-+#else
- #define Long long
- #endif
-+#endif
- #ifndef ULong
- typedef unsigned Long ULong;
- #endif
-@@ -221,7 +225,7 @@ extern void *MALLOC(size_t);
- #ifndef PRIVATE_MEM
- #define PRIVATE_MEM 2304
- #endif
--#define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
-+#define PRIVATE_mem ((unsigned)((PRIVATE_MEM+sizeof(double)-1)/sizeof(double)))
- static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
- #endif
- 
diff --git a/base/third_party/dmg_fp/gcc_warnings.patch b/base/third_party/dmg_fp/gcc_warnings.patch
deleted file mode 100644
index 4262237..0000000
--- a/base/third_party/dmg_fp/gcc_warnings.patch
+++ /dev/null
@@ -1,126 +0,0 @@
-Index: dtoa.cc
---- dtoa.cc    (old copy)
-+++ dtoa.cc    (working copy)
-@@ -179,6 +179,9 @@
-  *	used for input more than STRTOD_DIGLIM digits long (default 40).
-  */
- 
-+#define IEEE_8087
-+#define NO_HEX_FP
-+
- #ifndef Long
- #define Long long
- #endif
-@@ -280,9 +283,7 @@
- #include "math.h"
- #endif
- 
--#ifdef __cplusplus
--extern "C" {
--#endif
-+namespace dmg_fp {
- 
- #ifndef CONST
- #ifdef KR_headers
-@@ -511,11 +512,9 @@
- 
- #define Kmax 7
- 
--#ifdef __cplusplus
--extern "C" double strtod(const char *s00, char **se);
--extern "C" char *dtoa(double d, int mode, int ndigits,
-+double strtod(const char *s00, char **se);
-+char *dtoa(double d, int mode, int ndigits,
- 			int *decpt, int *sign, char **rve);
--#endif
- 
-  struct
- Bigint {
-@@ -1527,7 +1526,7 @@
- #ifdef KR_headers
- 	(sp, t) char **sp, *t;
- #else
--	(CONST char **sp, char *t)
-+	(CONST char **sp, CONST char *t)
- #endif
- {
- 	int c, d;
-@@ -2234,7 +2234,7 @@ bigcomp
- 	nd = bc->nd;
- 	nd0 = bc->nd0;
- 	p5 = nd + bc->e0 - 1;
--	speccase = 0;
-+	dd = speccase = 0;
- #ifndef Sudden_Underflow
- 	if (rv->d == 0.) {	/* special case: value near underflow-to-zero */
- 				/* threshold was rounded to zero */
-@@ -3431,7 +3430,7 @@
- 
- 	j = sizeof(ULong);
- 	for(k = 0;
--		sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= i;
-+		sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (size_t)i;
- 		j <<= 1)
- 			k++;
- 	r = (int*)Balloc(k);
-@@ -3447,7 +3446,7 @@
- #ifdef KR_headers
- nrv_alloc(s, rve, n) char *s, **rve; int n;
- #else
--nrv_alloc(char *s, char **rve, int n)
-+nrv_alloc(CONST char *s, char **rve, int n)
- #endif
- {
- 	char *rv, *t;
-@@ -4202,6 +4201,5 @@
- 		*rve = s;
- 	return s0;
- 	}
--#ifdef __cplusplus
--}
--#endif
-+
-+}  // namespace dmg_fp
-Index: g_fmt.cc
---- g_fmt.cc   (old copy)
-+++ g_fmt.cc   (new copy)
-@@ -46,14 +46,14 @@ g_fmt(register char *b, double x)
- 	if (sign)
- 		*b++ = '-';
- 	if (decpt == 9999) /* Infinity or Nan */ {
--		while(*b++ = *s++);
-+		while((*b++ = *s++));
- 		goto done0;
- 		}
- 	if (decpt <= -4 || decpt > se - s + 5) {
- 		*b++ = *s++;
- 		if (*s) {
- 			*b++ = '.';
--			while(*b = *s++)
-+			while((*b = *s++))
- 				b++;
- 			}
- 		*b++ = 'e';
-@@ -79,10 +79,10 @@ g_fmt(register char *b, double x)
- 		*b++ = '.';
- 		for(; decpt < 0; decpt++)
- 			*b++ = '0';
--		while(*b++ = *s++);
-+		while((*b++ = *s++));
- 		}
- 	else {
--		while(*b = *s++) {
-+		while((*b = *s++)) {
- 			b++;
- 			if (--decpt == 0 && *s)
- 				*b++ = '.';
-@@ -93,7 +93,9 @@ g_fmt(register char *b, double x)
- 		}
-  done0:
- 	freedtoa(s0);
-+#ifdef IGNORE_ZERO_SIGN
-  done:
-+#endif
- 	return b0;
- 	}
- 
diff --git a/base/third_party/dmg_fp/mac_wextra.patch b/base/third_party/dmg_fp/mac_wextra.patch
deleted file mode 100644
index 15340f2..0000000
--- a/base/third_party/dmg_fp/mac_wextra.patch
+++ /dev/null
@@ -1,53 +0,0 @@
-Index: g_fmt.cc
-===================================================================
---- g_fmt.cc	(revision 49784)
-+++ g_fmt.cc	(working copy)
-@@ -46,7 +46,7 @@
- 	if (sign)
- 		*b++ = '-';
- 	if (decpt == 9999) /* Infinity or Nan */ {
--		while((*b++ = *s++));
-+		while((*b++ = *s++)) {}
- 		goto done0;
- 		}
- 	if (decpt <= -4 || decpt > se - s + 5) {
-@@ -64,7 +64,7 @@
- 			}
- 		else
- 			*b++ = '+';
--		for(j = 2, k = 10; 10*k <= decpt; j++, k *= 10);
-+		for(j = 2, k = 10; 10*k <= decpt; j++, k *= 10) {}
- 		for(;;) {
- 			i = decpt / k;
- 			*b++ = i + '0';
-@@ -79,7 +79,7 @@
- 		*b++ = '.';
- 		for(; decpt < 0; decpt++)
- 			*b++ = '0';
--		while((*b++ = *s++));
-+		while((*b++ = *s++)) {}
- 		}
- 	else {
- 		while((*b = *s++)) {
-Index: dtoa.cc
-===================================================================
---- dtoa.cc	(revision 49784)
-+++ dtoa.cc	(working copy)
-@@ -3863,7 +3863,7 @@
- 					if (dval(&u) > 0.5 + dval(&eps))
- 						goto bump_up;
- 					else if (dval(&u) < 0.5 - dval(&eps)) {
--						while(*--s == '0');
-+						while(*--s == '0') {}
- 						s++;
- 						goto ret1;
- 						}
-@@ -4176,7 +4176,7 @@
- #ifdef Honor_FLT_ROUNDS
-  trimzeros:
- #endif
--		while(*--s == '0');
-+		while(*--s == '0') {}
- 		s++;
- 		}
-  ret:
diff --git a/base/third_party/dmg_fp/msvc_warnings.patch b/base/third_party/dmg_fp/msvc_warnings.patch
deleted file mode 100644
index 22e89cd..0000000
--- a/base/third_party/dmg_fp/msvc_warnings.patch
+++ /dev/null
@@ -1,419 +0,0 @@
-diff --git a/base/third_party/dmg_fp/dtoa.cc b/base/third_party/dmg_fp/dtoa.cc
-index 3312fa4..502c16c 100644
---- a/base/third_party/dmg_fp/dtoa.cc
-+++ b/base/third_party/dmg_fp/dtoa.cc
-@@ -548,8 +548,10 @@ Balloc
- 	ACQUIRE_DTOA_LOCK(0);
- 	/* The k > Kmax case does not need ACQUIRE_DTOA_LOCK(0), */
- 	/* but this case seems very unlikely. */
--	if (k <= Kmax && (rv = freelist[k]))
-+	if (k <= Kmax && freelist[k]) {
-+		rv = freelist[k];
- 		freelist[k] = rv->next;
-+		}
- 	else {
- 		x = 1 << k;
- #ifdef Omit_Private_Memory
-@@ -650,7 +652,7 @@ multadd
- 			Bfree(b);
- 			b = b1;
- 			}
--		b->x[wds++] = carry;
-+		b->x[wds++] = (ULong)carry;
- 		b->wds = wds;
- 		}
- 	return b;
-@@ -834,7 +836,8 @@ mult
- 	xc0 = c->x;
- #ifdef ULLong
- 	for(; xb < xbe; xc0++) {
--		if ((y = *xb++)) {
-+		y = *xb++;
-+		if (y) {
- 			x = xa;
- 			xc = xc0;
- 			carry = 0;
-@@ -844,7 +847,7 @@ mult
- 				*xc++ = z & FFFFFFFF;
- 				}
- 				while(x < xae);
--			*xc = carry;
-+			*xc = (ULong)carry;
- 			}
- 		}
- #else
-@@ -916,16 +919,19 @@ pow5mult
- 	int i;
- 	static int p05[3] = { 5, 25, 125 };
- 
--	if ((i = k & 3))
-+	i = k & 3;
-+	if (i)
- 		b = multadd(b, p05[i-1], 0);
- 
- 	if (!(k >>= 2))
- 		return b;
--	if (!(p5 = p5s)) {
-+	p5 = p5s;
-+	if (!p5) {
- 		/* first time */
- #ifdef MULTIPLE_THREADS
- 		ACQUIRE_DTOA_LOCK(1);
--		if (!(p5 = p5s)) {
-+		p5 = p5s;
-+		if (!p5) {
- 			p5 = p5s = i2b(625);
- 			p5->next = 0;
- 			}
-@@ -943,10 +949,12 @@ pow5mult
- 			}
- 		if (!(k >>= 1))
- 			break;
--		if (!(p51 = p5->next)) {
-+		p51 = p5->next;
-+		if (!p51) {
- #ifdef MULTIPLE_THREADS
- 			ACQUIRE_DTOA_LOCK(1);
--			if (!(p51 = p5->next)) {
-+			p51 = p5->next;
-+			if (!p51) {
- 				p51 = p5->next = mult(p5,p5);
- 				p51->next = 0;
- 				}
-@@ -997,7 +1005,8 @@ lshift
- 			z = *x++ >> k1;
- 			}
- 			while(x < xe);
--		if ((*x1 = z))
-+		*x1 = z;
-+		if (*x1)
- 			++n1;
- 		}
- #else
-@@ -1299,21 +1308,25 @@ d2b
- 	z |= Exp_msk11;
- #endif
- #else
--	if ((de = (int)(d0 >> Exp_shift)))
-+	de = (int)(d0 >> Exp_shift);
-+	if (de)
- 		z |= Exp_msk1;
- #endif
- #ifdef Pack_32
--	if ((y = d1)) {
--		if ((k = lo0bits(&y))) {
-+	y = d1;
-+	if (y) {
-+		k = lo0bits(&y);
-+		if (k) {
- 			x[0] = y | z << (32 - k);
- 			z >>= k;
- 			}
- 		else
- 			x[0] = y;
-+		x[1] = z;
-+		b->wds = x[1] ? 2 : 1;
- #ifndef Sudden_Underflow
--		i =
-+		i = b->wds;
- #endif
--		    b->wds = (x[1] = z) ? 2 : 1;
- 		}
- 	else {
- 		k = lo0bits(&z);
-@@ -1498,7 +1511,7 @@ htinit(unsigned char *h, unsigned char *s, int inc)
- {
- 	int i, j;
- 	for(i = 0; (j = s[i]) !=0; i++)
--		h[j] = i + inc;
-+		h[j] = (unsigned char)(i + inc);
- 	}
- 
-  static void
-@@ -1536,7 +1549,7 @@ match
- 	int c, d;
- 	CONST char *s = *sp;
- 
--	while((d = *t++)) {
-+	for(d = *t++; d; d = *t++) {
- 		if ((c = *++s) >= 'A' && c <= 'Z')
- 			c += 'a' - 'A';
- 		if (c != d)
-@@ -1566,12 +1579,13 @@ hexnan
- 	udx0 = 1;
- 	s = *sp;
- 	/* allow optional initial 0x or 0X */
--	while((c = *(CONST unsigned char*)(s+1)) && c <= ' ')
-+	for(c = *(CONST unsigned char*)(s+1); c && c <= ' '; c = *(CONST unsigned char*)(s+1))
- 		++s;
- 	if (s[1] == '0' && (s[2] == 'x' || s[2] == 'X'))
- 		s += 2;
--	while((c = *(CONST unsigned char*)++s)) {
--		if ((c1 = hexdig[c]))
-+	for(c = *(CONST unsigned char*)++s; c; c = *(CONST unsigned char*)++s) {
-+		c1 = hexdig[c];
-+		if (c1)
- 			c  = c1 & 0xf;
- 		else if (c <= ' ') {
- 			if (udx0 && havedig) {
-@@ -1594,7 +1608,8 @@ hexnan
- 					*sp = s + 1;
- 					break;
- 					}
--				} while((c = *++s));
-+				c = *++s;
-+				} while(c);
- 			break;
- 			}
- #endif
-@@ -2328,7 +2343,8 @@ bigcomp
- 	/* Now b/d = exactly half-way between the two floating-point values */
- 	/* on either side of the input string.  Compute first digit of b/d. */
- 
--	if (!(dig = quorem(b,d))) {
-+	dig = quorem(b,d);
-+	if (!dig) {
- 		b = multadd(b, 10, 0);	/* very unlikely */
- 		dig = quorem(b,d);
- 		}
-@@ -2336,7 +2352,8 @@ bigcomp
- 	/* Compare b/d with s0 */
- 
- 	for(i = 0; i < nd0; ) {
--		if ((dd = s0[i++] - '0' - dig))
-+		dd = s0[i++] - '0' - dig;
-+		if (dd)
- 			goto ret;
- 		if (!b->x[0] && b->wds == 1) {
- 			if (i < nd)
-@@ -2347,7 +2364,8 @@ bigcomp
- 		dig = quorem(b,d);
- 		}
- 	for(j = bc->dp1; i++ < nd;) {
--		if ((dd = s0[j++] - '0' - dig))
-+		dd = s0[j++] - '0' - dig;
-+		if (dd)
- 			goto ret;
- 		if (!b->x[0] && b->wds == 1) {
- 			if (i < nd)
-@@ -2747,7 +2765,8 @@ strtod
- 	/* Get starting approximation = rv * 10**e1 */
- 
- 	if (e1 > 0) {
--		if ((i = e1 & 15))
-+		i = e1 & 15;
-+		if (i)
- 			dval(&rv) *= tens[i];
- 		if (e1 &= ~15) {
- 			if (e1 > DBL_MAX_10_EXP) {
-@@ -2805,7 +2824,8 @@ strtod
- 		}
- 	else if (e1 < 0) {
- 		e1 = -e1;
--		if ((i = e1 & 15))
-+		i = e1 & 15;
-+		if (i)
- 			dval(&rv) /= tens[i];
- 		if (e1 >>= 4) {
- 			if (e1 >= 1 << n_bigtens)
-@@ -3283,7 +3303,7 @@ strtod
- #ifdef Avoid_Underflow
- 			if (bc.scale && y <= 2*P*Exp_msk1) {
- 				if (aadj <= 0x7fffffff) {
--					if ((z = aadj) <= 0)
-+					if ((z = (ULong)aadj) <= 0)
- 						z = 1;
- 					aadj = z;
- 					aadj1 = bc.dsign ? aadj : -aadj;
-@@ -3456,7 +3476,7 @@ nrv_alloc(CONST char *s, char **rve, int n)
- 	char *rv, *t;
- 
- 	t = rv = rv_alloc(n);
--	while((*t = *s++)) t++;
-+	for(*t = *s++; *t; *t = *s++) t++;
- 	if (rve)
- 		*rve = t;
- 	return rv;
-@@ -3569,7 +3589,7 @@ dtoa
- 	int denorm;
- 	ULong x;
- #endif
--	Bigint *b, *b1, *delta, *mlo, *mhi, *S;
-+	Bigint *b, *b1, *delta, *mlo = NULL, *mhi, *S;
- 	U d2, eps, u;
- 	double ds;
- 	char *s, *s0;
-@@ -3645,10 +3665,9 @@ dtoa
- #endif
- 
- 	b = d2b(&u, &be, &bbits);
--#ifdef Sudden_Underflow
- 	i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
--#else
--	if ((i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1)))) {
-+#ifndef Sudden_Underflow
-+	if (i) {
- #endif
- 		dval(&d2) = dval(&u);
- 		word0(&d2) &= Frac_mask1;
-@@ -3803,13 +3822,16 @@ dtoa
- 					}
- 			dval(&u) /= ds;
- 			}
--		else if ((j1 = -k)) {
--			dval(&u) *= tens[j1 & 0xf];
--			for(j = j1 >> 4; j; j >>= 1, i++)
--				if (j & 1) {
--					ieps++;
--					dval(&u) *= bigtens[i];
--					}
-+		else {
-+			j1 = -k;
-+			if (j1) {
-+				dval(&u) *= tens[j1 & 0xf];
-+				for(j = j1 >> 4; j; j >>= 1, i++)
-+					if (j & 1) {
-+						ieps++;
-+						dval(&u) *= bigtens[i];
-+						}
-+				}
- 			}
- 		if (k_check && dval(&u) < 1. && ilim > 0) {
- 			if (ilim1 <= 0)
-@@ -3837,9 +3859,9 @@ dtoa
- 			 */
- 			dval(&eps) = 0.5/tens[ilim-1] - dval(&eps);
- 			for(i = 0;;) {
--				L = dval(&u);
-+				L = (long)dval(&u);
- 				dval(&u) -= L;
--				*s++ = '0' + (int)L;
-+				*s++ = '0' + (char)L;
- 				if (dval(&u) < dval(&eps))
- 					goto ret1;
- 				if (1. - dval(&u) < dval(&eps))
-@@ -3858,7 +3880,7 @@ dtoa
- 				L = (Long)(dval(&u));
- 				if (!(dval(&u) -= L))
- 					ilim = i;
--				*s++ = '0' + (int)L;
-+				*s++ = '0' + (char)L;
- 				if (i == ilim) {
- 					if (dval(&u) > 0.5 + dval(&eps))
- 						goto bump_up;
-@@ -3901,7 +3923,7 @@ dtoa
- 				dval(&u) += ds;
- 				}
- #endif
--			*s++ = '0' + (int)L;
-+			*s++ = '0' + (char)L;
- 			if (!dval(&u)) {
- #ifdef SET_INEXACT
- 				inexact = 0;
-@@ -3964,7 +3986,8 @@ dtoa
- 				Bfree(b);
- 				b = b1;
- 				}
--			if ((j = b5 - m5))
-+			j = b5 - m5;
-+			if (j)
- 				b = pow5mult(b, j);
- 			}
- 		else
-@@ -4002,7 +4025,8 @@ dtoa
- 	 * can do shifts and ors to compute the numerator for q.
- 	 */
- #ifdef Pack_32
--	if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f))
-+	i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f;
-+	if (i)
- 		i = 32 - i;
- #define iInc 28
- #else
-@@ -4077,7 +4101,7 @@ dtoa
- 				else if (!b->x[0] && b->wds <= 1)
- 					inexact = 0;
- #endif
--				*s++ = dig;
-+				*s++ = (char)dig;
- 				goto ret;
- 				}
- #endif
-@@ -4107,7 +4131,7 @@ dtoa
- 						goto round_9_up;
- 					}
-  accept_dig:
--				*s++ = dig;
-+				*s++ = (char)dig;
- 				goto ret;
- 				}
- 			if (j1 > 0) {
-@@ -4120,13 +4144,13 @@ dtoa
- 					*s++ = '9';
- 					goto roundoff;
- 					}
--				*s++ = dig + 1;
-+				*s++ = (char)dig + 1;
- 				goto ret;
- 				}
- #ifdef Honor_FLT_ROUNDS
-  keep_dig:
- #endif
--			*s++ = dig;
-+			*s++ = (char)dig;
- 			if (i == ilim)
- 				break;
- 			b = multadd(b, 10, 0);
-@@ -4140,7 +4164,8 @@ dtoa
- 		}
- 	else
- 		for(i = 1;; i++) {
--			*s++ = dig = quorem(b,S) + '0';
-+			dig = quorem(b,S) + '0';
-+			*s++ = (char)dig;
- 			if (!b->x[0] && b->wds <= 1) {
- #ifdef SET_INEXACT
- 				inexact = 0;
-diff --git a/base/third_party/dmg_fp/g_fmt.cc b/base/third_party/dmg_fp/g_fmt.cc
-index d864eb7..bfa358d 100644
---- a/base/third_party/dmg_fp/g_fmt.cc
-+++ b/base/third_party/dmg_fp/g_fmt.cc
-@@ -46,14 +46,14 @@ g_fmt(register char *b, double x)
- 	if (sign)
- 		*b++ = '-';
- 	if (decpt == 9999) /* Infinity or Nan */ {
--		while((*b++ = *s++)) {}
-+		for(*b = *s++; *b++; *b = *s++) {}
- 		goto done0;
- 		}
- 	if (decpt <= -4 || decpt > se - s + 5) {
- 		*b++ = *s++;
- 		if (*s) {
- 			*b++ = '.';
--			while((*b = *s++))
-+			for(*b = *s++; *b; *b = *s++)
- 				b++;
- 			}
- 		*b++ = 'e';
-@@ -67,7 +67,7 @@ g_fmt(register char *b, double x)
- 		for(j = 2, k = 10; 10*k <= decpt; j++, k *= 10) {}
- 		for(;;) {
- 			i = decpt / k;
--			*b++ = i + '0';
-+			*b++ = (char)i + '0';
- 			if (--j <= 0)
- 				break;
- 			decpt -= i*k;
-@@ -79,10 +79,10 @@ g_fmt(register char *b, double x)
- 		*b++ = '.';
- 		for(; decpt < 0; decpt++)
- 			*b++ = '0';
--		while((*b++ = *s++)) {}
-+		for(*b = *s++; *b++; *b = *s++) {}
- 		}
- 	else {
--		while((*b = *s++)) {
-+		for(*b = *s++; *b; *b = *s++) {
- 			b++;
- 			if (--decpt == 0 && *s)
- 				*b++ = '.';
diff --git a/base/third_party/libevent/ChangeLog b/base/third_party/libevent/ChangeLog
deleted file mode 100644
index 893b087..0000000
--- a/base/third_party/libevent/ChangeLog
+++ /dev/null
@@ -1,253 +0,0 @@
-Changes in 1.4.15-stable (5 January 2015)
-
- o Avoid integer overflow bugs in evbuffer_add() and related functions.  See CVE-2014-6272 advisory for more information. (d49bc0e88b81a5812116074dc007f1db0ca1eecd)
-
- o Pass flags to fcntl(F_SETFL) as int, not long (b3d0382)
- o Backport and tweak the LICENSE file for 1.4 (8a5ebd3)
- o set close-on-exec bit for filedescriptors created by dns subsystem (9985231 Ralf Schmitt)
- o Replace unused case of FD_CLOSEONEXEC with a proper null statement. (44f04a2)
- o Fix kqueue correctness test on x84_64 (1c25b07)
- o Avoid deadlock when activating signals. (e0e6958)
- o Backport doc fix for evhttp_bind_socket. (95b71d0 Marco)
- o Fix an issue with forking and signal socketpairs in select/poll backends (f0ff765)
- o Fix compilation on Visual Studio 2010 (53c47c2 VDm)
- o Defensive programming to prevent (hopefully impossible) stack-stomping (2d8cf0b)
- o Check for POLLERR, POLLHUP and POLLNVAL for Solaris event ports (353b4ac Trond Norbye)
- o Fix a bug that could allow dns requests with duplicate tx ids (e50ba5b)
- o Avoid truncating huge values for content-length (1d6e30e)
- o Take generated files out of git; add correct m4 magic for libtool to auto* files (7cf794b)
- o Prefer autoregen -ivf to manual autogen.sh (823d9be)
-
-
-Changes in 1.4.14b-stable
- o Set the VERSION_INFO correctly for 1.4.14
-
-
-Changes in 1.4.14-stable
- o Add a .gitignore file for the 1.4 branch. (d014edb)
- o Backport evbuffer_readln(). (b04cc60 Nicholas Marriott)
- o Make the evbuffer_readln backport follow the current API (c545485)
- o Valgrind fix: Clear struct kevent before checking for OSX bug. (5713d5d William Ahern)
- o Fix a crash when reading badly formatted resolve.conf (5b10d00 Yasuoka Masahiko)
- o Fix memory-leak of signal handler array with kqueue. [backport] (01f3775)
- o Update sample/signal-test.c to use newer APIs and not leak. (891765c Evan Jones)
- o Correct all versions in 1.4 branch (ac0d213)
- o Make evutil_make_socket_nonblocking() leave any other flags alone. (81c26ba Jardel Weyrich)
- o Adjusted fcntl() retval comparison on evutil_make_socket_nonblocking(). (5f2e250 Jardel Weyrich)
- o Correct a debug message in evhttp_parse_request_line (35df59e)
- o Merge branch 'readln-backport' into patches-1.4 (8771d5b)
- o Do not send an HTTP error when we've already closed or responded. (4fd2dd9 Pavel Plesov)
- o Re-add event_siglcb; some old code _was_ still using it. :( (bd03d06)
- o Make Libevent 1.4 build on win32 with Unicode enabled. (bce58d6 Brodie Thiesfield)
- o Distribute nmake makefile for 1.4 (20d706d)
- o do not fail while sending on http connections the client closed. (5c8b446)
- o make evhttp_send() safe against terminated connections, too (01ea0c5)
- o Fix a free(NULL) in min_heap.h (2458934)
- o Fix memory leak when setting up priorities; reported by Alexander Drozdov (cb1a722)
- o Clean up properly when adding a signal handler fails. (ae6ece0 Gilad Benjamini)
- o Do not abort HTTP requests missing a reason string. (29d7b32 Pierre Phaneuf)
- o Fix compile warning in http.c (906d573)
- o Define _REENTRANT as needed on Solaris, elsewhere (6cbea13)
-
-
-Changes in 1.4.13-stable:
- o If the kernel tells us that there are a negative number of bytes to read from a socket, do not believe it.  Fixes bug 2841177; found by Alexander Pronchenkov.
- o Do not allocate the maximum event queue and fd array for the epoll backend at startup.  Instead, start out accepting 32 events at a time, and double the queue's size when it seems that the OS is generating events faster than we're requesting them.  Saves up to 512K per epoll-based event_base.  Resolves bug 2839240.
- o Fix compilation on Android, which forgot to define fd_mask in its sys/select.h
- o Do not drop data from evbuffer when out of memory; reported by Jacek Masiulaniec
- o Rename our replacement compat/sys/_time.h header to avoid build a conflict on HPUX; reported by Kathryn Hogg.
- o Build kqueue.c correctly on GNU/kFreeBSD platforms. Patch pulled upstream from Debian.
- o Fix a problem with excessive memory allocation when using multiple event priorities.
- o When running set[ug]id, don't check the environment. Based on a patch from OpenBSD.
-
-
-Changes in 1.4.12-stable:
- o Try to contain degree of failure when running on a win32 version so heavily firewalled that we can't fake a socketpair.
- o Fix an obscure timing-dependent, allocator-dependent crash in the evdns code.
- o Use __VA_ARGS__ syntax for varargs macros in event_rpcgen when compiler is not GCC.
- o Activate fd events in a pseudorandom order with O(N) backends, so that we don't systematically favor low fds (select) or earlier-added fds (poll, win32).
- o Fix another pair of fencepost bugs in epoll.c.  [Patch from Adam Langley.]
- o Do not break evdns connections to nameservers when our IP changes.
- o Set truncated flag correctly in evdns server replies.
- o Disable strict aliasing with GCC: our code is not compliant with it.
-
-Changes in 1.4.11-stable:
- o Fix a bug when removing a timeout from the heap. [Patch from Marko Kreen]
- o Remove the limit on size of HTTP headers by removing static buffers.
- o Fix a nasty dangling pointer bug in epoll.c that could occur after epoll_recalc(). [Patch from Kevin Springborn]
- o Distribute Win32-Code/event-config.h, not ./event-config.h
-
-Changes in 1.4.10-stable:
- o clean up buffered http connection data on reset; reported by Brian O'Kelley
- o bug fix and potential race condition in signal handling; from Alexander Drozdov
- o rename the Solaris event ports backend to evport
- o support compilation on Haiku
- o fix signal processing when a signal callback delivers a signal; from Alexander Drozdov
- o const-ify some arguments to evdns functions.
- o off-by-one error in epoll_recalc; reported by Victor Goya
- o include Doxyfile in tar ball; from Jeff Garzik
- o correctly parse queries with encoded \r, \n or + characters
-
-Changes in 1.4.9-stable:
- o event_add would not return error for some backends; from Dean McNamee
- o Clear the timer cache on entering the event loop; reported by Victor Chang
- o Only bind the socket on connect when a local address has been provided; reported by Alejo Sanchez
- o Allow setting of local port for evhttp connections to support millions of connections from a single system; from Richard Jones.
- o Clear the timer cache when leaving the event loop; reported by Robin Haberkorn
- o Fix a typo in setting the global event base; reported by lance.
- o Fix a memory leak when reading multi-line headers
- o Fix a memory leak by not running explicit close detection for server connections
-
-Changes in 1.4.8-stable:
- o Match the query in DNS replies to the query in the request; from Vsevolod Stakhov.
- o Fix a merge problem in which name_from_addr returned pointers to the stack; found by Jiang Hong.
- o Do not remove Accept-Encoding header
-	
-Changes in 1.4.7-stable:
- o Fix a bug where headers arriving in multiple packets were not parsed; fix from Jiang Hong; test by me.
-	
-Changes in 1.4.6-stable:
- o evutil.h now includes <stdarg.h> directly
- o switch all uses of [v]snprintf over to evutil
- o Correct handling of trailing headers in chunked replies; from Scott Lamb.
- o Support multi-line HTTP headers; based on a patch from Moshe Litvin
- o Reject negative Content-Length headers; anonymous bug report
- o Detect CLOCK_MONOTONIC at runtime for evdns; anonymous bug report	
- o Fix a bug where deleting signals with the kqueue backend would cause subsequent adds to fail
- o Support multiple events listening on the same signal; make signals regular events that go on the same event queue; problem report by Alexander Drozdov.
- o Deal with evbuffer_read() returning -1 on EINTR|EAGAIN; from Adam Langley.
- o Fix a bug in which the DNS server would incorrectly set the type of a cname reply to a.
- o Fix a bug where setting the timeout on a bufferevent would take not effect if the event was already pending.
- o Fix a memory leak when using signals for some event bases; reported by Alexander Drozdov.
- o Add libevent.vcproj file to distribution to help with Windows build.
- o Fix a problem with epoll() and reinit; problem report by Alexander Drozdov.	
- o Fix off-by-one errors in devpoll; from Ian Bell
- o Make event_add not change any state if it fails; reported by Ian Bell.
- o Do not warn on accept when errno is either EAGAIN or EINTR
-
-Changes in 1.4.5-stable:
- o Fix connection keep-alive behavior for HTTP/1.0
- o Fix use of freed memory in event_reinit; pointed out by Peter Postma
- o Constify struct timeval * where possible; pointed out by Forest Wilkinson
- o allow min_heap_erase to be called on removed members; from liusifan.
- o Rename INPUT and OUTPUT to EVRPC_INPUT and EVRPC_OUTPUT.  Retain INPUT/OUTPUT aliases on on-win32 platforms for backwards compatibility.
- o Do not use SO_REUSEADDR when connecting
- o Fix Windows build
- o Fix a bug in event_rpcgen when generated fixed-sized entries
-
-Changes in 1.4.4-stable:
- o Correct the documentation on buffer printf functions.
- o Don't warn on unimplemented epoll_create(): this isn't a problem, just a reason to fall back to poll or select.
- o Correctly handle timeouts larger than 35 minutes on Linux with epoll.c.  This is probably a kernel defect, but we'll have to support old kernels anyway even if it gets fixed.
- o Fix a potential stack corruption bug in tagging on 64-bit CPUs.
- o expose bufferevent_setwatermark via header files and fix high watermark on read
- o fix a bug in bufferevent read water marks and add a test for them
- o introduce bufferevent_setcb and bufferevent_setfd to allow better manipulation of bufferevents
- o use libevent's internal timercmp on all platforms, to avoid bugs on old platforms where timercmp(a,b,<=) is buggy.
- o reduce system calls for getting current time by caching it.
- o fix evhttp_bind_socket() so that multiple sockets can be bound by the same http server.
- o Build test directory correctly with CPPFLAGS set.
- o Fix build under Visual C++ 2005.
- o Expose evhttp_accept_socket() API.
- o Merge windows gettimeofday() replacement into a new evutil_gettimeofday() function.
- o Fix autoconf script behavior on IRIX.
- o Make sure winsock2.h include always comes before windows.h include.
-
-Changes in 1.4.3-stable:
- o include Content-Length in reply for HTTP/1.0 requests with keep-alive
- o Patch from Tani Hosokawa: make some functions in http.c threadsafe.
- o Do not free the kqop file descriptor in other processes, also allow it to be 0; from Andrei Nigmatulin
- o make event_rpcgen.py generate code include event-config.h; reported by Sam Banks.
- o make event methods static so that they are not exported; from Andrei Nigmatulin
- o make RPC replies use application/octet-stream as mime type
- o do not delete uninitialized timeout event in evdns
-
-Changes in 1.4.2-rc:
- o remove pending timeouts on event_base_free()
- o also check EAGAIN for Solaris' event ports; from W.C.A. Wijngaards
- o devpoll and evport need reinit; tested by W.C.A Wijngaards
- o event_base_get_method; from Springande Ulv
- o Send CRLF after each chunk in HTTP output, for compliance with RFC2626.  Patch from "propanbutan".  Fixes bug 1894184.
- o Add a int64_t parsing function, with unit tests, so we can apply Scott Lamb's fix to allow large HTTP values.
- o Use a 64-bit field to hold HTTP content-lengths.  Patch from Scott Lamb.
- o Allow regression code to build even without Python installed
- o remove NDEBUG ifdefs from evdns.c
- o update documentation of event_loop and event_base_loop; from Tani Hosokawa.
- o detect integer types properly on platforms without stdint.h
- o Remove "AM_MAINTAINER_MODE" declaration in configure.in: now makefiles and configure should get re-generated automatically when Makefile.am or configure.in chanes.
- o do not insert event into list when evsel->add fails
-
-Changes in 1.4.1-beta:
- o free minheap on event_base_free(); from Christopher Layne
- o debug cleanups in signal.c; from Christopher Layne
- o provide event_base_new() that does not set the current_base global
- o bufferevent_write now uses a const source argument; report from Charles Kerr
- o better documentation for event_base_loopexit; from Scott Lamb.
- o Make kqueue have the same behavior as other backends when a signal is caught between event_add() and event_loop().  Previously, it would catch and ignore such signals.
- o Make kqueue restore signal handlers correctly when event_del() is called.
- o provide event_reinit() to reintialize an event_base after fork
- o small improvements to evhttp documentation
- o always generate Date and Content-Length headers for HTTP/1.1 replies
- o set the correct event base for HTTP close events
- o New function, event_{base_}loopbreak.  Like event_loopexit, it makes an event loop stop executing and return.  Unlike event_loopexit, it keeps subsequent pending events from getting executed.  Patch from Scott Lamb
- o Removed obsoleted recalc code
- o pull setters/getters out of RPC structures into a base class to which we just need to store a pointer; this reduces the memory footprint of these structures.
- o fix a bug with event_rpcgen for integers
- o move EV_PERSIST handling out of the event backends
- o support for 32-bit tag numbers in rpc structures; this is wire compatible, but changes the API slightly.
- o prefix {encode,decode}_tag functions with evtag to avoid collisions
- o Correctly handle DNS replies with no answers set (Fixes bug 1846282)
- o The configure script now takes an --enable-gcc-warnigns option that turns on many optional gcc warnings.  (Nick has been building with these for a while, but they might be useful to other developers.)
- o When building with GCC, use the "format" attribute to verify type correctness of calls to printf-like functions.
- o removed linger from http server socket; reported by Ilya Martynov
- o allow \r or \n individually to separate HTTP headers instead of the standard "\r\n"; from Charles Kerr.
- o demote most http warnings to debug messages
- o Fix Solaris compilation; from Magne Mahre
- o Add a "Date" header to HTTP responses, as required by HTTP 1.1.
- o Support specifying the local address of an evhttp_connection using set_local_address
- o Fix a memory leak in which failed HTTP connections would not free the request object
- o Make adding of array members in event_rpcgen more efficient, but doubling memory allocation
- o Fix a memory leak in the DNS server
- o Fix compilation when DNS_USE_OPENSSL_FOR_ID is enabled
- o Fix buffer size and string generation in evdns_resolve_reverse_ipv6().
- o Respond to nonstandard DNS queries with "NOTIMPL" rather than by ignoring them.
- o In DNS responses, the CD flag should be preserved, not the TC flag.
- o Fix http.c to compile properly with USE_DEBUG; from Christopher Layne
- o Handle NULL timeouts correctly on Solaris; from Trond Norbye
- o Recalculate pending events properly when reallocating event array on Solaris; from Trond Norbye
- o Add Doxygen documentation to header files; from Mark Heily
- o Add a evdns_set_transaction_id_fn() function to override the default
-   transaction ID generation code.
- o Add an evutil module (with header evutil.h) to implement our standard cross-platform hacks, on the theory that somebody else would like to use them too.
- o Fix signals implementation on windows.
- o Fix http module on windows to close sockets properly.
- o Make autogen.sh script run correctly on systems where /bin/sh isn't bash. (Patch from Trond Norbye, rewritten by Hagne Mahre and then Hannah Schroeter.)
- o Skip calling gettime() in timeout_process if we are not in fact waiting for any events. (Patch from Trond Norbye)
- o Make test subdirectory compile under mingw.
- o Fix win32 buffer.c behavior so that it is correct for sockets (which do not like ReadFile and WriteFile).
- o Make the test.sh script run unit tests for the evpoll method.
- o Make the entire evdns.h header enclosed in "extern C" as appropriate.
- o Fix implementation of strsep on platforms that lack it
- o Fix implementation of getaddrinfo on platforms that lack it; mainly, this will make Windows http.c work better.  Original patch by Lubomir Marinov.
- o Fix evport implementation: port_disassociate called on unassociated events resulting in bogus errors; more efficient memory management; from Trond Norbye and Prakash Sangappa
- o support for hooks on rpc input and output; can be used to implement rpc independent processing such as compression or authentication.
- o use a min heap instead of a red-black tree for timeouts; as a result finding the min is a O(1) operation now; from Maxim Yegorushkin
- o associate an event base with an rpc pool
- o added two additional libraries: libevent_core and libevent_extra in addition to the regular libevent.  libevent_core contains only the event core whereas libevent_extra contains dns, http and rpc support
- o Begin using libtool's library versioning support correctly.  If we don't mess up, this will more or less guarantee binaries linked against old versions of libevent continue working when we make changes to libevent that do not break backward compatibility.
- o Fix evhttp.h compilation when TAILQ_ENTRY is not defined.
- o Small code cleanups in epoll_dispatch().
- o Increase the maximum number of addresses read from a packet in evdns to 32.
- o Remove support for the rtsig method: it hasn't compiled for a while, and nobody seems to miss it very much.  Let us know if there's a good reason to put it back in.
- o Rename the "class" field in evdns_server_request to dns_question_class, so that it won't break compilation under C++.  Use a macro so that old code won't break.  Mark the macro as deprecated.
- o Fix DNS unit tests so that having a DNS server with broken IPv6 support is no longer cause for aborting the unit tests.
- o Make event_base_free() succeed even if there are pending non-internal events on a base.  This may still leak memory and fds, but at least it no longer crashes.
- o Post-process the config.h file into a new, installed event-config.h file that we can install, and whose macros will be safe to include in header files.
- o Remove the long-deprecated acconfig.h file.
- o Do not require #include <sys/types.h> before #include <event.h>.
- o Add new evutil_timer* functions to wrap (or replace) the regular timeval manipulation functions.
- o Fix many build issues when using the Microsoft C compiler.
- o Remove a bash-ism in autogen.sh
- o When calling event_del on a signal, restore the signal handler's previous value rather than setting it to SIG_DFL. Patch from Christopher Layne.
- o Make the logic for active events work better with internal events; patch from Christopher Layne.
- o We do not need to specially remove a timeout before calling event_del; patch from Christopher Layne.
diff --git a/base/third_party/libevent/Doxyfile b/base/third_party/libevent/Doxyfile
deleted file mode 100644
index 77f6de8..0000000
--- a/base/third_party/libevent/Doxyfile
+++ /dev/null
@@ -1,230 +0,0 @@
-# Doxyfile 1.5.1
-
-# This file describes the settings to be used by the documentation system
-# doxygen (www.doxygen.org) for a project
-#
-# All text after a hash (#) is considered a comment and will be ignored
-# The format is:
-#       TAG = value [value, ...]
-# For lists items can also be appended using:
-#       TAG += value [value, ...]
-# Values that contain spaces should be placed between quotes (" ")
-
-#---------------------------------------------------------------------------
-# Project related configuration options
-#---------------------------------------------------------------------------
-
-# The PROJECT_NAME tag is a single word (or a sequence of words surrounded 
-# by quotes) that should identify the project.
-
-PROJECT_NAME           = libevent
-
-# Place all output under 'doxygen/'
-
-OUTPUT_DIRECTORY        = doxygen/
-
-# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen 
-# will interpret the first line (until the first dot) of a JavaDoc-style 
-# comment as the brief description. If set to NO, the JavaDoc 
-# comments will behave just like the Qt-style comments (thus requiring an 
-# explicit @brief command for a brief description.
-
-JAVADOC_AUTOBRIEF      = YES
-
-# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C 
-# sources only. Doxygen will then generate output that is more tailored for C. 
-# For instance, some of the names that are used will be different. The list 
-# of all members will be omitted, etc.
-
-OPTIMIZE_OUTPUT_FOR_C  = YES
-
-# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the 
-# brief documentation of file, namespace and class members alphabetically 
-# by member name. If set to NO (the default) the members will appear in 
-# declaration order.
-
-SORT_BRIEF_DOCS        = YES
-
-#---------------------------------------------------------------------------
-# configuration options related to the input files
-#---------------------------------------------------------------------------
-
-# The INPUT tag can be used to specify the files and/or directories that contain 
-# documented source files. You may enter file names like "myfile.cpp" or 
-# directories like "/usr/src/myproject". Separate the files or directories 
-# with spaces.
-
-INPUT                  = event.h evdns.h evhttp.h evrpc.h
-
-#---------------------------------------------------------------------------
-# configuration options related to the HTML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_HTML tag is set to YES (the default) Doxygen will 
-# generate HTML output.
-
-GENERATE_HTML          = YES
-
-#---------------------------------------------------------------------------
-# configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will 
-# generate Latex output.
-
-GENERATE_LATEX         = YES
-
-# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. 
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
-# put in front of it. If left blank `latex' will be used as the default path.
-
-LATEX_OUTPUT           = latex
-
-# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be 
-# invoked. If left blank `latex' will be used as the default command name.
-
-LATEX_CMD_NAME         = latex
-
-# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to 
-# generate index for LaTeX. If left blank `makeindex' will be used as the 
-# default command name.
-
-MAKEINDEX_CMD_NAME     = makeindex
-
-# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact 
-# LaTeX documents. This may be useful for small projects and may help to 
-# save some trees in general.
-
-COMPACT_LATEX          = NO
-
-# The PAPER_TYPE tag can be used to set the paper type that is used 
-# by the printer. Possible values are: a4, a4wide, letter, legal and 
-# executive. If left blank a4wide will be used.
-
-PAPER_TYPE             = a4wide
-
-# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX 
-# packages that should be included in the LaTeX output.
-
-EXTRA_PACKAGES         = 
-
-# The LATEX_HEADER tag can be used to specify a personal LaTeX header for 
-# the generated latex document. The header should contain everything until 
-# the first chapter. If it is left blank doxygen will generate a 
-# standard header. Notice: only use this tag if you know what you are doing!
-
-LATEX_HEADER           = 
-
-# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated 
-# is prepared for conversion to pdf (using ps2pdf). The pdf file will 
-# contain links (just like the HTML output) instead of page references 
-# This makes the output suitable for online browsing using a pdf viewer.
-
-PDF_HYPERLINKS         = NO
-
-# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of 
-# plain latex in the generated Makefile. Set this option to YES to get a 
-# higher quality PDF documentation.
-
-USE_PDFLATEX           = NO
-
-# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. 
-# command to the generated LaTeX files. This will instruct LaTeX to keep 
-# running if errors occur, instead of asking the user for help. 
-# This option is also used when generating formulas in HTML.
-
-LATEX_BATCHMODE        = NO
-
-# If LATEX_HIDE_INDICES is set to YES then doxygen will not 
-# include the index chapters (such as File Index, Compound Index, etc.) 
-# in the output.
-
-LATEX_HIDE_INDICES     = NO
-
-#---------------------------------------------------------------------------
-# configuration options related to the man page output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_MAN tag is set to YES (the default) Doxygen will 
-# generate man pages
-
-GENERATE_MAN           = YES
-
-# The MAN_EXTENSION tag determines the extension that is added to 
-# the generated man pages (default is the subroutine's section .3)
-
-MAN_EXTENSION          = .3
-
-# If the MAN_LINKS tag is set to YES and Doxygen generates man output, 
-# then it will generate one additional man file for each entity 
-# documented in the real man page(s). These additional files 
-# only source the real man page, but without them the man command 
-# would be unable to find the correct page. The default is NO.
-
-MAN_LINKS              = YES
-
-#---------------------------------------------------------------------------
-# Configuration options related to the preprocessor   
-#---------------------------------------------------------------------------
-
-# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will 
-# evaluate all C-preprocessor directives found in the sources and include 
-# files.
-
-ENABLE_PREPROCESSING   = YES
-
-# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro 
-# names in the source code. If set to NO (the default) only conditional 
-# compilation will be performed. Macro expansion can be done in a controlled 
-# way by setting EXPAND_ONLY_PREDEF to YES.
-
-MACRO_EXPANSION        = NO
-
-# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES 
-# then the macro expansion is limited to the macros specified with the 
-# PREDEFINED and EXPAND_AS_DEFINED tags.
-
-EXPAND_ONLY_PREDEF     = NO
-
-# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files 
-# in the INCLUDE_PATH (see below) will be search if a #include is found.
-
-SEARCH_INCLUDES        = YES
-
-# The INCLUDE_PATH tag can be used to specify one or more directories that 
-# contain include files that are not input files but should be processed by 
-# the preprocessor.
-
-INCLUDE_PATH           = 
-
-# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard 
-# patterns (like *.h and *.hpp) to filter out the header-files in the 
-# directories. If left blank, the patterns specified with FILE_PATTERNS will 
-# be used.
-
-INCLUDE_FILE_PATTERNS  = 
-
-# The PREDEFINED tag can be used to specify one or more macro names that 
-# are defined before the preprocessor is started (similar to the -D option of 
-# gcc). The argument of the tag is a list of macros of the form: name 
-# or name=definition (no spaces). If the definition and the = are 
-# omitted =1 is assumed. To prevent a macro definition from being 
-# undefined via #undef or recursively expanded use the := operator 
-# instead of the = operator.
-
-PREDEFINED             = TAILQ_ENTRY RB_ENTRY _EVENT_DEFINED_TQENTRY
-
-# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then 
-# this tag can be used to specify a list of macro names that should be expanded. 
-# The macro definition that is found in the sources will be used. 
-# Use the PREDEFINED tag if you want to use a different macro definition.
-
-EXPAND_AS_DEFINED      = 
-
-# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then 
-# doxygen's preprocessor will remove all function-like macros that are alone 
-# on a line, have an all uppercase name, and do not end with a semicolon. Such 
-# function macros are typically used for boiler-plate code, and will confuse 
-# the parser if not removed.
-
-SKIP_FUNCTION_MACROS   = YES
diff --git a/base/third_party/libevent/LICENSE b/base/third_party/libevent/LICENSE
deleted file mode 100644
index cabd9fc..0000000
--- a/base/third_party/libevent/LICENSE
+++ /dev/null
@@ -1,53 +0,0 @@
-Libevent is available for use under the following license, commonly known
-as the 3-clause (or "modified") BSD license:
-
-==============================
-Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
-Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-1. Redistributions of source code must retain the above copyright
-   notice, this list of conditions and the following disclaimer.
-2. Redistributions in binary form must reproduce the above copyright
-   notice, this list of conditions and the following disclaimer in the
-   documentation and/or other materials provided with the distribution.
-3. The name of the author may not be used to endorse or promote products
-   derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
-IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
-OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
-NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-==============================
-
-Portions of Libevent are based on works by others, also made available by
-them under the three-clause BSD license above.  The copyright notices are
-available in the corresponding source files; the license is as above.  Here's
-a list:
-
-log.c:
-   Copyright (c) 2000 Dug Song <dugsong@monkey.org>
-   Copyright (c) 1993 The Regents of the University of California.
-
-strlcpy.c:
-   Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
-
-win32.c:
-   Copyright (c) 2003 Michael A. Davis <mike@datanerds.net>
-
-evport.c:
-   Copyright (c) 2007 Sun Microsystems
-
-min_heap.h:
-   Copyright (c) 2006 Maxim Yegorushkin <maxim.yegorushkin@gmail.com>
-
-tree.h:
-   Copyright 2002 Niels Provos <provos@citi.umich.edu>
diff --git a/base/third_party/libevent/Makefile.am b/base/third_party/libevent/Makefile.am
deleted file mode 100644
index c1ed62a..0000000
--- a/base/third_party/libevent/Makefile.am
+++ /dev/null
@@ -1,152 +0,0 @@
-AUTOMAKE_OPTIONS = foreign no-dependencies
-
-ACLOCAL_AMFLAGS = -I m4
-
-# This is the point release for libevent.  It shouldn't include any
-# a/b/c/d/e notations.
-RELEASE = 1.4
-
-# This is the version info for the libevent binary API.  It has three
-# numbers:
-#   Current  -- the number of the binary API that we're implementing
-#   Revision -- which iteration of the implementation of the binary
-#               API are we supplying?
-#   Age      -- How many previous binary API versions do we also
-#               support?
-#
-# If we release a new version that does not change the binary API,
-# increment Revision.
-#
-# If we release a new version that changes the binary API, but does
-# not break programs compiled against the old binary API, increment
-# Current and Age.  Set Revision to 0, since this is the first
-# implementation of the new API.
-#
-# Otherwise, we're changing the binary API and breaking bakward
-# compatibility with old binaries.  Increment Current.  Set Age to 0,
-# since we're backward compatible with no previous APIs.  Set Revision
-# to 0 too.
-VERSION_INFO = 4:1:2
-
-###
-# History:
-#   We started using Libtool around version 1.0d.  For all versions from
-#   1.0d through 1.3e, we set RELEASE to the version name, and
-#   VERSION_INFO to something haphazard.  The didn't matter, since
-#   setting RELEASE meant that no version of Libevent was treated as
-#   binary-compatible with any other version.
-#
-#   As of 1.4.0-beta, we set RELEASE to "1.4", so that releases in the
-#   1.4.x series could be potentially binary-compatible with one another,
-#   but not with any other series.  (They aren't.)  We didn't necessarily
-#   set VERSION_INFO correctly, or update it as often as we should have.
-#   The VERSION_INFO values were:
-#    1.4.0-beta .. 1.4.4-stable     : 2:0:0   [See note 1]
-#    1.4.5-stable                   : 3:0:1   (compatible ABI change)
-#    1.4.6-stable                   : 3:1:1   (no ABI change)
-#    1.4.7-stable                   : 3:1:1   [see note 1]
-#    1.4.8-stable                   : 3:2:1   (no ABI change)
-#    1.4.9-stable                   : 3:2:1   [see note 1]
-#    1.4.10-stable                  : 3:3:1   (no ABI change)
-#    1.4.11-stable .. 1.4.13-stable : 3:3:1   [see note 1]
-#    1.4.14a-stable:                : 3:3:2   [see note 2]
-#    1.4.14b-stable:                : 4:0:2   (compatible ABI change)
-#    1.4.15-stable:                 : 4:1:2   (no ABI change)
-#
-# [1]: Using the same VERSION_INFO value was wrong; we should have been
-#      updating the Revision field.
-# [2]: We set the VERSION_INFO completely wrong on 1.4.14b-stable
-
-bin_SCRIPTS = event_rpcgen.py
-
-EXTRA_DIST = autogen.sh event.h event-internal.h log.h evsignal.h evdns.3 \
-	evrpc.h evrpc-internal.h min_heap.h \
-	event.3 \
-	Doxyfile \
-	kqueue.c epoll_sub.c epoll.c select.c poll.c signal.c \
-	evport.c devpoll.c event_rpcgen.py \
-	sample/Makefile.am sample/Makefile.in sample/event-test.c \
-	sample/signal-test.c sample/time-test.c \
-	test/Makefile.am test/Makefile.in test/bench.c test/regress.c \
-	test/test-eof.c test/test-weof.c test/test-time.c \
-	test/test-init.c test/test.sh \
-	compat/sys/queue.h compat/sys/_libevent_time.h \
-	WIN32-Code/config.h \
-	WIN32-Code/event-config.h \
-	WIN32-Code/win32.c \
-	WIN32-Code/tree.h \
-	WIN32-Prj/event_test/event_test.dsp \
-	WIN32-Prj/event_test/test.txt WIN32-Prj/libevent.dsp \
-	WIN32-Prj/libevent.dsw WIN32-Prj/signal_test/signal_test.dsp \
-	WIN32-Prj/time_test/time_test.dsp WIN32-Prj/regress/regress.vcproj \
-	WIN32-Prj/libevent.sln WIN32-Prj/libevent.vcproj \
-	Makefile.nmake test/Makefile.nmake \
-	LICENSE
-
-lib_LTLIBRARIES = libevent.la libevent_core.la libevent_extra.la
-
-if BUILD_WIN32
-
-SUBDIRS = . sample
-SYS_LIBS = -lws2_32
-SYS_SRC = WIN32-Code/win32.c
-SYS_INCLUDES = -IWIN32-Code
-
-else
-
-SUBDIRS = . sample test
-SYS_LIBS =
-SYS_SRC =
-SYS_INCLUDES =
-
-endif
-
-BUILT_SOURCES = event-config.h
-
-event-config.h: config.h
-	echo '/* event-config.h' > $@
-	echo ' * Generated by autoconf; post-processed by libevent.' >> $@
-	echo ' * Do not edit this file.' >> $@
-	echo ' * Do not rely on macros in this file existing in later versions.'>> $@
-	echo ' */' >> $@
-	echo '#ifndef _EVENT_CONFIG_H_' >> $@
-	echo '#define _EVENT_CONFIG_H_' >> $@
-
-	sed -e 's/#define /#define _EVENT_/' \
-	    -e 's/#undef /#undef _EVENT_/' \
-	    -e 's/#ifndef /#ifndef _EVENT_/' < config.h >> $@
-	echo "#endif" >> $@
-
-CORE_SRC = event.c buffer.c evbuffer.c log.c evutil.c $(SYS_SRC)
-EXTRA_SRC = event_tagging.c http.c evhttp.h http-internal.h evdns.c \
-	evdns.h evrpc.c evrpc.h evrpc-internal.h \
-	strlcpy.c strlcpy-internal.h strlcpy-internal.h
-
-libevent_la_SOURCES = $(CORE_SRC) $(EXTRA_SRC)
-libevent_la_LIBADD = @LTLIBOBJS@ $(SYS_LIBS)
-libevent_la_LDFLAGS = -release $(RELEASE) -version-info $(VERSION_INFO)
-
-libevent_core_la_SOURCES = $(CORE_SRC)
-libevent_core_la_LIBADD = @LTLIBOBJS@ $(SYS_LIBS)
-libevent_core_la_LDFLAGS = -release $(RELEASE) -version-info $(VERSION_INFO)
-
-libevent_extra_la_SOURCES = $(EXTRA_SRC)
-libevent_extra_la_LIBADD = @LTLIBOBJS@ $(SYS_LIBS)
-libevent_extra_la_LDFLAGS = -release $(RELEASE) -version-info $(VERSION_INFO)
-
-include_HEADERS = event.h evhttp.h evdns.h evrpc.h evutil.h
-
-nodist_include_HEADERS = event-config.h
-
-INCLUDES = -I$(srcdir)/compat $(SYS_INCLUDES)
-
-man_MANS = event.3 evdns.3
-
-verify: libevent.la
-	cd test && make verify
-
-doxygen: FORCE
-	doxygen $(srcdir)/Doxyfile
-FORCE:
-
-DISTCLEANFILES = *~ event-config.h
diff --git a/base/third_party/libevent/Makefile.nmake b/base/third_party/libevent/Makefile.nmake
deleted file mode 100644
index f8d5722..0000000
--- a/base/third_party/libevent/Makefile.nmake
+++ /dev/null
@@ -1,48 +0,0 @@
-# WATCH OUT!  This makefile is a work in progress.  It is probably missing
-# tons of important things.  DO NOT RELY ON IT TO BUILD A GOOD LIBEVENT.
-
-# Needed for correctness
-CFLAGS=/Iinclude /Icompat /IWIN32-Code /DWIN32 /DHAVE_CONFIG_H /I.
-
-# For optimization and warnings
-CFLAGS=$(CFLAGS) /Ox /W3 /wd4996 /nologo
-
-# XXXX have a debug mode
-
-LIBFLAGS=/nologo
-
-
-CORE_OBJS=event.obj buffer.obj evbuffer.obj \
-	log.obj evutil.obj \
-	strlcpy.obj signal.obj win32.obj
-EXTRA_OBJS=event_tagging.obj http.obj evdns.obj evrpc.obj
-
-ALL_OBJS=$(CORE_OBJS) $(WIN_OBJS) $(EXTRA_OBJS)
-STATIC_LIBS=libevent_core.lib libevent_extras.lib libevent.lib
-
-
-all: static_libs tests
-
-static_libs: $(STATIC_LIBS)
-
-win32.obj: WIN32-Code\win32.c
-	$(CC) $(CFLAGS) /c WIN32-Code\win32.c
-
-libevent_core.lib: $(CORE_OBJS)
-	lib $(LIBFLAGS) $(CORE_OBJS) /out:libevent_core.lib 
-
-libevent_extras.lib: $(EXTRA_OBJS)
-	lib $(LIBFLAGS) $(EXTRA_OBJS) /out:libevent_extras.lib
-
-libevent.lib: $(CORE_OBJ) $(EXTRA_OBJS)
-	lib $(LIBFLAGS) $(CORE_OBJS) $(EXTRA_OBJS) /out:libevent.lib
-
-clean:
-	del $(ALL_OBJS)
-	del $(STATIC_LIBS)
-	cd test
-	$(MAKE) /F Makefile.nmake clean
-
-tests:
-	cd test
-	$(MAKE) /F Makefile.nmake
diff --git a/base/third_party/libevent/README b/base/third_party/libevent/README
deleted file mode 100644
index b065039..0000000
--- a/base/third_party/libevent/README
+++ /dev/null
@@ -1,57 +0,0 @@
-To build libevent, type
-
-$ ./configure && make
-
-     (If you got libevent from the subversion repository, you will
-      first need to run the included "autogen.sh" script in order to
-      generate the configure script.)
-
-Install as root via
-
-# make install
-
-You can run the regression tests by
-
-$ make verify
-
-Before, reporting any problems, please run the regression tests.
-
-To enable the low-level tracing build the library as:
-
-CFLAGS=-DUSE_DEBUG ./configure [...]
-
-Acknowledgements:
------------------
-
-The following people have helped with suggestions, ideas, code or
-fixing bugs:
-
-  Alejo
-  Weston Andros Adamson
-  William Ahern
-  Stas Bekman
-  Andrew Danforth
-  Mike Davis
-  Shie Erlich
-  Alexander von Gernler
-  Artur Grabowski
-  Aaron Hopkins
-  Claudio Jeker
-  Scott Lamb
-  Adam Langley
-  Philip Lewis
-  David Libenzi
-  Nick Mathewson
-  Andrey Matveev
-  Richard Nyberg
-  Jon Oberheide
-  Phil Oleson
-  Dave Pacheco
-  Tassilo von Parseval
-  Pierre Phaneuf
-  Jon Poland
-  Bert JW Regeer
-  Dug Song
-  Taral
-
-If I have forgotten your name, please contact me.
diff --git a/base/third_party/libevent/README.chromium b/base/third_party/libevent/README.chromium
deleted file mode 100644
index 1462e88..0000000
--- a/base/third_party/libevent/README.chromium
+++ /dev/null
@@ -1,39 +0,0 @@
-Name: libevent
-URL: http://libevent.org/
-Version: 1.4.15
-License: BSD
-Security Critical: yes
-
-Local Modifications:
-Rather than use libevent's own build system, we just build a Chrome
-static library using GYP.
-
-1) Run configure and "make event-config.h" on Linux, FreeBSD, Solaris,
-   and Mac and copy config.h and event-config.h to linux/, freebsd/,
-   solaris/, and mac/ respectively.
-2) Add libevent.gyp.
-3) chromium.patch is applied to make the following changes:
-   - Allow libevent to be used without being installed by changing <...>
-     #includes to "...".
-   - Fix a race condition in event_del.
-   - Optimistically assume CLOCK_MONOTONIC is available and fallback if it
-     fails, rather than explicitly testing for it.
-   - Remove an unneeded variable that causes a -Werror build failure.
-   - Add an #ifndef to fix a preprocessor redefined -Werror build failure.
-   - Revert the patch from http://sourceforge.net/p/levent/bugs/223/ that
-     introduces use-after-free memory corruption when an event callback frees
-     the struct event memory.
-   - Remove deprecated global variables, event_sigcb and event_gotsig
-     (essentially unused) that trigger tsan errors. (crbug/605894)
-4) The directories WIN32-Code and WIN32-Prj are not included.
-5) The configs for android were copied from Linux's which were very close to
-   android one with the exception of HAVE_FD_MASK and HAVE_STRLCPY.
-6) Add files to support building with the PNaCl toolchain. Added
-   libevent_nacl_nonsfi.gyp for build rule. nacl_nonsfi/config.h and
-   nacl_nonsfi/event-config.h are derived from linux/ counterparts.
-   nacl_nonsfi/random.c is also added to provide the random() function,
-   which is missing in the newlib-based PNaCl toolchain.
-7) Stub out signal.c for nacl_helper_nonsfi. socketpair() will be prohibited
-   by sandbox in nacl_helper_nonsfi.
-8) Remove an unnecessary workaround for OS X 10.4 from kqueue.c. It was causing
-   problems on macOS Sierra.
diff --git a/base/third_party/libevent/aix/config.h b/base/third_party/libevent/aix/config.h
deleted file mode 100644
index 89e1f11..0000000
--- a/base/third_party/libevent/aix/config.h
+++ /dev/null
@@ -1,276 +0,0 @@
-/* config.h.  Generated from config.h.in by configure.  */
-/* config.h.in.  Generated from configure.in by autoheader.  */
-
-/* Define if clock_gettime is available in libc */
-#define DNS_USE_CPU_CLOCK_FOR_ID 1
-
-/* Define is no secure id variant is available */
-/* #undef DNS_USE_GETTIMEOFDAY_FOR_ID */
-
-/* Define to 1 if you have the `clock_gettime' function. */
-#define HAVE_CLOCK_GETTIME 1
-
-/* Define if /dev/poll is available */
-/* #undef HAVE_DEVPOLL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if your system supports the epoll system calls */
-/* #undef HAVE_EPOLL */
-
-/* Define to 1 if you have the `epoll_ctl' function. */
-/* #undef HAVE_EPOLL_CTL */
-
-/* Define if your system supports event ports */
-/* #undef HAVE_EVENT_PORTS */
-
-/* Define to 1 if you have the `fcntl' function. */
-#define HAVE_FCNTL 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H 1
-
-/* Define to 1 if the system has the type `fd_mask'. */
-/* #undef HAVE_FD_MASK */
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#define HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the `getegid' function. */
-#define HAVE_GETEGID 1
-
-/* Define to 1 if you have the `geteuid' function. */
-#define HAVE_GETEUID 1
-
-/* Define to 1 if you have the `getnameinfo' function. */
-#define HAVE_GETNAMEINFO 1
-
-/* Define to 1 if you have the `gettimeofday' function. */
-#define HAVE_GETTIMEOFDAY 1
-
-/* Define to 1 if you have the `inet_ntop' function. */
-#define HAVE_INET_NTOP 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `issetugid' function. */
-/* #undef HAVE_ISSETUGID */
-
-/* Define to 1 if you have the `kqueue' function. */
-/* #undef HAVE_KQUEUE */
-
-/* Define to 1 if you have the `nsl' library (-lnsl). */
-#define HAVE_LIBNSL 1
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-/* #undef HAVE_LIBRESOLV */
-
-/* Define to 1 if you have the `rt' library (-lrt). */
-#define HAVE_LIBRT 1
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-/* #undef HAVE_LIBSOCKET */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netinet/in6.h> header file. */
-/* #undef HAVE_NETINET_IN6_H */
-
-/* Define to 1 if you have the `poll' function. */
-#define HAVE_POLL 1
-
-/* Define to 1 if you have the <poll.h> header file. */
-#define HAVE_POLL_H 1
-
-/* Define to 1 if you have the `port_create' function. */
-/* #undef HAVE_PORT_CREATE */
-
-/* Define to 1 if you have the <port.h> header file. */
-/* #undef HAVE_PORT_H */
-
-/* Define to 1 if you have the `select' function. */
-#define HAVE_SELECT 1
-
-/* Define if F_SETFD is defined in <fcntl.h> */
-#define HAVE_SETFD 1
-
-/* Define to 1 if you have the `sigaction' function. */
-#define HAVE_SIGACTION 1
-
-/* Define to 1 if you have the `signal' function. */
-#define HAVE_SIGNAL 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the <stdarg.h> header file. */
-#define HAVE_STDARG_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-#define HAVE_STRLCPY 1
-
-/* Define to 1 if you have the `strsep' function. */
-#define HAVE_STRSEP 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-#define HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the `strtoll' function. */
-#define HAVE_STRTOLL 1
-
-/* Define to 1 if the system has the type `struct in6_addr'. */
-#define HAVE_STRUCT_IN6_ADDR 1
-
-/* Define to 1 if you have the <sys/devpoll.h> header file. */
-/* #undef HAVE_SYS_DEVPOLL_H */
-
-/* Define to 1 if you have the <sys/epoll.h> header file. */
-/* #undef HAVE_SYS_EPOLL_H */
-
-/* Define to 1 if you have the <sys/event.h> header file. */
-/* #undef HAVE_SYS_EVENT_H */
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-#define HAVE_SYS_IOCTL_H 1
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/queue.h> header file. */
-#define HAVE_SYS_QUEUE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#define HAVE_SYS_SELECT_H 1
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
-#define HAVE_TAILQFOREACH 1
-
-/* Define if timeradd is defined in <sys/time.h> */
-/* #undef HAVE_TIMERADD */
-
-/* Define if timerclear is defined in <sys/time.h> */
-#define HAVE_TIMERCLEAR 1
-
-/* Define if timercmp is defined in <sys/time.h> */
-#define HAVE_TIMERCMP 1
-
-/* Define if timerisset is defined in <sys/time.h> */
-#define HAVE_TIMERISSET 1
-
-/* Define to 1 if the system has the type `uint16_t'. */
-#define HAVE_UINT16_T 1
-
-/* Define to 1 if the system has the type `uint32_t'. */
-#define HAVE_UINT32_T 1
-
-/* Define to 1 if the system has the type `uint64_t'. */
-#define HAVE_UINT64_T 1
-
-/* Define to 1 if the system has the type `uint8_t'. */
-#define HAVE_UINT8_T 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `vasprintf' function. */
-/* #undef HAVE_VASPRINTF */
-
-/* Define if kqueue works correctly with pipes */
-/* #undef HAVE_WORKING_KQUEUE */
-
-/* Define to the sub-directory in which libtool stores uninstalled libraries.
- */
-#define LT_OBJDIR ".libs/"
-
-/* Numeric representation of the version */
-#define NUMERIC_VERSION 0x01040f00
-
-/* Name of package */
-#define PACKAGE "libevent"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT ""
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME ""
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING ""
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME ""
-
-/* Define to the home page for this package. */
-#define PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION ""
-
-/* The size of `int', as computed by sizeof. */
-#define SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define SIZEOF_LONG 4
-
-/* The size of `long long', as computed by sizeof. */
-#define SIZEOF_LONG_LONG 8
-
-/* The size of `short', as computed by sizeof. */
-#define SIZEOF_SHORT 2
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define TIME_WITH_SYS_TIME 1
-
-/* Version number of package */
-#define VERSION "1.4.15"
-
-/* Define to appropriate substitue if compiler doesnt have __func__ */
-/* #undef __func__ */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef const */
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
-   calls it, or to nothing if 'inline' is not supported under any name.  */
-#ifndef __cplusplus
-/* #undef inline */
-#endif
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef pid_t */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-/* Define to unsigned int if you dont have it */
-/* #undef socklen_t */
diff --git a/base/third_party/libevent/aix/event-config.h b/base/third_party/libevent/aix/event-config.h
deleted file mode 100644
index 2679490..0000000
--- a/base/third_party/libevent/aix/event-config.h
+++ /dev/null
@@ -1,284 +0,0 @@
-/* event-config.h
- * Generated by autoconf; post-processed by libevent.
- * Do not edit this file.
- * Do not rely on macros in this file existing in later versions.
- */
-#ifndef _EVENT_CONFIG_H_
-#define _EVENT_CONFIG_H_
-/* config.h.  Generated from config.h.in by configure.  */
-/* config.h.in.  Generated from configure.in by autoheader.  */
-
-/* Define if clock_gettime is available in libc */
-#define _EVENT_DNS_USE_CPU_CLOCK_FOR_ID 1
-
-/* Define is no secure id variant is available */
-/* #undef _EVENT_DNS_USE_GETTIMEOFDAY_FOR_ID */
-
-/* Define to 1 if you have the `clock_gettime' function. */
-#define _EVENT_HAVE_CLOCK_GETTIME 1
-
-/* Define if /dev/poll is available */
-/* #undef _EVENT_HAVE_DEVPOLL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define _EVENT_HAVE_DLFCN_H 1
-
-/* Define if your system supports the epoll system calls */
-/* #undef _EVENT_HAVE_EPOLL */
-
-/* Define to 1 if you have the `epoll_ctl' function. */
-/* #undef _EVENT_HAVE_EPOLL_CTL */
-
-/* Define if your system supports event ports */
-/* #undef _EVENT_HAVE_EVENT_PORTS */
-
-/* Define to 1 if you have the `fcntl' function. */
-#define _EVENT_HAVE_FCNTL 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define _EVENT_HAVE_FCNTL_H 1
-
-/* Define to 1 if the system has the type `fd_mask'. */
-#define _EVENT_HAVE_FD_MASK 1
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#define _EVENT_HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the `getegid' function. */
-#define _EVENT_HAVE_GETEGID 1
-
-/* Define to 1 if you have the `geteuid' function. */
-#define _EVENT_HAVE_GETEUID 1
-
-/* Define to 1 if you have the `getnameinfo' function. */
-#define _EVENT_HAVE_GETNAMEINFO 1
-
-/* Define to 1 if you have the `gettimeofday' function. */
-#define _EVENT_HAVE_GETTIMEOFDAY 1
-
-/* Define to 1 if you have the `inet_ntop' function. */
-#define _EVENT_HAVE_INET_NTOP 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define _EVENT_HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `issetugid' function. */
-/* #undef _EVENT_HAVE_ISSETUGID */
-
-/* Define to 1 if you have the `kqueue' function. */
-/* #undef _EVENT_HAVE_KQUEUE */
-
-/* Define to 1 if you have the `nsl' library (-lnsl). */
-#define _EVENT_HAVE_LIBNSL 1
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-/* #undef _EVENT_HAVE_LIBRESOLV */
-
-/* Define to 1 if you have the `rt' library (-lrt). */
-#define _EVENT_HAVE_LIBRT 1
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-/* #undef _EVENT_HAVE_LIBSOCKET */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define _EVENT_HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netinet/in6.h> header file. */
-/* #undef _EVENT_HAVE_NETINET_IN6_H */
-
-/* Define to 1 if you have the `poll' function. */
-#define _EVENT_HAVE_POLL 1
-
-/* Define to 1 if you have the <poll.h> header file. */
-#define _EVENT_HAVE_POLL_H 1
-
-/* Define to 1 if you have the `port_create' function. */
-/* #undef _EVENT_HAVE_PORT_CREATE */
-
-/* Define to 1 if you have the <port.h> header file. */
-/* #undef _EVENT_HAVE_PORT_H */
-
-/* Define to 1 if you have the `select' function. */
-#define _EVENT_HAVE_SELECT 1
-
-/* Define if F_SETFD is defined in <fcntl.h> */
-#define _EVENT_HAVE_SETFD 1
-
-/* Define to 1 if you have the `sigaction' function. */
-#define _EVENT_HAVE_SIGACTION 1
-
-/* Define to 1 if you have the `signal' function. */
-#define _EVENT_HAVE_SIGNAL 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define _EVENT_HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the <stdarg.h> header file. */
-#define _EVENT_HAVE_STDARG_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define _EVENT_HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define _EVENT_HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define _EVENT_HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define _EVENT_HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-#define _EVENT_HAVE_STRLCPY 1
-
-/* Define to 1 if you have the `strsep' function. */
-#define _EVENT_HAVE_STRSEP 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-#define _EVENT_HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the `strtoll' function. */
-#define _EVENT_HAVE_STRTOLL 1
-
-/* Define to 1 if the system has the type `struct in6_addr'. */
-#define _EVENT_HAVE_STRUCT_IN6_ADDR 1
-
-/* Define to 1 if you have the <sys/devpoll.h> header file. */
-/* #undef _EVENT_HAVE_SYS_DEVPOLL_H */
-
-/* Define to 1 if you have the <sys/epoll.h> header file. */
-/* #undef _EVENT_HAVE_SYS_EPOLL_H */
-
-/* Define to 1 if you have the <sys/event.h> header file. */
-/* #undef _EVENT_HAVE_SYS_EVENT_H */
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-#define _EVENT_HAVE_SYS_IOCTL_H 1
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define _EVENT_HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/queue.h> header file. */
-#define _EVENT_HAVE_SYS_QUEUE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#define _EVENT_HAVE_SYS_SELECT_H 1
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define _EVENT_HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define _EVENT_HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define _EVENT_HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define _EVENT_HAVE_SYS_TYPES_H 1
-
-/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
-#define _EVENT_HAVE_TAILQFOREACH 1
-
-/* Define if timeradd is defined in <sys/time.h> */
-/* #undef _EVENT_HAVE_TIMERADD */
-
-/* Define if timerclear is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERCLEAR 1
-
-/* Define if timercmp is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERCMP 1
-
-/* Define if timerisset is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERISSET 1
-
-/* Define to 1 if the system has the type `uint16_t'. */
-#define _EVENT_HAVE_UINT16_T 1
-
-/* Define to 1 if the system has the type `uint32_t'. */
-#define _EVENT_HAVE_UINT32_T 1
-
-/* Define to 1 if the system has the type `uint64_t'. */
-#define _EVENT_HAVE_UINT64_T 1
-
-/* Define to 1 if the system has the type `uint8_t'. */
-#define _EVENT_HAVE_UINT8_T 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define _EVENT_HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `vasprintf' function. */
-/* #undef _EVENT_HAVE_VASPRINTF */
-
-/* Define if kqueue works correctly with pipes */
-/* #undef _EVENT_HAVE_WORKING_KQUEUE */
-
-/* Define to the sub-directory in which libtool stores uninstalled libraries.
- */
-#define _EVENT_LT_OBJDIR ".libs/"
-
-/* Numeric representation of the version */
-#define _EVENT_NUMERIC_VERSION 0x01040f00
-
-/* Name of package */
-#define _EVENT_PACKAGE "libevent"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define _EVENT_PACKAGE_BUGREPORT ""
-
-/* Define to the full name of this package. */
-#define _EVENT_PACKAGE_NAME ""
-
-/* Define to the full name and version of this package. */
-#define _EVENT_PACKAGE_STRING ""
-
-/* Define to the one symbol short name of this package. */
-#define _EVENT_PACKAGE_TARNAME ""
-
-/* Define to the home page for this package. */
-#define _EVENT_PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define _EVENT_PACKAGE_VERSION ""
-
-/* The size of `int', as computed by sizeof. */
-#define _EVENT_SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG 4
-
-/* The size of `long long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG_LONG 8
-
-/* The size of `short', as computed by sizeof. */
-#define _EVENT_SIZEOF_SHORT 2
-
-/* Define to 1 if you have the ANSI C header files. */
-#define _EVENT_STDC_HEADERS 1
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define _EVENT_TIME_WITH_SYS_TIME 1
-
-/* Version number of package */
-#define _EVENT_VERSION "1.4.15"
-
-/* Define to appropriate substitue if compiler doesnt have __func__ */
-/* #undef _EVENT___func__ */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef _EVENT_const */
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
-   calls it, or to nothing if 'inline' is not supported under any name.  */
-#ifndef _EVENT___cplusplus
-/* #undef _EVENT_inline */
-#endif
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef _EVENT_pid_t */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef _EVENT_size_t */
-
-/* Define to unsigned int if you dont have it */
-/* #undef _EVENT_socklen_t */
-#endif
diff --git a/base/third_party/libevent/autogen.sh b/base/third_party/libevent/autogen.sh
deleted file mode 100755
index 099cb30..0000000
--- a/base/third_party/libevent/autogen.sh
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/bin/sh
-if [ -x "`which autoreconf 2>/dev/null`" ] ; then
-   exec autoreconf -ivf
-fi
-
-LIBTOOLIZE=libtoolize
-SYSNAME=`uname`
-if [ "x$SYSNAME" = "xDarwin" ] ; then
-  LIBTOOLIZE=glibtoolize
-fi
-aclocal && \
-	autoheader && \
-	$LIBTOOLIZE && \
-	autoconf && \
-	automake --add-missing --copy
diff --git a/base/third_party/libevent/buffer.c b/base/third_party/libevent/buffer.c
deleted file mode 100644
index ebf35c9..0000000
--- a/base/third_party/libevent/buffer.c
+++ /dev/null
@@ -1,554 +0,0 @@
-/*
- * Copyright (c) 2002, 2003 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef WIN32
-#include <winsock2.h>
-#include <windows.h>
-#endif
-
-#ifdef HAVE_VASPRINTF
-/* If we have vasprintf, we need to define this before we include stdio.h. */
-#define _GNU_SOURCE
-#endif
-
-#include <sys/types.h>
-
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-
-#ifdef HAVE_SYS_IOCTL_H
-#include <sys/ioctl.h>
-#endif
-
-#include <assert.h>
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#ifdef HAVE_STDARG_H
-#include <stdarg.h>
-#endif
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#include "event.h"
-#include "config.h"
-#include "evutil.h"
-#include "./log.h"
-
-struct evbuffer *
-evbuffer_new(void)
-{
-	struct evbuffer *buffer;
-	
-	buffer = calloc(1, sizeof(struct evbuffer));
-
-	return (buffer);
-}
-
-void
-evbuffer_free(struct evbuffer *buffer)
-{
-	if (buffer->orig_buffer != NULL)
-		free(buffer->orig_buffer);
-	free(buffer);
-}
-
-/* 
- * This is a destructive add.  The data from one buffer moves into
- * the other buffer.
- */
-
-#define SWAP(x,y) do { \
-	(x)->buffer = (y)->buffer; \
-	(x)->orig_buffer = (y)->orig_buffer; \
-	(x)->misalign = (y)->misalign; \
-	(x)->totallen = (y)->totallen; \
-	(x)->off = (y)->off; \
-} while (0)
-
-int
-evbuffer_add_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
-{
-	int res;
-
-	/* Short cut for better performance */
-	if (outbuf->off == 0) {
-		struct evbuffer tmp;
-		size_t oldoff = inbuf->off;
-
-		/* Swap them directly */
-		SWAP(&tmp, outbuf);
-		SWAP(outbuf, inbuf);
-		SWAP(inbuf, &tmp);
-
-		/* 
-		 * Optimization comes with a price; we need to notify the
-		 * buffer if necessary of the changes. oldoff is the amount
-		 * of data that we transfered from inbuf to outbuf
-		 */
-		if (inbuf->off != oldoff && inbuf->cb != NULL)
-			(*inbuf->cb)(inbuf, oldoff, inbuf->off, inbuf->cbarg);
-		if (oldoff && outbuf->cb != NULL)
-			(*outbuf->cb)(outbuf, 0, oldoff, outbuf->cbarg);
-		
-		return (0);
-	}
-
-	res = evbuffer_add(outbuf, inbuf->buffer, inbuf->off);
-	if (res == 0) {
-		/* We drain the input buffer on success */
-		evbuffer_drain(inbuf, inbuf->off);
-	}
-
-	return (res);
-}
-
-int
-evbuffer_add_vprintf(struct evbuffer *buf, const char *fmt, va_list ap)
-{
-	char *buffer;
-	size_t space;
-	size_t oldoff = buf->off;
-	int sz;
-	va_list aq;
-
-	/* make sure that at least some space is available */
-	if (evbuffer_expand(buf, 64) < 0)
-		return (-1);
-	for (;;) {
-		size_t used = buf->misalign + buf->off;
-		buffer = (char *)buf->buffer + buf->off;
-		assert(buf->totallen >= used);
-		space = buf->totallen - used;
-
-#ifndef va_copy
-#define	va_copy(dst, src)	memcpy(&(dst), &(src), sizeof(va_list))
-#endif
-		va_copy(aq, ap);
-
-		sz = evutil_vsnprintf(buffer, space, fmt, aq);
-
-		va_end(aq);
-
-		if (sz < 0)
-			return (-1);
-		if ((size_t)sz < space) {
-			buf->off += sz;
-			if (buf->cb != NULL)
-				(*buf->cb)(buf, oldoff, buf->off, buf->cbarg);
-			return (sz);
-		}
-		if (evbuffer_expand(buf, sz + 1) == -1)
-			return (-1);
-
-	}
-	/* NOTREACHED */
-}
-
-int
-evbuffer_add_printf(struct evbuffer *buf, const char *fmt, ...)
-{
-	int res = -1;
-	va_list ap;
-
-	va_start(ap, fmt);
-	res = evbuffer_add_vprintf(buf, fmt, ap);
-	va_end(ap);
-
-	return (res);
-}
-
-/* Reads data from an event buffer and drains the bytes read */
-
-int
-evbuffer_remove(struct evbuffer *buf, void *data, size_t datlen)
-{
-	size_t nread = datlen;
-	if (nread >= buf->off)
-		nread = buf->off;
-
-	memcpy(data, buf->buffer, nread);
-	evbuffer_drain(buf, nread);
-	
-	return (nread);
-}
-
-/*
- * Reads a line terminated by either '\r\n', '\n\r' or '\r' or '\n'.
- * The returned buffer needs to be freed by the called.
- */
-
-char *
-evbuffer_readline(struct evbuffer *buffer)
-{
-	u_char *data = EVBUFFER_DATA(buffer);
-	size_t len = EVBUFFER_LENGTH(buffer);
-	char *line;
-	unsigned int i;
-
-	for (i = 0; i < len; i++) {
-		if (data[i] == '\r' || data[i] == '\n')
-			break;
-	}
-
-	if (i == len)
-		return (NULL);
-
-	if ((line = malloc(i + 1)) == NULL) {
-		fprintf(stderr, "%s: out of memory\n", __func__);
-		return (NULL);
-	}
-
-	memcpy(line, data, i);
-	line[i] = '\0';
-
-	/*
-	 * Some protocols terminate a line with '\r\n', so check for
-	 * that, too.
-	 */
-	if ( i < len - 1 ) {
-		char fch = data[i], sch = data[i+1];
-
-		/* Drain one more character if needed */
-		if ( (sch == '\r' || sch == '\n') && sch != fch )
-			i += 1;
-	}
-
-	evbuffer_drain(buffer, i + 1);
-
-	return (line);
-}
-
-
-char *
-evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
-		enum evbuffer_eol_style eol_style)
-{
-	u_char *data = EVBUFFER_DATA(buffer);
-	u_char *start_of_eol, *end_of_eol;
-	size_t len = EVBUFFER_LENGTH(buffer);
-	char *line;
-	unsigned int i, n_to_copy, n_to_drain;
-
-	if (n_read_out)
-		*n_read_out = 0;
-
-	/* depending on eol_style, set start_of_eol to the first character
-	 * in the newline, and end_of_eol to one after the last character. */
-	switch (eol_style) {
-	case EVBUFFER_EOL_ANY:
-		for (i = 0; i < len; i++) {
-			if (data[i] == '\r' || data[i] == '\n')
-				break;
-		}
-		if (i == len)
-			return (NULL);
-		start_of_eol = data+i;
-		++i;
-		for ( ; i < len; i++) {
-			if (data[i] != '\r' && data[i] != '\n')
-				break;
-		}
-		end_of_eol = data+i;
-		break;
-	case EVBUFFER_EOL_CRLF:
-		end_of_eol = memchr(data, '\n', len);
-		if (!end_of_eol)
-			return (NULL);
-		if (end_of_eol > data && *(end_of_eol-1) == '\r')
-			start_of_eol = end_of_eol - 1;
-		else
-			start_of_eol = end_of_eol;
-		end_of_eol++; /*point to one after the LF. */
-		break;
-	case EVBUFFER_EOL_CRLF_STRICT: {
-		u_char *cp = data;
-		while ((cp = memchr(cp, '\r', len-(cp-data)))) {
-			if (cp < data+len-1 && *(cp+1) == '\n')
-				break;
-			if (++cp >= data+len) {
-				cp = NULL;
-				break;
-			}
-		}
-		if (!cp)
-			return (NULL);
-		start_of_eol = cp;
-		end_of_eol = cp+2;
-		break;
-	}
-	case EVBUFFER_EOL_LF:
-		start_of_eol = memchr(data, '\n', len);
-		if (!start_of_eol)
-			return (NULL);
-		end_of_eol = start_of_eol + 1;
-		break;
-	default:
-		return (NULL);
-	}
-
-	n_to_copy = start_of_eol - data;
-	n_to_drain = end_of_eol - data;
-
-	if ((line = malloc(n_to_copy+1)) == NULL) {
-		event_warn("%s: out of memory\n", __func__);
-		return (NULL);
-	}
-
-	memcpy(line, data, n_to_copy);
-	line[n_to_copy] = '\0';
-
-	evbuffer_drain(buffer, n_to_drain);
-	if (n_read_out)
-		*n_read_out = (size_t)n_to_copy;
-
-	return (line);
-}
-
-/* Adds data to an event buffer */
-
-static void
-evbuffer_align(struct evbuffer *buf)
-{
-	memmove(buf->orig_buffer, buf->buffer, buf->off);
-	buf->buffer = buf->orig_buffer;
-	buf->misalign = 0;
-}
-
-#ifndef SIZE_MAX
-#define SIZE_MAX ((size_t)-1)
-#endif
-
-/* Expands the available space in the event buffer to at least datlen */
-
-int
-evbuffer_expand(struct evbuffer *buf, size_t datlen)
-{
-	size_t used = buf->misalign + buf->off;
-
-	assert(buf->totallen >= used);
-
-	/* If we can fit all the data, then we don't have to do anything */
-	if (buf->totallen - used >= datlen)
-		return (0);
-	/* If we would need to overflow to fit this much data, we can't
-	 * do anything. */
-	if (datlen > SIZE_MAX - buf->off)
-		return (-1);
-
-	/*
-	 * If the misalignment fulfills our data needs, we just force an
-	 * alignment to happen.  Afterwards, we have enough space.
-	 */
-	if (buf->totallen - buf->off >= datlen) {
-		evbuffer_align(buf);
-	} else {
-		void *newbuf;
-		size_t length = buf->totallen;
-		size_t need = buf->off + datlen;
-
-		if (length < 256)
-			length = 256;
-		if (need < SIZE_MAX / 2) {
-			while (length < need) {
-				length <<= 1;
-			}
-		} else {
-			length = need;
-		}
-
-		if (buf->orig_buffer != buf->buffer)
-			evbuffer_align(buf);
-		if ((newbuf = realloc(buf->buffer, length)) == NULL)
-			return (-1);
-
-		buf->orig_buffer = buf->buffer = newbuf;
-		buf->totallen = length;
-	}
-
-	return (0);
-}
-
-int
-evbuffer_add(struct evbuffer *buf, const void *data, size_t datlen)
-{
-	size_t used = buf->misalign + buf->off;
-	size_t oldoff = buf->off;
-
-	if (buf->totallen - used < datlen) {
-		if (evbuffer_expand(buf, datlen) == -1)
-			return (-1);
-	}
-
-	memcpy(buf->buffer + buf->off, data, datlen);
-	buf->off += datlen;
-
-	if (datlen && buf->cb != NULL)
-		(*buf->cb)(buf, oldoff, buf->off, buf->cbarg);
-
-	return (0);
-}
-
-void
-evbuffer_drain(struct evbuffer *buf, size_t len)
-{
-	size_t oldoff = buf->off;
-
-	if (len >= buf->off) {
-		buf->off = 0;
-		buf->buffer = buf->orig_buffer;
-		buf->misalign = 0;
-		goto done;
-	}
-
-	buf->buffer += len;
-	buf->misalign += len;
-
-	buf->off -= len;
-
- done:
-	/* Tell someone about changes in this buffer */
-	if (buf->off != oldoff && buf->cb != NULL)
-		(*buf->cb)(buf, oldoff, buf->off, buf->cbarg);
-
-}
-
-/*
- * Reads data from a file descriptor into a buffer.
- */
-
-#define EVBUFFER_MAX_READ	4096
-
-int
-evbuffer_read(struct evbuffer *buf, int fd, int howmuch)
-{
-	u_char *p;
-	size_t oldoff = buf->off;
-	int n = EVBUFFER_MAX_READ;
-
-#if defined(FIONREAD)
-#ifdef WIN32
-	long lng = n;
-	if (ioctlsocket(fd, FIONREAD, &lng) == -1 || (n=lng) <= 0) {
-#else
-	if (ioctl(fd, FIONREAD, &n) == -1 || n <= 0) {
-#endif
-		n = EVBUFFER_MAX_READ;
-	} else if (n > EVBUFFER_MAX_READ && n > howmuch) {
-		/*
-		 * It's possible that a lot of data is available for
-		 * reading.  We do not want to exhaust resources
-		 * before the reader has a chance to do something
-		 * about it.  If the reader does not tell us how much
-		 * data we should read, we artifically limit it.
-		 */
-		if ((size_t)n > buf->totallen << 2)
-			n = buf->totallen << 2;
-		if (n < EVBUFFER_MAX_READ)
-			n = EVBUFFER_MAX_READ;
-	}
-#endif	
-	if (howmuch < 0 || howmuch > n)
-		howmuch = n;
-
-	/* If we don't have FIONREAD, we might waste some space here */
-	if (evbuffer_expand(buf, howmuch) == -1)
-		return (-1);
-
-	/* We can append new data at this point */
-	p = buf->buffer + buf->off;
-
-#ifndef WIN32
-	n = read(fd, p, howmuch);
-#else
-	n = recv(fd, p, howmuch, 0);
-#endif
-	if (n == -1)
-		return (-1);
-	if (n == 0)
-		return (0);
-
-	buf->off += n;
-
-	/* Tell someone about changes in this buffer */
-	if (buf->off != oldoff && buf->cb != NULL)
-		(*buf->cb)(buf, oldoff, buf->off, buf->cbarg);
-
-	return (n);
-}
-
-int
-evbuffer_write(struct evbuffer *buffer, int fd)
-{
-	int n;
-
-#ifndef WIN32
-	n = write(fd, buffer->buffer, buffer->off);
-#else
-	n = send(fd, buffer->buffer, buffer->off, 0);
-#endif
-	if (n == -1)
-		return (-1);
-	if (n == 0)
-		return (0);
-	evbuffer_drain(buffer, n);
-
-	return (n);
-}
-
-u_char *
-evbuffer_find(struct evbuffer *buffer, const u_char *what, size_t len)
-{
-	u_char *search = buffer->buffer, *end = search + buffer->off;
-	u_char *p;
-
-	while (search < end &&
-	    (p = memchr(search, *what, end - search)) != NULL) {
-		if (p + len > end)
-			break;
-		if (memcmp(p, what, len) == 0)
-			return (p);
-		search = p + 1;
-	}
-
-	return (NULL);
-}
-
-void evbuffer_setcb(struct evbuffer *buffer,
-    void (*cb)(struct evbuffer *, size_t, size_t, void *),
-    void *cbarg)
-{
-	buffer->cb = cb;
-	buffer->cbarg = cbarg;
-}
diff --git a/base/third_party/libevent/chromium.patch b/base/third_party/libevent/chromium.patch
deleted file mode 100644
index 5cbdfba..0000000
--- a/base/third_party/libevent/chromium.patch
+++ /dev/null
@@ -1,226 +0,0 @@
-diff --git a/third_party/libevent/buffer.c b/third_party/libevent/buffer.c
-index 64324bb..ebf35c9 100644
---- a/third_party/libevent/buffer.c
-+++ b/third_party/libevent/buffer.c
-@@ -356,7 +356,6 @@ int
- evbuffer_expand(struct evbuffer *buf, size_t datlen)
- {
- 	size_t used = buf->misalign + buf->off;
--	size_t need;
- 
- 	assert(buf->totallen >= used);
- 
-diff --git a/third_party/libevent/evdns.c b/third_party/libevent/evdns.c
-index fa23163..f1c70d0 100644
---- a/third_party/libevent/evdns.c
-+++ b/third_party/libevent/evdns.c
-@@ -55,7 +55,9 @@
- #endif
- 
- /* #define _POSIX_C_SOURCE 200507 */
-+#ifndef _GNU_SOURCE
- #define _GNU_SOURCE
-+#endif
- 
- #ifdef DNS_USE_CPU_CLOCK_FOR_ID
- #ifdef DNS_USE_OPENSSL_FOR_ID
-@@ -134,7 +136,7 @@
- typedef ev_uint8_t u_char;
- typedef unsigned int uint;
- #endif
--#include <event.h>
-+#include "event.h"
- 
- #define u64 ev_uint64_t
- #define u32 ev_uint32_t
-diff --git a/third_party/libevent/evdns.h b/third_party/libevent/evdns.h
-index 1eb5c38..fca4ac3 100644
---- a/third_party/libevent/evdns.h
-+++ b/third_party/libevent/evdns.h
-@@ -165,7 +165,7 @@ extern "C" {
- #endif
- 
- /* For integer types. */
--#include <evutil.h>
-+#include "evutil.h"
- 
- /** Error codes 0-5 are as described in RFC 1035. */
- #define DNS_ERR_NONE 0
-diff --git a/third_party/libevent/event.c b/third_party/libevent/event.c
-index da6cd42..36b1c51 100644
---- a/third_party/libevent/event.c
-+++ b/third_party/libevent/event.c
-@@ -107,11 +107,7 @@ static const struct eventop *eventops[] = {
- /* Global state */
- struct event_base *current_base = NULL;
- extern struct event_base *evsignal_base;
--static int use_monotonic;
--
--/* Handle signals - This is a deprecated interface */
--int (*event_sigcb)(void);		/* Signal callback when gotsig is set */
--volatile sig_atomic_t event_gotsig;	/* Set in signal handler */
-+static int use_monotonic = 1;
- 
- /* Prototypes */
- static void	event_queue_insert(struct event_base *, struct event *, int);
-@@ -124,17 +120,6 @@ static int	timeout_next(struct event_base *, struct timeval **);
- static void	timeout_process(struct event_base *);
- static void	timeout_correct(struct event_base *, struct timeval *);
- 
--static void
--detect_monotonic(void)
--{
--#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
--	struct timespec	ts;
--
--	if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
--		use_monotonic = 1;
--#endif
--}
--
- static int
- gettime(struct event_base *base, struct timeval *tp)
- {
-@@ -144,18 +129,18 @@ gettime(struct event_base *base, struct timeval *tp)
- 	}
- 
- #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
--	if (use_monotonic) {
--		struct timespec	ts;
--
--		if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
--			return (-1);
-+	struct timespec	ts;
- 
-+	if (use_monotonic &&
-+	    clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
- 		tp->tv_sec = ts.tv_sec;
- 		tp->tv_usec = ts.tv_nsec / 1000;
- 		return (0);
- 	}
- #endif
- 
-+	use_monotonic = 0;
-+
- 	return (evutil_gettimeofday(tp, NULL));
- }
- 
-@@ -179,10 +164,6 @@ event_base_new(void)
- 	if ((base = calloc(1, sizeof(struct event_base))) == NULL)
- 		event_err(1, "%s: calloc", __func__);
- 
--	event_sigcb = NULL;
--	event_gotsig = 0;
--
--	detect_monotonic();
- 	gettime(base, &base->event_tv);
- 	
- 	min_heap_ctor(&base->timeheap);
-@@ -398,12 +379,9 @@ event_process_active(struct event_base *base)
- 			ncalls--;
- 			ev->ev_ncalls = ncalls;
- 			(*ev->ev_callback)((int)ev->ev_fd, ev->ev_res, ev->ev_arg);
--			if (event_gotsig || base->event_break) {
--			  	ev->ev_pncalls = NULL;
-+			if (base->event_break)
- 				return;
--			}
- 		}
--		ev->ev_pncalls = NULL;
- 	}
- }
- 
-@@ -506,18 +484,6 @@ event_base_loop(struct event_base *base, int flags)
- 			break;
- 		}
- 
--		/* You cannot use this interface for multi-threaded apps */
--		while (event_gotsig) {
--			event_gotsig = 0;
--			if (event_sigcb) {
--				res = (*event_sigcb)();
--				if (res == -1) {
--					errno = EINTR;
--					return (-1);
--				}
--			}
--		}
--
- 		timeout_correct(base, &tv);
- 
- 		tv_p = &tv;
-@@ -808,8 +774,6 @@ int
- event_del(struct event *ev)
- {
- 	struct event_base *base;
--	const struct eventop *evsel;
--	void *evbase;
- 
- 	event_debug(("event_del: %p, callback %p",
- 		 ev, ev->ev_callback));
-@@ -819,8 +783,6 @@ event_del(struct event *ev)
- 		return (-1);
- 
- 	base = ev->ev_base;
--	evsel = base->evsel;
--	evbase = base->evbase;
- 
- 	assert(!(ev->ev_flags & ~EVLIST_ALL));
- 
-@@ -838,7 +800,7 @@ event_del(struct event *ev)
- 
- 	if (ev->ev_flags & EVLIST_INSERTED) {
- 		event_queue_remove(base, ev, EVLIST_INSERTED);
--		return (evsel->del(evbase, ev));
-+		return (base->evsel->del(base->evbase, ev));
- 	}
- 
- 	return (0);
-diff --git a/third_party/libevent/event.h b/third_party/libevent/event.h
-index d1f5d9e..f0887b9 100644
---- a/third_party/libevent/event.h
-+++ b/third_party/libevent/event.h
-@@ -159,7 +159,7 @@
- extern "C" {
- #endif
- 
--#include <event-config.h>
-+#include "event-config.h"
- #ifdef _EVENT_HAVE_SYS_TYPES_H
- #include <sys/types.h>
- #endif
-@@ -172,7 +172,7 @@ extern "C" {
- #include <stdarg.h>
- 
- /* For int types. */
--#include <evutil.h>
-+#include "evutil.h"
- 
- #ifdef WIN32
- #define WIN32_LEAN_AND_MEAN
-diff --git a/third_party/libevent/evhttp.h b/third_party/libevent/evhttp.h
-index cba8be1..48c1d91 100644
---- a/third_party/libevent/evhttp.h
-+++ b/third_party/libevent/evhttp.h
-@@ -27,7 +27,7 @@
- #ifndef _EVHTTP_H_
- #define _EVHTTP_H_
- 
--#include <event.h>
-+#include "event.h"
- 
- #ifdef __cplusplus
- extern "C" {
-diff --git a/third_party/libevent/evutil.h b/third_party/libevent/evutil.h
-index dcb0013..8b664b9 100644
---- a/third_party/libevent/evutil.h
-+++ b/third_party/libevent/evutil.h
-@@ -38,7 +38,7 @@
- extern "C" {
- #endif
- 
--#include <event-config.h>
-+#include "event-config.h"
- #ifdef _EVENT_HAVE_SYS_TIME_H
- #include <sys/time.h>
- #endif
diff --git a/base/third_party/libevent/compat/sys/_libevent_time.h b/base/third_party/libevent/compat/sys/_libevent_time.h
deleted file mode 100644
index 8cabb0d..0000000
--- a/base/third_party/libevent/compat/sys/_libevent_time.h
+++ /dev/null
@@ -1,163 +0,0 @@
-/*	$OpenBSD: time.h,v 1.11 2000/10/10 13:36:48 itojun Exp $	*/
-/*	$NetBSD: time.h,v 1.18 1996/04/23 10:29:33 mycroft Exp $	*/
-
-/*
- * Copyright (c) 1982, 1986, 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- *	@(#)time.h	8.2 (Berkeley) 7/10/94
- */
-
-#ifndef _SYS_TIME_H_
-#define _SYS_TIME_H_
-
-#include <sys/types.h>
-
-/*
- * Structure returned by gettimeofday(2) system call,
- * and used in other calls.
- */
-struct timeval {
-	long	tv_sec;		/* seconds */
-	long	tv_usec;	/* and microseconds */
-};
-
-/*
- * Structure defined by POSIX.1b to be like a timeval.
- */
-struct timespec {
-	time_t	tv_sec;		/* seconds */
-	long	tv_nsec;	/* and nanoseconds */
-};
-
-#define	TIMEVAL_TO_TIMESPEC(tv, ts) {					\
-	(ts)->tv_sec = (tv)->tv_sec;					\
-	(ts)->tv_nsec = (tv)->tv_usec * 1000;				\
-}
-#define	TIMESPEC_TO_TIMEVAL(tv, ts) {					\
-	(tv)->tv_sec = (ts)->tv_sec;					\
-	(tv)->tv_usec = (ts)->tv_nsec / 1000;				\
-}
-
-struct timezone {
-	int	tz_minuteswest;	/* minutes west of Greenwich */
-	int	tz_dsttime;	/* type of dst correction */
-};
-#define	DST_NONE	0	/* not on dst */
-#define	DST_USA		1	/* USA style dst */
-#define	DST_AUST	2	/* Australian style dst */
-#define	DST_WET		3	/* Western European dst */
-#define	DST_MET		4	/* Middle European dst */
-#define	DST_EET		5	/* Eastern European dst */
-#define	DST_CAN		6	/* Canada */
-
-/* Operations on timevals. */
-#define	timerclear(tvp)		(tvp)->tv_sec = (tvp)->tv_usec = 0
-#define	timerisset(tvp)		((tvp)->tv_sec || (tvp)->tv_usec)
-#define	timercmp(tvp, uvp, cmp)						\
-	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
-	    ((tvp)->tv_usec cmp (uvp)->tv_usec) :			\
-	    ((tvp)->tv_sec cmp (uvp)->tv_sec))
-#define	timeradd(tvp, uvp, vvp)						\
-	do {								\
-		(vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec;		\
-		(vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec;	\
-		if ((vvp)->tv_usec >= 1000000) {			\
-			(vvp)->tv_sec++;				\
-			(vvp)->tv_usec -= 1000000;			\
-		}							\
-	} while (0)
-#define	timersub(tvp, uvp, vvp)						\
-	do {								\
-		(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;		\
-		(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;	\
-		if ((vvp)->tv_usec < 0) {				\
-			(vvp)->tv_sec--;				\
-			(vvp)->tv_usec += 1000000;			\
-		}							\
-	} while (0)
-
-/* Operations on timespecs. */
-#define	timespecclear(tsp)		(tsp)->tv_sec = (tsp)->tv_nsec = 0
-#define	timespecisset(tsp)		((tsp)->tv_sec || (tsp)->tv_nsec)
-#define	timespeccmp(tsp, usp, cmp)					\
-	(((tsp)->tv_sec == (usp)->tv_sec) ?				\
-	    ((tsp)->tv_nsec cmp (usp)->tv_nsec) :			\
-	    ((tsp)->tv_sec cmp (usp)->tv_sec))
-#define	timespecadd(tsp, usp, vsp)					\
-	do {								\
-		(vsp)->tv_sec = (tsp)->tv_sec + (usp)->tv_sec;		\
-		(vsp)->tv_nsec = (tsp)->tv_nsec + (usp)->tv_nsec;	\
-		if ((vsp)->tv_nsec >= 1000000000L) {			\
-			(vsp)->tv_sec++;				\
-			(vsp)->tv_nsec -= 1000000000L;			\
-		}							\
-	} while (0)
-#define	timespecsub(tsp, usp, vsp)					\
-	do {								\
-		(vsp)->tv_sec = (tsp)->tv_sec - (usp)->tv_sec;		\
-		(vsp)->tv_nsec = (tsp)->tv_nsec - (usp)->tv_nsec;	\
-		if ((vsp)->tv_nsec < 0) {				\
-			(vsp)->tv_sec--;				\
-			(vsp)->tv_nsec += 1000000000L;			\
-		}							\
-	} while (0)
-
-/*
- * Names of the interval timers, and structure
- * defining a timer setting.
- */
-#define	ITIMER_REAL	0
-#define	ITIMER_VIRTUAL	1
-#define	ITIMER_PROF	2
-
-struct	itimerval {
-	struct	timeval it_interval;	/* timer interval */
-	struct	timeval it_value;	/* current value */
-};
-
-/*
- * Getkerninfo clock information structure
- */
-struct clockinfo {
-	int	hz;		/* clock frequency */
-	int	tick;		/* micro-seconds per hz tick */
-	int	tickadj;	/* clock skew rate for adjtime() */
-	int	stathz;		/* statistics clock frequency */
-	int	profhz;		/* profiling clock frequency */
-};
-
-#define CLOCK_REALTIME	0
-#define CLOCK_VIRTUAL	1
-#define CLOCK_PROF	2
-
-#define TIMER_RELTIME	0x0	/* relative timer */
-#define TIMER_ABSTIME	0x1	/* absolute timer */
-
-/* --- stuff got cut here - niels --- */
-
-#endif /* !_SYS_TIME_H_ */
diff --git a/base/third_party/libevent/compat/sys/queue.h b/base/third_party/libevent/compat/sys/queue.h
deleted file mode 100644
index c0956dd..0000000
--- a/base/third_party/libevent/compat/sys/queue.h
+++ /dev/null
@@ -1,488 +0,0 @@
-/*	$OpenBSD: queue.h,v 1.16 2000/09/07 19:47:59 art Exp $	*/
-/*	$NetBSD: queue.h,v 1.11 1996/05/16 05:17:14 mycroft Exp $	*/
-
-/*
- * Copyright (c) 1991, 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- *	@(#)queue.h	8.5 (Berkeley) 8/20/94
- */
-
-#ifndef	_SYS_QUEUE_H_
-#define	_SYS_QUEUE_H_
-
-/*
- * This file defines five types of data structures: singly-linked lists, 
- * lists, simple queues, tail queues, and circular queues.
- *
- *
- * A singly-linked list is headed by a single forward pointer. The elements
- * are singly linked for minimum space and pointer manipulation overhead at
- * the expense of O(n) removal for arbitrary elements. New elements can be
- * added to the list after an existing element or at the head of the list.
- * Elements being removed from the head of the list should use the explicit
- * macro for this purpose for optimum efficiency. A singly-linked list may
- * only be traversed in the forward direction.  Singly-linked lists are ideal
- * for applications with large datasets and few or no removals or for
- * implementing a LIFO queue.
- *
- * A list is headed by a single forward pointer (or an array of forward
- * pointers for a hash table header). The elements are doubly linked
- * so that an arbitrary element can be removed without a need to
- * traverse the list. New elements can be added to the list before
- * or after an existing element or at the head of the list. A list
- * may only be traversed in the forward direction.
- *
- * A simple queue is headed by a pair of pointers, one the head of the
- * list and the other to the tail of the list. The elements are singly
- * linked to save space, so elements can only be removed from the
- * head of the list. New elements can be added to the list before or after
- * an existing element, at the head of the list, or at the end of the
- * list. A simple queue may only be traversed in the forward direction.
- *
- * A tail queue is headed by a pair of pointers, one to the head of the
- * list and the other to the tail of the list. The elements are doubly
- * linked so that an arbitrary element can be removed without a need to
- * traverse the list. New elements can be added to the list before or
- * after an existing element, at the head of the list, or at the end of
- * the list. A tail queue may be traversed in either direction.
- *
- * A circle queue is headed by a pair of pointers, one to the head of the
- * list and the other to the tail of the list. The elements are doubly
- * linked so that an arbitrary element can be removed without a need to
- * traverse the list. New elements can be added to the list before or after
- * an existing element, at the head of the list, or at the end of the list.
- * A circle queue may be traversed in either direction, but has a more
- * complex end of list detection.
- *
- * For details on the use of these macros, see the queue(3) manual page.
- */
-
-/*
- * Singly-linked List definitions.
- */
-#define SLIST_HEAD(name, type)						\
-struct name {								\
-	struct type *slh_first;	/* first element */			\
-}
- 
-#define	SLIST_HEAD_INITIALIZER(head)					\
-	{ NULL }
-
-#ifndef WIN32
-#define SLIST_ENTRY(type)						\
-struct {								\
-	struct type *sle_next;	/* next element */			\
-}
-#endif
-
-/*
- * Singly-linked List access methods.
- */
-#define	SLIST_FIRST(head)	((head)->slh_first)
-#define	SLIST_END(head)		NULL
-#define	SLIST_EMPTY(head)	(SLIST_FIRST(head) == SLIST_END(head))
-#define	SLIST_NEXT(elm, field)	((elm)->field.sle_next)
-
-#define	SLIST_FOREACH(var, head, field)					\
-	for((var) = SLIST_FIRST(head);					\
-	    (var) != SLIST_END(head);					\
-	    (var) = SLIST_NEXT(var, field))
-
-/*
- * Singly-linked List functions.
- */
-#define	SLIST_INIT(head) {						\
-	SLIST_FIRST(head) = SLIST_END(head);				\
-}
-
-#define	SLIST_INSERT_AFTER(slistelm, elm, field) do {			\
-	(elm)->field.sle_next = (slistelm)->field.sle_next;		\
-	(slistelm)->field.sle_next = (elm);				\
-} while (0)
-
-#define	SLIST_INSERT_HEAD(head, elm, field) do {			\
-	(elm)->field.sle_next = (head)->slh_first;			\
-	(head)->slh_first = (elm);					\
-} while (0)
-
-#define	SLIST_REMOVE_HEAD(head, field) do {				\
-	(head)->slh_first = (head)->slh_first->field.sle_next;		\
-} while (0)
-
-/*
- * List definitions.
- */
-#define LIST_HEAD(name, type)						\
-struct name {								\
-	struct type *lh_first;	/* first element */			\
-}
-
-#define LIST_HEAD_INITIALIZER(head)					\
-	{ NULL }
-
-#define LIST_ENTRY(type)						\
-struct {								\
-	struct type *le_next;	/* next element */			\
-	struct type **le_prev;	/* address of previous next element */	\
-}
-
-/*
- * List access methods
- */
-#define	LIST_FIRST(head)		((head)->lh_first)
-#define	LIST_END(head)			NULL
-#define	LIST_EMPTY(head)		(LIST_FIRST(head) == LIST_END(head))
-#define	LIST_NEXT(elm, field)		((elm)->field.le_next)
-
-#define LIST_FOREACH(var, head, field)					\
-	for((var) = LIST_FIRST(head);					\
-	    (var)!= LIST_END(head);					\
-	    (var) = LIST_NEXT(var, field))
-
-/*
- * List functions.
- */
-#define	LIST_INIT(head) do {						\
-	LIST_FIRST(head) = LIST_END(head);				\
-} while (0)
-
-#define LIST_INSERT_AFTER(listelm, elm, field) do {			\
-	if (((elm)->field.le_next = (listelm)->field.le_next) != NULL)	\
-		(listelm)->field.le_next->field.le_prev =		\
-		    &(elm)->field.le_next;				\
-	(listelm)->field.le_next = (elm);				\
-	(elm)->field.le_prev = &(listelm)->field.le_next;		\
-} while (0)
-
-#define	LIST_INSERT_BEFORE(listelm, elm, field) do {			\
-	(elm)->field.le_prev = (listelm)->field.le_prev;		\
-	(elm)->field.le_next = (listelm);				\
-	*(listelm)->field.le_prev = (elm);				\
-	(listelm)->field.le_prev = &(elm)->field.le_next;		\
-} while (0)
-
-#define LIST_INSERT_HEAD(head, elm, field) do {				\
-	if (((elm)->field.le_next = (head)->lh_first) != NULL)		\
-		(head)->lh_first->field.le_prev = &(elm)->field.le_next;\
-	(head)->lh_first = (elm);					\
-	(elm)->field.le_prev = &(head)->lh_first;			\
-} while (0)
-
-#define LIST_REMOVE(elm, field) do {					\
-	if ((elm)->field.le_next != NULL)				\
-		(elm)->field.le_next->field.le_prev =			\
-		    (elm)->field.le_prev;				\
-	*(elm)->field.le_prev = (elm)->field.le_next;			\
-} while (0)
-
-#define LIST_REPLACE(elm, elm2, field) do {				\
-	if (((elm2)->field.le_next = (elm)->field.le_next) != NULL)	\
-		(elm2)->field.le_next->field.le_prev =			\
-		    &(elm2)->field.le_next;				\
-	(elm2)->field.le_prev = (elm)->field.le_prev;			\
-	*(elm2)->field.le_prev = (elm2);				\
-} while (0)
-
-/*
- * Simple queue definitions.
- */
-#define SIMPLEQ_HEAD(name, type)					\
-struct name {								\
-	struct type *sqh_first;	/* first element */			\
-	struct type **sqh_last;	/* addr of last next element */		\
-}
-
-#define SIMPLEQ_HEAD_INITIALIZER(head)					\
-	{ NULL, &(head).sqh_first }
-
-#define SIMPLEQ_ENTRY(type)						\
-struct {								\
-	struct type *sqe_next;	/* next element */			\
-}
-
-/*
- * Simple queue access methods.
- */
-#define	SIMPLEQ_FIRST(head)	    ((head)->sqh_first)
-#define	SIMPLEQ_END(head)	    NULL
-#define	SIMPLEQ_EMPTY(head)	    (SIMPLEQ_FIRST(head) == SIMPLEQ_END(head))
-#define	SIMPLEQ_NEXT(elm, field)    ((elm)->field.sqe_next)
-
-#define SIMPLEQ_FOREACH(var, head, field)				\
-	for((var) = SIMPLEQ_FIRST(head);				\
-	    (var) != SIMPLEQ_END(head);					\
-	    (var) = SIMPLEQ_NEXT(var, field))
-
-/*
- * Simple queue functions.
- */
-#define	SIMPLEQ_INIT(head) do {						\
-	(head)->sqh_first = NULL;					\
-	(head)->sqh_last = &(head)->sqh_first;				\
-} while (0)
-
-#define SIMPLEQ_INSERT_HEAD(head, elm, field) do {			\
-	if (((elm)->field.sqe_next = (head)->sqh_first) == NULL)	\
-		(head)->sqh_last = &(elm)->field.sqe_next;		\
-	(head)->sqh_first = (elm);					\
-} while (0)
-
-#define SIMPLEQ_INSERT_TAIL(head, elm, field) do {			\
-	(elm)->field.sqe_next = NULL;					\
-	*(head)->sqh_last = (elm);					\
-	(head)->sqh_last = &(elm)->field.sqe_next;			\
-} while (0)
-
-#define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do {		\
-	if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\
-		(head)->sqh_last = &(elm)->field.sqe_next;		\
-	(listelm)->field.sqe_next = (elm);				\
-} while (0)
-
-#define SIMPLEQ_REMOVE_HEAD(head, elm, field) do {			\
-	if (((head)->sqh_first = (elm)->field.sqe_next) == NULL)	\
-		(head)->sqh_last = &(head)->sqh_first;			\
-} while (0)
-
-/*
- * Tail queue definitions.
- */
-#define TAILQ_HEAD(name, type)						\
-struct name {								\
-	struct type *tqh_first;	/* first element */			\
-	struct type **tqh_last;	/* addr of last next element */		\
-}
-
-#define TAILQ_HEAD_INITIALIZER(head)					\
-	{ NULL, &(head).tqh_first }
-
-#define TAILQ_ENTRY(type)						\
-struct {								\
-	struct type *tqe_next;	/* next element */			\
-	struct type **tqe_prev;	/* address of previous next element */	\
-}
-
-/* 
- * tail queue access methods 
- */
-#define	TAILQ_FIRST(head)		((head)->tqh_first)
-#define	TAILQ_END(head)			NULL
-#define	TAILQ_NEXT(elm, field)		((elm)->field.tqe_next)
-#define TAILQ_LAST(head, headname)					\
-	(*(((struct headname *)((head)->tqh_last))->tqh_last))
-/* XXX */
-#define TAILQ_PREV(elm, headname, field)				\
-	(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
-#define	TAILQ_EMPTY(head)						\
-	(TAILQ_FIRST(head) == TAILQ_END(head))
-
-#define TAILQ_FOREACH(var, head, field)					\
-	for((var) = TAILQ_FIRST(head);					\
-	    (var) != TAILQ_END(head);					\
-	    (var) = TAILQ_NEXT(var, field))
-
-#define TAILQ_FOREACH_REVERSE(var, head, field, headname)		\
-	for((var) = TAILQ_LAST(head, headname);				\
-	    (var) != TAILQ_END(head);					\
-	    (var) = TAILQ_PREV(var, headname, field))
-
-/*
- * Tail queue functions.
- */
-#define	TAILQ_INIT(head) do {						\
-	(head)->tqh_first = NULL;					\
-	(head)->tqh_last = &(head)->tqh_first;				\
-} while (0)
-
-#define TAILQ_INSERT_HEAD(head, elm, field) do {			\
-	if (((elm)->field.tqe_next = (head)->tqh_first) != NULL)	\
-		(head)->tqh_first->field.tqe_prev =			\
-		    &(elm)->field.tqe_next;				\
-	else								\
-		(head)->tqh_last = &(elm)->field.tqe_next;		\
-	(head)->tqh_first = (elm);					\
-	(elm)->field.tqe_prev = &(head)->tqh_first;			\
-} while (0)
-
-#define TAILQ_INSERT_TAIL(head, elm, field) do {			\
-	(elm)->field.tqe_next = NULL;					\
-	(elm)->field.tqe_prev = (head)->tqh_last;			\
-	*(head)->tqh_last = (elm);					\
-	(head)->tqh_last = &(elm)->field.tqe_next;			\
-} while (0)
-
-#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do {		\
-	if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\
-		(elm)->field.tqe_next->field.tqe_prev =			\
-		    &(elm)->field.tqe_next;				\
-	else								\
-		(head)->tqh_last = &(elm)->field.tqe_next;		\
-	(listelm)->field.tqe_next = (elm);				\
-	(elm)->field.tqe_prev = &(listelm)->field.tqe_next;		\
-} while (0)
-
-#define	TAILQ_INSERT_BEFORE(listelm, elm, field) do {			\
-	(elm)->field.tqe_prev = (listelm)->field.tqe_prev;		\
-	(elm)->field.tqe_next = (listelm);				\
-	*(listelm)->field.tqe_prev = (elm);				\
-	(listelm)->field.tqe_prev = &(elm)->field.tqe_next;		\
-} while (0)
-
-#define TAILQ_REMOVE(head, elm, field) do {				\
-	if (((elm)->field.tqe_next) != NULL)				\
-		(elm)->field.tqe_next->field.tqe_prev =			\
-		    (elm)->field.tqe_prev;				\
-	else								\
-		(head)->tqh_last = (elm)->field.tqe_prev;		\
-	*(elm)->field.tqe_prev = (elm)->field.tqe_next;			\
-} while (0)
-
-#define TAILQ_REPLACE(head, elm, elm2, field) do {			\
-	if (((elm2)->field.tqe_next = (elm)->field.tqe_next) != NULL)	\
-		(elm2)->field.tqe_next->field.tqe_prev =		\
-		    &(elm2)->field.tqe_next;				\
-	else								\
-		(head)->tqh_last = &(elm2)->field.tqe_next;		\
-	(elm2)->field.tqe_prev = (elm)->field.tqe_prev;			\
-	*(elm2)->field.tqe_prev = (elm2);				\
-} while (0)
-
-/*
- * Circular queue definitions.
- */
-#define CIRCLEQ_HEAD(name, type)					\
-struct name {								\
-	struct type *cqh_first;		/* first element */		\
-	struct type *cqh_last;		/* last element */		\
-}
-
-#define CIRCLEQ_HEAD_INITIALIZER(head)					\
-	{ CIRCLEQ_END(&head), CIRCLEQ_END(&head) }
-
-#define CIRCLEQ_ENTRY(type)						\
-struct {								\
-	struct type *cqe_next;		/* next element */		\
-	struct type *cqe_prev;		/* previous element */		\
-}
-
-/*
- * Circular queue access methods 
- */
-#define	CIRCLEQ_FIRST(head)		((head)->cqh_first)
-#define	CIRCLEQ_LAST(head)		((head)->cqh_last)
-#define	CIRCLEQ_END(head)		((void *)(head))
-#define	CIRCLEQ_NEXT(elm, field)	((elm)->field.cqe_next)
-#define	CIRCLEQ_PREV(elm, field)	((elm)->field.cqe_prev)
-#define	CIRCLEQ_EMPTY(head)						\
-	(CIRCLEQ_FIRST(head) == CIRCLEQ_END(head))
-
-#define CIRCLEQ_FOREACH(var, head, field)				\
-	for((var) = CIRCLEQ_FIRST(head);				\
-	    (var) != CIRCLEQ_END(head);					\
-	    (var) = CIRCLEQ_NEXT(var, field))
-
-#define CIRCLEQ_FOREACH_REVERSE(var, head, field)			\
-	for((var) = CIRCLEQ_LAST(head);					\
-	    (var) != CIRCLEQ_END(head);					\
-	    (var) = CIRCLEQ_PREV(var, field))
-
-/*
- * Circular queue functions.
- */
-#define	CIRCLEQ_INIT(head) do {						\
-	(head)->cqh_first = CIRCLEQ_END(head);				\
-	(head)->cqh_last = CIRCLEQ_END(head);				\
-} while (0)
-
-#define CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) do {		\
-	(elm)->field.cqe_next = (listelm)->field.cqe_next;		\
-	(elm)->field.cqe_prev = (listelm);				\
-	if ((listelm)->field.cqe_next == CIRCLEQ_END(head))		\
-		(head)->cqh_last = (elm);				\
-	else								\
-		(listelm)->field.cqe_next->field.cqe_prev = (elm);	\
-	(listelm)->field.cqe_next = (elm);				\
-} while (0)
-
-#define CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) do {		\
-	(elm)->field.cqe_next = (listelm);				\
-	(elm)->field.cqe_prev = (listelm)->field.cqe_prev;		\
-	if ((listelm)->field.cqe_prev == CIRCLEQ_END(head))		\
-		(head)->cqh_first = (elm);				\
-	else								\
-		(listelm)->field.cqe_prev->field.cqe_next = (elm);	\
-	(listelm)->field.cqe_prev = (elm);				\
-} while (0)
-
-#define CIRCLEQ_INSERT_HEAD(head, elm, field) do {			\
-	(elm)->field.cqe_next = (head)->cqh_first;			\
-	(elm)->field.cqe_prev = CIRCLEQ_END(head);			\
-	if ((head)->cqh_last == CIRCLEQ_END(head))			\
-		(head)->cqh_last = (elm);				\
-	else								\
-		(head)->cqh_first->field.cqe_prev = (elm);		\
-	(head)->cqh_first = (elm);					\
-} while (0)
-
-#define CIRCLEQ_INSERT_TAIL(head, elm, field) do {			\
-	(elm)->field.cqe_next = CIRCLEQ_END(head);			\
-	(elm)->field.cqe_prev = (head)->cqh_last;			\
-	if ((head)->cqh_first == CIRCLEQ_END(head))			\
-		(head)->cqh_first = (elm);				\
-	else								\
-		(head)->cqh_last->field.cqe_next = (elm);		\
-	(head)->cqh_last = (elm);					\
-} while (0)
-
-#define	CIRCLEQ_REMOVE(head, elm, field) do {				\
-	if ((elm)->field.cqe_next == CIRCLEQ_END(head))			\
-		(head)->cqh_last = (elm)->field.cqe_prev;		\
-	else								\
-		(elm)->field.cqe_next->field.cqe_prev =			\
-		    (elm)->field.cqe_prev;				\
-	if ((elm)->field.cqe_prev == CIRCLEQ_END(head))			\
-		(head)->cqh_first = (elm)->field.cqe_next;		\
-	else								\
-		(elm)->field.cqe_prev->field.cqe_next =			\
-		    (elm)->field.cqe_next;				\
-} while (0)
-
-#define CIRCLEQ_REPLACE(head, elm, elm2, field) do {			\
-	if (((elm2)->field.cqe_next = (elm)->field.cqe_next) ==		\
-	    CIRCLEQ_END(head))						\
-		(head).cqh_last = (elm2);				\
-	else								\
-		(elm2)->field.cqe_next->field.cqe_prev = (elm2);	\
-	if (((elm2)->field.cqe_prev = (elm)->field.cqe_prev) ==		\
-	    CIRCLEQ_END(head))						\
-		(head).cqh_first = (elm2);				\
-	else								\
-		(elm2)->field.cqe_prev->field.cqe_next = (elm2);	\
-} while (0)
-
-#endif	/* !_SYS_QUEUE_H_ */
diff --git a/base/third_party/libevent/configure.in b/base/third_party/libevent/configure.in
deleted file mode 100644
index 468d774..0000000
--- a/base/third_party/libevent/configure.in
+++ /dev/null
@@ -1,421 +0,0 @@
-dnl configure.in for libevent
-dnl Dug Song <dugsong@monkey.org>
-AC_INIT(event.c)
-
-AM_INIT_AUTOMAKE(libevent,1.4.15)
-AM_CONFIG_HEADER(config.h)
-dnl AM_MAINTAINER_MODE
-
-AC_CONFIG_MACRO_DIR([m4])
-
-AC_CANONICAL_HOST
-
-AC_DEFINE(NUMERIC_VERSION, 0x01040f00, [Numeric representation of the version])
-
-dnl Initialize prefix.
-if test "$prefix" = "NONE"; then
-   prefix="/usr/local"
-fi
-
-dnl Checks for programs.
-AC_PROG_CC
-AC_PROG_INSTALL
-AC_PROG_LN_S
-
-AC_PROG_GCC_TRADITIONAL
-if test "$GCC" = yes ; then
-        CFLAGS="$CFLAGS -Wall"
-        # And disable the strict-aliasing optimization, since it breaks
-        # our sockaddr-handling code in strange ways.
-        CFLAGS="$CFLAGS -fno-strict-aliasing"
-fi
-
-dnl Libevent 1.4 isn't multithreaded, but some of its functions are
-dnl documented to be reentrant.  If you don't define the right macros
-dnl on some platforms, you get non-reentrant versions of the libc
-dnl functinos (like an errno that's shared by all threads).
-AC_MSG_CHECKING([whether we need extra flags to make libc reentrant])
-case $host in
-   *solaris* | *-osf* | *-hpux* )
-     AC_MSG_RESULT([-D_REENTRANT])
-     CFLAGS="$CFLAGS -D_REENTRANT"
-     ;;
-   *-aix* | *-freebsd* | *-darwin* )
-     AC_MSG_RESULT([-D_THREAD_SAFE])
-     CFLAGS="$CFLAGS -D_THREAD_SAFE"
-     ;;
-   *)
-     AC_MSG_RESULT(no)
-     ;;
-esac
-
-AC_ARG_ENABLE(gcc-warnings,
-     AS_HELP_STRING(--enable-gcc-warnings, enable verbose warnings with GCC))
-
-AC_PROG_LIBTOOL
-
-dnl   Uncomment "AC_DISABLE_SHARED" to make shared librraries not get
-dnl   built by default.  You can also turn shared libs on and off from 
-dnl   the command line with --enable-shared and --disable-shared.
-dnl AC_DISABLE_SHARED
-AC_SUBST(LIBTOOL_DEPS)
-
-dnl Checks for libraries.
-AC_CHECK_LIB(socket, socket)
-AC_CHECK_LIB(resolv, inet_aton)
-AC_CHECK_LIB(rt, clock_gettime)
-AC_CHECK_LIB(nsl, inet_ntoa)
-
-dnl Checks for header files.
-AC_HEADER_STDC
-AC_CHECK_HEADERS(fcntl.h stdarg.h inttypes.h stdint.h poll.h signal.h unistd.h sys/epoll.h sys/time.h sys/queue.h sys/event.h sys/param.h sys/ioctl.h sys/select.h sys/devpoll.h port.h netinet/in6.h sys/socket.h)
-if test "x$ac_cv_header_sys_queue_h" = "xyes"; then
-	AC_MSG_CHECKING(for TAILQ_FOREACH in sys/queue.h)
-	AC_EGREP_CPP(yes,
-[
-#include <sys/queue.h>
-#ifdef TAILQ_FOREACH
- yes
-#endif
-],	[AC_MSG_RESULT(yes)
-	 AC_DEFINE(HAVE_TAILQFOREACH, 1,
-		[Define if TAILQ_FOREACH is defined in <sys/queue.h>])],
-	AC_MSG_RESULT(no)
-	)
-fi
-
-if test "x$ac_cv_header_sys_time_h" = "xyes"; then
-	AC_MSG_CHECKING(for timeradd in sys/time.h)
-	AC_EGREP_CPP(yes,
-[
-#include <sys/time.h>
-#ifdef timeradd
- yes
-#endif
-],	[ AC_DEFINE(HAVE_TIMERADD, 1,
-		[Define if timeradd is defined in <sys/time.h>])
-	  AC_MSG_RESULT(yes)] ,AC_MSG_RESULT(no)
-)
-fi
-
-if test "x$ac_cv_header_sys_time_h" = "xyes"; then
-	AC_MSG_CHECKING(for timercmp in sys/time.h)
-	AC_EGREP_CPP(yes,
-[
-#include <sys/time.h>
-#ifdef timercmp
- yes
-#endif
-],	[ AC_DEFINE(HAVE_TIMERCMP, 1,
-		[Define if timercmp is defined in <sys/time.h>])
-	  AC_MSG_RESULT(yes)] ,AC_MSG_RESULT(no)
-)
-fi
-
-if test "x$ac_cv_header_sys_time_h" = "xyes"; then
-	AC_MSG_CHECKING(for timerclear in sys/time.h)
-	AC_EGREP_CPP(yes,
-[
-#include <sys/time.h>
-#ifdef timerclear
- yes
-#endif
-],	[ AC_DEFINE(HAVE_TIMERCLEAR, 1,
-		[Define if timerclear is defined in <sys/time.h>])
-	  AC_MSG_RESULT(yes)] ,AC_MSG_RESULT(no)
-)
-fi
-
-if test "x$ac_cv_header_sys_time_h" = "xyes"; then
-	AC_MSG_CHECKING(for timerisset in sys/time.h)
-	AC_EGREP_CPP(yes,
-[
-#include <sys/time.h>
-#ifdef timerisset
- yes
-#endif
-],	[ AC_DEFINE(HAVE_TIMERISSET, 1,
-		[Define if timerisset is defined in <sys/time.h>])
-	  AC_MSG_RESULT(yes)] ,AC_MSG_RESULT(no)
-)
-fi
-
-dnl - check if the macro WIN32 is defined on this compiler.
-dnl - (this is how we check for a windows version of GCC)
-AC_MSG_CHECKING(for WIN32)
-AC_TRY_COMPILE(,
-	[
-#ifndef WIN32
-die horribly
-#endif
-	],
-	bwin32=true; AC_MSG_RESULT(yes),
-	bwin32=false; AC_MSG_RESULT(no),
-)
-
-AM_CONDITIONAL(BUILD_WIN32, test x$bwin32 = xtrue)
-
-dnl Checks for typedefs, structures, and compiler characteristics.
-AC_C_CONST
-AC_C_INLINE
-AC_HEADER_TIME
-
-dnl Checks for library functions.
-AC_CHECK_FUNCS(gettimeofday vasprintf fcntl clock_gettime strtok_r strsep getaddrinfo getnameinfo strlcpy inet_ntop signal sigaction strtoll issetugid geteuid getegid)
-
-AC_CHECK_SIZEOF(long)
-
-if test "x$ac_cv_func_clock_gettime" = "xyes"; then
-   AC_DEFINE(DNS_USE_CPU_CLOCK_FOR_ID, 1, [Define if clock_gettime is available in libc])
-else
-   AC_DEFINE(DNS_USE_GETTIMEOFDAY_FOR_ID, 1, [Define is no secure id variant is available])
-fi
-
-AC_MSG_CHECKING(for F_SETFD in fcntl.h)
-AC_EGREP_CPP(yes,
-[
-#define _GNU_SOURCE
-#include <fcntl.h>
-#ifdef F_SETFD
-yes
-#endif
-],	[ AC_DEFINE(HAVE_SETFD, 1,
-	      [Define if F_SETFD is defined in <fcntl.h>])
-	  AC_MSG_RESULT(yes) ], AC_MSG_RESULT(no))
-
-needsignal=no
-haveselect=no
-AC_CHECK_FUNCS(select, [haveselect=yes], )
-if test "x$haveselect" = "xyes" ; then
-	AC_LIBOBJ(select)
-	needsignal=yes
-fi
-
-havepoll=no
-AC_CHECK_FUNCS(poll, [havepoll=yes], )
-if test "x$havepoll" = "xyes" ; then
-	AC_LIBOBJ(poll)
-	needsignal=yes
-fi
-
-haveepoll=no
-AC_CHECK_FUNCS(epoll_ctl, [haveepoll=yes], )
-if test "x$haveepoll" = "xyes" ; then
-	AC_DEFINE(HAVE_EPOLL, 1,
-		[Define if your system supports the epoll system calls])
-	AC_LIBOBJ(epoll)
-	needsignal=yes
-fi
-
-havedevpoll=no
-if test "x$ac_cv_header_sys_devpoll_h" = "xyes"; then
-	AC_DEFINE(HAVE_DEVPOLL, 1,
-		    [Define if /dev/poll is available])
-        AC_LIBOBJ(devpoll)
-fi
-
-havekqueue=no
-if test "x$ac_cv_header_sys_event_h" = "xyes"; then
-	AC_CHECK_FUNCS(kqueue, [havekqueue=yes], )
-	if test "x$havekqueue" = "xyes" ; then
-		AC_MSG_CHECKING(for working kqueue)
-		AC_TRY_RUN(
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/event.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <fcntl.h>
-
-int
-main(int argc, char **argv)
-{
-	int kq;
-	int n;
-	int fd[[2]];
-	struct kevent ev;
-	struct timespec ts;
-	char buf[[8000]];
-
-	if (pipe(fd) == -1)
-		exit(1);
-	if (fcntl(fd[[1]], F_SETFL, O_NONBLOCK) == -1)
-		exit(1);
-
-	while ((n = write(fd[[1]], buf, sizeof(buf))) == sizeof(buf))
-		;
-
-        if ((kq = kqueue()) == -1)
-		exit(1);
-
-	memset(&ev, 0, sizeof(ev));
-	ev.ident = fd[[1]];
-	ev.filter = EVFILT_WRITE;
-	ev.flags = EV_ADD | EV_ENABLE;
-	n = kevent(kq, &ev, 1, NULL, 0, NULL);
-	if (n == -1)
-		exit(1);
-
-	read(fd[[0]], buf, sizeof(buf));
-
-	ts.tv_sec = 0;
-	ts.tv_nsec = 0;
-	n = kevent(kq, NULL, 0, &ev, 1, &ts);
-	if (n == -1 || n == 0)
-		exit(1);
-
-	exit(0);
-}, [AC_MSG_RESULT(yes)
-    AC_DEFINE(HAVE_WORKING_KQUEUE, 1,
-		[Define if kqueue works correctly with pipes])
-    AC_LIBOBJ(kqueue)], AC_MSG_RESULT(no), AC_MSG_RESULT(no))
-	fi
-fi
-
-haveepollsyscall=no
-if test "x$ac_cv_header_sys_epoll_h" = "xyes"; then
-	if test "x$haveepoll" = "xno" ; then
-		AC_MSG_CHECKING(for epoll system call)
-		AC_TRY_RUN(
-#include <stdint.h>
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/syscall.h>
-#include <sys/epoll.h>
-#include <unistd.h>
-
-int
-epoll_create(int size)
-{
-	return (syscall(__NR_epoll_create, size));
-}
-
-int
-main(int argc, char **argv)
-{
-	int epfd;
-
-	epfd = epoll_create(256);
-	exit (epfd == -1 ? 1 : 0);
-}, [AC_MSG_RESULT(yes)
-    AC_DEFINE(HAVE_EPOLL, 1,
-	[Define if your system supports the epoll system calls])
-    needsignal=yes
-    AC_LIBOBJ(epoll_sub)
-    AC_LIBOBJ(epoll)], AC_MSG_RESULT(no), AC_MSG_RESULT(no))
-	fi
-fi
-
-haveeventports=no
-AC_CHECK_FUNCS(port_create, [haveeventports=yes], )
-if test "x$haveeventports" = "xyes" ; then
-	AC_DEFINE(HAVE_EVENT_PORTS, 1,
-		[Define if your system supports event ports])
-	AC_LIBOBJ(evport)
-	needsignal=yes
-fi
-if test "x$bwin32" = "xtrue"; then
-	needsignal=yes
-fi
-if test "x$bwin32" = "xtrue"; then
-	needsignal=yes
-fi
-if test "x$needsignal" = "xyes" ; then
-	AC_LIBOBJ(signal)
-fi
-
-AC_TYPE_PID_T
-AC_TYPE_SIZE_T
-AC_CHECK_TYPES([uint64_t, uint32_t, uint16_t, uint8_t], , ,
-[#ifdef HAVE_STDINT_H
-#include <stdint.h>
-#elif defined(HAVE_INTTYPES_H)
-#include <inttypes.h>
-#endif
-#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif])
-AC_CHECK_TYPES([fd_mask], , ,
-[#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif
-#ifdef HAVE_SELECT_H
-#include <select.h>
-#endif])
-
-AC_CHECK_SIZEOF(long long)
-AC_CHECK_SIZEOF(int)
-AC_CHECK_SIZEOF(short)
-AC_CHECK_TYPES([struct in6_addr], , ,
-[#ifdef WIN32
-#include <winsock2.h>
-#else
-#include <sys/types.h>
-#include <netinet/in.h>
-#include <sys/socket.h>
-#endif
-#ifdef HAVE_NETINET_IN6_H
-#include <netinet/in6.h>
-#endif])
-
-AC_MSG_CHECKING([for socklen_t])
-AC_TRY_COMPILE([
- #include <sys/types.h>
- #include <sys/socket.h>],
-  [socklen_t x;],
-  AC_MSG_RESULT([yes]),
-  [AC_MSG_RESULT([no])
-  AC_DEFINE(socklen_t, unsigned int,
-	[Define to unsigned int if you dont have it])]
-)
-
-AC_MSG_CHECKING([whether our compiler supports __func__])
-AC_TRY_COMPILE([],
- [ const char *cp = __func__; ],
- AC_MSG_RESULT([yes]),
- AC_MSG_RESULT([no])
- AC_MSG_CHECKING([whether our compiler supports __FUNCTION__])
- AC_TRY_COMPILE([],
-   [ const char *cp = __FUNCTION__; ],
-   AC_MSG_RESULT([yes])
-   AC_DEFINE(__func__, __FUNCTION__,
-         [Define to appropriate substitue if compiler doesnt have __func__]),
-   AC_MSG_RESULT([no])
-   AC_DEFINE(__func__, __FILE__,
-         [Define to appropriate substitue if compiler doesnt have __func__])))
-
-
-# Add some more warnings which we use in development but not in the
-# released versions.  (Some relevant gcc versions can't handle these.)
-if test x$enable_gcc_warnings = xyes; then
-
-  AC_COMPILE_IFELSE(AC_LANG_PROGRAM([], [
-#if !defined(__GNUC__) || (__GNUC__ < 4)
-#error
-#endif]), have_gcc4=yes, have_gcc4=no)
-
-  AC_COMPILE_IFELSE(AC_LANG_PROGRAM([], [
-#if !defined(__GNUC__) || (__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)
-#error
-#endif]), have_gcc42=yes, have_gcc42=no)
-
-  CFLAGS="$CFLAGS -W -Wfloat-equal -Wundef -Wpointer-arith -Wstrict-prototypes -Wmissing-prototypes -Wwrite-strings -Wredundant-decls -Wchar-subscripts -Wcomment -Wformat=2 -Wwrite-strings -Wmissing-declarations -Wredundant-decls -Wnested-externs -Wbad-function-cast -Wswitch-enum -Werror"
-  CFLAGS="$CFLAGS -Wno-unused-parameter -Wno-sign-compare -Wstrict-aliasing"
-
-  if test x$have_gcc4 = xyes ; then 
-    # These warnings break gcc 3.3.5 and work on gcc 4.0.2
-    CFLAGS="$CFLAGS -Winit-self -Wmissing-field-initializers -Wdeclaration-after-statement"
-    #CFLAGS="$CFLAGS -Wold-style-definition"
-  fi
-
-  if test x$have_gcc42 = xyes ; then 
-    # These warnings break gcc 4.0.2 and work on gcc 4.2
-    CFLAGS="$CFLAGS -Waddress -Wnormalized=id -Woverride-init"
-  fi
-
-##This will break the world on some 64-bit architectures
-# CFLAGS="$CFLAGS -Winline"
-
-fi
-
-AC_OUTPUT(Makefile test/Makefile sample/Makefile)
diff --git a/base/third_party/libevent/devpoll.c b/base/third_party/libevent/devpoll.c
deleted file mode 100644
index 2d34ae3..0000000
--- a/base/third_party/libevent/devpoll.c
+++ /dev/null
@@ -1,417 +0,0 @@
-/*
- * Copyright 2000-2004 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <sys/types.h>
-#include <sys/resource.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#else
-#include <sys/_libevent_time.h>
-#endif
-#include <sys/queue.h>
-#include <sys/devpoll.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <assert.h>
-
-#include "event.h"
-#include "event-internal.h"
-#include "evsignal.h"
-#include "log.h"
-
-/* due to limitations in the devpoll interface, we need to keep track of
- * all file descriptors outself.
- */
-struct evdevpoll {
-	struct event *evread;
-	struct event *evwrite;
-};
-
-struct devpollop {
-	struct evdevpoll *fds;
-	int nfds;
-	struct pollfd *events;
-	int nevents;
-	int dpfd;
-	struct pollfd *changes;
-	int nchanges;
-};
-
-static void *devpoll_init	(struct event_base *);
-static int devpoll_add	(void *, struct event *);
-static int devpoll_del	(void *, struct event *);
-static int devpoll_dispatch	(struct event_base *, void *, struct timeval *);
-static void devpoll_dealloc	(struct event_base *, void *);
-
-const struct eventop devpollops = {
-	"devpoll",
-	devpoll_init,
-	devpoll_add,
-	devpoll_del,
-	devpoll_dispatch,
-	devpoll_dealloc,
-	1 /* need reinit */
-};
-
-#define NEVENT	32000
-
-static int
-devpoll_commit(struct devpollop *devpollop)
-{
-	/*
-	 * Due to a bug in Solaris, we have to use pwrite with an offset of 0.
-	 * Write is limited to 2GB of data, until it will fail.
-	 */
-	if (pwrite(devpollop->dpfd, devpollop->changes,
-		sizeof(struct pollfd) * devpollop->nchanges, 0) == -1)
-		return(-1);
-
-	devpollop->nchanges = 0;
-	return(0);
-}
-
-static int
-devpoll_queue(struct devpollop *devpollop, int fd, int events) {
-	struct pollfd *pfd;
-
-	if (devpollop->nchanges >= devpollop->nevents) {
-		/*
-		 * Change buffer is full, must commit it to /dev/poll before 
-		 * adding more 
-		 */
-		if (devpoll_commit(devpollop) != 0)
-			return(-1);
-	}
-
-	pfd = &devpollop->changes[devpollop->nchanges++];
-	pfd->fd = fd;
-	pfd->events = events;
-	pfd->revents = 0;
-
-	return(0);
-}
-
-static void *
-devpoll_init(struct event_base *base)
-{
-	int dpfd, nfiles = NEVENT;
-	struct rlimit rl;
-	struct devpollop *devpollop;
-
-	/* Disable devpoll when this environment variable is set */
-	if (evutil_getenv("EVENT_NODEVPOLL"))
-		return (NULL);
-
-	if (!(devpollop = calloc(1, sizeof(struct devpollop))))
-		return (NULL);
-
-	if (getrlimit(RLIMIT_NOFILE, &rl) == 0 &&
-	    rl.rlim_cur != RLIM_INFINITY)
-		nfiles = rl.rlim_cur;
-
-	/* Initialize the kernel queue */
-	if ((dpfd = open("/dev/poll", O_RDWR)) == -1) {
-                event_warn("open: /dev/poll");
-		free(devpollop);
-		return (NULL);
-	}
-
-	devpollop->dpfd = dpfd;
-
-	/* Initialize fields */
-	devpollop->events = calloc(nfiles, sizeof(struct pollfd));
-	if (devpollop->events == NULL) {
-		free(devpollop);
-		close(dpfd);
-		return (NULL);
-	}
-	devpollop->nevents = nfiles;
-
-	devpollop->fds = calloc(nfiles, sizeof(struct evdevpoll));
-	if (devpollop->fds == NULL) {
-		free(devpollop->events);
-		free(devpollop);
-		close(dpfd);
-		return (NULL);
-	}
-	devpollop->nfds = nfiles;
-
-	devpollop->changes = calloc(nfiles, sizeof(struct pollfd));
-	if (devpollop->changes == NULL) {
-		free(devpollop->fds);
-		free(devpollop->events);
-		free(devpollop);
-		close(dpfd);
-		return (NULL);
-	}
-
-	evsignal_init(base);
-
-	return (devpollop);
-}
-
-static int
-devpoll_recalc(struct event_base *base, void *arg, int max)
-{
-	struct devpollop *devpollop = arg;
-
-	if (max >= devpollop->nfds) {
-		struct evdevpoll *fds;
-		int nfds;
-
-		nfds = devpollop->nfds;
-		while (nfds <= max)
-			nfds <<= 1;
-
-		fds = realloc(devpollop->fds, nfds * sizeof(struct evdevpoll));
-		if (fds == NULL) {
-			event_warn("realloc");
-			return (-1);
-		}
-		devpollop->fds = fds;
-		memset(fds + devpollop->nfds, 0,
-		    (nfds - devpollop->nfds) * sizeof(struct evdevpoll));
-		devpollop->nfds = nfds;
-	}
-
-	return (0);
-}
-
-static int
-devpoll_dispatch(struct event_base *base, void *arg, struct timeval *tv)
-{
-	struct devpollop *devpollop = arg;
-	struct pollfd *events = devpollop->events;
-	struct dvpoll dvp;
-	struct evdevpoll *evdp;
-	int i, res, timeout = -1;
-
-	if (devpollop->nchanges)
-		devpoll_commit(devpollop);
-
-	if (tv != NULL)
-		timeout = tv->tv_sec * 1000 + (tv->tv_usec + 999) / 1000;
-
-	dvp.dp_fds = devpollop->events;
-	dvp.dp_nfds = devpollop->nevents;
-	dvp.dp_timeout = timeout;
-
-	res = ioctl(devpollop->dpfd, DP_POLL, &dvp);
-
-	if (res == -1) {
-		if (errno != EINTR) {
-			event_warn("ioctl: DP_POLL");
-			return (-1);
-		}
-
-		evsignal_process(base);
-		return (0);
-	} else if (base->sig.evsignal_caught) {
-		evsignal_process(base);
-	}
-
-	event_debug(("%s: devpoll_wait reports %d", __func__, res));
-
-	for (i = 0; i < res; i++) {
-		int which = 0;
-		int what = events[i].revents;
-		struct event *evread = NULL, *evwrite = NULL;
-
-		assert(events[i].fd < devpollop->nfds);
-		evdp = &devpollop->fds[events[i].fd];
-   
-                if (what & POLLHUP)
-                        what |= POLLIN | POLLOUT;
-                else if (what & POLLERR)
-                        what |= POLLIN | POLLOUT;
-
-		if (what & POLLIN) {
-			evread = evdp->evread;
-			which |= EV_READ;
-		}
-
-		if (what & POLLOUT) {
-			evwrite = evdp->evwrite;
-			which |= EV_WRITE;
-		}
-
-		if (!which)
-			continue;
-
-		if (evread != NULL && !(evread->ev_events & EV_PERSIST))
-			event_del(evread);
-		if (evwrite != NULL && evwrite != evread &&
-		    !(evwrite->ev_events & EV_PERSIST))
-			event_del(evwrite);
-
-		if (evread != NULL)
-			event_active(evread, EV_READ, 1);
-		if (evwrite != NULL)
-			event_active(evwrite, EV_WRITE, 1);
-	}
-
-	return (0);
-}
-
-
-static int
-devpoll_add(void *arg, struct event *ev)
-{
-	struct devpollop *devpollop = arg;
-	struct evdevpoll *evdp;
-	int fd, events;
-
-	if (ev->ev_events & EV_SIGNAL)
-		return (evsignal_add(ev));
-
-	fd = ev->ev_fd;
-	if (fd >= devpollop->nfds) {
-		/* Extend the file descriptor array as necessary */
-		if (devpoll_recalc(ev->ev_base, devpollop, fd) == -1)
-			return (-1);
-	}
-	evdp = &devpollop->fds[fd];
-
-	/* 
-	 * It's not necessary to OR the existing read/write events that we
-	 * are currently interested in with the new event we are adding.
-	 * The /dev/poll driver ORs any new events with the existing events
-	 * that it has cached for the fd.
-	 */
-
-	events = 0;
-	if (ev->ev_events & EV_READ) {
-		if (evdp->evread && evdp->evread != ev) {
-		   /* There is already a different read event registered */
-		   return(-1);
-		}
-		events |= POLLIN;
-	}
-
-	if (ev->ev_events & EV_WRITE) {
-		if (evdp->evwrite && evdp->evwrite != ev) {
-		   /* There is already a different write event registered */
-		   return(-1);
-		}
-		events |= POLLOUT;
-	}
-
-	if (devpoll_queue(devpollop, fd, events) != 0)
-		return(-1);
-
-	/* Update events responsible */
-	if (ev->ev_events & EV_READ)
-		evdp->evread = ev;
-	if (ev->ev_events & EV_WRITE)
-		evdp->evwrite = ev;
-
-	return (0);
-}
-
-static int
-devpoll_del(void *arg, struct event *ev)
-{
-	struct devpollop *devpollop = arg;
-	struct evdevpoll *evdp;
-	int fd, events;
-	int needwritedelete = 1, needreaddelete = 1;
-
-	if (ev->ev_events & EV_SIGNAL)
-		return (evsignal_del(ev));
-
-	fd = ev->ev_fd;
-	if (fd >= devpollop->nfds)
-		return (0);
-	evdp = &devpollop->fds[fd];
-
-	events = 0;
-	if (ev->ev_events & EV_READ)
-		events |= POLLIN;
-	if (ev->ev_events & EV_WRITE)
-		events |= POLLOUT;
-
-	/*
-	 * The only way to remove an fd from the /dev/poll monitored set is
-	 * to use POLLREMOVE by itself.  This removes ALL events for the fd 
-	 * provided so if we care about two events and are only removing one 
-	 * we must re-add the other event after POLLREMOVE.
-	 */
-
-	if (devpoll_queue(devpollop, fd, POLLREMOVE) != 0)
-		return(-1);
-
-	if ((events & (POLLIN|POLLOUT)) != (POLLIN|POLLOUT)) {
-		/*
-		 * We're not deleting all events, so we must resubmit the
-		 * event that we are still interested in if one exists.
-		 */
-
-		if ((events & POLLIN) && evdp->evwrite != NULL) {
-			/* Deleting read, still care about write */
-			devpoll_queue(devpollop, fd, POLLOUT);
-			needwritedelete = 0;
-		} else if ((events & POLLOUT) && evdp->evread != NULL) {
-			/* Deleting write, still care about read */
-			devpoll_queue(devpollop, fd, POLLIN);
-			needreaddelete = 0;
-		}
-	}
-
-	if (needreaddelete)
-		evdp->evread = NULL;
-	if (needwritedelete)
-		evdp->evwrite = NULL;
-
-	return (0);
-}
-
-static void
-devpoll_dealloc(struct event_base *base, void *arg)
-{
-	struct devpollop *devpollop = arg;
-
-	evsignal_dealloc(base);
-	if (devpollop->fds)
-		free(devpollop->fds);
-	if (devpollop->events)
-		free(devpollop->events);
-	if (devpollop->changes)
-		free(devpollop->changes);
-	if (devpollop->dpfd >= 0)
-		close(devpollop->dpfd);
-
-	memset(devpollop, 0, sizeof(struct devpollop));
-	free(devpollop);
-}
diff --git a/base/third_party/libevent/epoll.c b/base/third_party/libevent/epoll.c
deleted file mode 100644
index 4387ef8..0000000
--- a/base/third_party/libevent/epoll.c
+++ /dev/null
@@ -1,377 +0,0 @@
-/*
- * Copyright 2000-2003 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <sys/resource.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#else
-#include <sys/_libevent_time.h>
-#endif
-#include <sys/queue.h>
-#include <sys/epoll.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <errno.h>
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif
-
-#include "event.h"
-#include "event-internal.h"
-#include "evsignal.h"
-#include "log.h"
-
-/* due to limitations in the epoll interface, we need to keep track of
- * all file descriptors outself.
- */
-struct evepoll {
-	struct event *evread;
-	struct event *evwrite;
-};
-
-struct epollop {
-	struct evepoll *fds;
-	int nfds;
-	struct epoll_event *events;
-	int nevents;
-	int epfd;
-};
-
-static void *epoll_init	(struct event_base *);
-static int epoll_add	(void *, struct event *);
-static int epoll_del	(void *, struct event *);
-static int epoll_dispatch	(struct event_base *, void *, struct timeval *);
-static void epoll_dealloc	(struct event_base *, void *);
-
-const struct eventop epollops = {
-	"epoll",
-	epoll_init,
-	epoll_add,
-	epoll_del,
-	epoll_dispatch,
-	epoll_dealloc,
-	1 /* need reinit */
-};
-
-#ifdef HAVE_SETFD
-#define FD_CLOSEONEXEC(x) do { \
-        if (fcntl(x, F_SETFD, 1) == -1) \
-                event_warn("fcntl(%d, F_SETFD)", x); \
-} while (0)
-#else
-#define FD_CLOSEONEXEC(x)
-#endif
-
-/* On Linux kernels at least up to 2.6.24.4, epoll can't handle timeout
- * values bigger than (LONG_MAX - 999ULL)/HZ.  HZ in the wild can be
- * as big as 1000, and LONG_MAX can be as small as (1<<31)-1, so the
- * largest number of msec we can support here is 2147482.  Let's
- * round that down by 47 seconds.
- */
-#define MAX_EPOLL_TIMEOUT_MSEC (35*60*1000)
-
-#define INITIAL_NFILES 32
-#define INITIAL_NEVENTS 32
-#define MAX_NEVENTS 4096
-
-static void *
-epoll_init(struct event_base *base)
-{
-	int epfd;
-	struct epollop *epollop;
-
-	/* Disable epollueue when this environment variable is set */
-	if (evutil_getenv("EVENT_NOEPOLL"))
-		return (NULL);
-
-	/* Initalize the kernel queue */
-	if ((epfd = epoll_create(32000)) == -1) {
-		if (errno != ENOSYS)
-			event_warn("epoll_create");
-		return (NULL);
-	}
-
-	FD_CLOSEONEXEC(epfd);
-
-	if (!(epollop = calloc(1, sizeof(struct epollop))))
-		return (NULL);
-
-	epollop->epfd = epfd;
-
-	/* Initalize fields */
-	epollop->events = malloc(INITIAL_NEVENTS * sizeof(struct epoll_event));
-	if (epollop->events == NULL) {
-		free(epollop);
-		return (NULL);
-	}
-	epollop->nevents = INITIAL_NEVENTS;
-
-	epollop->fds = calloc(INITIAL_NFILES, sizeof(struct evepoll));
-	if (epollop->fds == NULL) {
-		free(epollop->events);
-		free(epollop);
-		return (NULL);
-	}
-	epollop->nfds = INITIAL_NFILES;
-
-	evsignal_init(base);
-
-	return (epollop);
-}
-
-static int
-epoll_recalc(struct event_base *base, void *arg, int max)
-{
-	struct epollop *epollop = arg;
-
-	if (max >= epollop->nfds) {
-		struct evepoll *fds;
-		int nfds;
-
-		nfds = epollop->nfds;
-		while (nfds <= max)
-			nfds <<= 1;
-
-		fds = realloc(epollop->fds, nfds * sizeof(struct evepoll));
-		if (fds == NULL) {
-			event_warn("realloc");
-			return (-1);
-		}
-		epollop->fds = fds;
-		memset(fds + epollop->nfds, 0,
-		    (nfds - epollop->nfds) * sizeof(struct evepoll));
-		epollop->nfds = nfds;
-	}
-
-	return (0);
-}
-
-static int
-epoll_dispatch(struct event_base *base, void *arg, struct timeval *tv)
-{
-	struct epollop *epollop = arg;
-	struct epoll_event *events = epollop->events;
-	struct evepoll *evep;
-	int i, res, timeout = -1;
-
-	if (tv != NULL)
-		timeout = tv->tv_sec * 1000 + (tv->tv_usec + 999) / 1000;
-
-	if (timeout > MAX_EPOLL_TIMEOUT_MSEC) {
-		/* Linux kernels can wait forever if the timeout is too big;
-		 * see comment on MAX_EPOLL_TIMEOUT_MSEC. */
-		timeout = MAX_EPOLL_TIMEOUT_MSEC;
-	}
-
-	res = epoll_wait(epollop->epfd, events, epollop->nevents, timeout);
-
-	if (res == -1) {
-		if (errno != EINTR) {
-			event_warn("epoll_wait");
-			return (-1);
-		}
-
-		evsignal_process(base);
-		return (0);
-	} else if (base->sig.evsignal_caught) {
-		evsignal_process(base);
-	}
-
-	event_debug(("%s: epoll_wait reports %d", __func__, res));
-
-	for (i = 0; i < res; i++) {
-		int what = events[i].events;
-		struct event *evread = NULL, *evwrite = NULL;
-		int fd = events[i].data.fd;
-
-		if (fd < 0 || fd >= epollop->nfds)
-			continue;
-		evep = &epollop->fds[fd];
-
-		if (what & (EPOLLHUP|EPOLLERR)) {
-			evread = evep->evread;
-			evwrite = evep->evwrite;
-		} else {
-			if (what & EPOLLIN) {
-				evread = evep->evread;
-			}
-
-			if (what & EPOLLOUT) {
-				evwrite = evep->evwrite;
-			}
-		}
-
-		if (!(evread||evwrite))
-			continue;
-
-		if (evread != NULL)
-			event_active(evread, EV_READ, 1);
-		if (evwrite != NULL)
-			event_active(evwrite, EV_WRITE, 1);
-	}
-
-	if (res == epollop->nevents && epollop->nevents < MAX_NEVENTS) {
-		/* We used all of the event space this time.  We should
-		   be ready for more events next time. */
-		int new_nevents = epollop->nevents * 2;
-		struct epoll_event *new_events;
-
-		new_events = realloc(epollop->events,
-		    new_nevents * sizeof(struct epoll_event));
-		if (new_events) {
-			epollop->events = new_events;
-			epollop->nevents = new_nevents;
-		}
-	}
-
-	return (0);
-}
-
-
-static int
-epoll_add(void *arg, struct event *ev)
-{
-	struct epollop *epollop = arg;
-	struct epoll_event epev = {0, {0}};
-	struct evepoll *evep;
-	int fd, op, events;
-
-	if (ev->ev_events & EV_SIGNAL)
-		return (evsignal_add(ev));
-
-	fd = ev->ev_fd;
-	if (fd >= epollop->nfds) {
-		/* Extent the file descriptor array as necessary */
-		if (epoll_recalc(ev->ev_base, epollop, fd) == -1)
-			return (-1);
-	}
-	evep = &epollop->fds[fd];
-	op = EPOLL_CTL_ADD;
-	events = 0;
-	if (evep->evread != NULL) {
-		events |= EPOLLIN;
-		op = EPOLL_CTL_MOD;
-	}
-	if (evep->evwrite != NULL) {
-		events |= EPOLLOUT;
-		op = EPOLL_CTL_MOD;
-	}
-
-	if (ev->ev_events & EV_READ)
-		events |= EPOLLIN;
-	if (ev->ev_events & EV_WRITE)
-		events |= EPOLLOUT;
-
-	epev.data.fd = fd;
-	epev.events = events;
-	if (epoll_ctl(epollop->epfd, op, ev->ev_fd, &epev) == -1)
-			return (-1);
-
-	/* Update events responsible */
-	if (ev->ev_events & EV_READ)
-		evep->evread = ev;
-	if (ev->ev_events & EV_WRITE)
-		evep->evwrite = ev;
-
-	return (0);
-}
-
-static int
-epoll_del(void *arg, struct event *ev)
-{
-	struct epollop *epollop = arg;
-	struct epoll_event epev = {0, {0}};
-	struct evepoll *evep;
-	int fd, events, op;
-	int needwritedelete = 1, needreaddelete = 1;
-
-	if (ev->ev_events & EV_SIGNAL)
-		return (evsignal_del(ev));
-
-	fd = ev->ev_fd;
-	if (fd >= epollop->nfds)
-		return (0);
-	evep = &epollop->fds[fd];
-
-	op = EPOLL_CTL_DEL;
-	events = 0;
-
-	if (ev->ev_events & EV_READ)
-		events |= EPOLLIN;
-	if (ev->ev_events & EV_WRITE)
-		events |= EPOLLOUT;
-
-	if ((events & (EPOLLIN|EPOLLOUT)) != (EPOLLIN|EPOLLOUT)) {
-		if ((events & EPOLLIN) && evep->evwrite != NULL) {
-			needwritedelete = 0;
-			events = EPOLLOUT;
-			op = EPOLL_CTL_MOD;
-		} else if ((events & EPOLLOUT) && evep->evread != NULL) {
-			needreaddelete = 0;
-			events = EPOLLIN;
-			op = EPOLL_CTL_MOD;
-		}
-	}
-
-	epev.events = events;
-	epev.data.fd = fd;
-
-	if (needreaddelete)
-		evep->evread = NULL;
-	if (needwritedelete)
-		evep->evwrite = NULL;
-
-	if (epoll_ctl(epollop->epfd, op, fd, &epev) == -1)
-		return (-1);
-
-	return (0);
-}
-
-static void
-epoll_dealloc(struct event_base *base, void *arg)
-{
-	struct epollop *epollop = arg;
-
-	evsignal_dealloc(base);
-	if (epollop->fds)
-		free(epollop->fds);
-	if (epollop->events)
-		free(epollop->events);
-	if (epollop->epfd >= 0)
-		close(epollop->epfd);
-
-	memset(epollop, 0, sizeof(struct epollop));
-	free(epollop);
-}
diff --git a/base/third_party/libevent/epoll_sub.c b/base/third_party/libevent/epoll_sub.c
deleted file mode 100644
index 431970c..0000000
--- a/base/third_party/libevent/epoll_sub.c
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright 2003 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#include <stdint.h>
-
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/syscall.h>
-#include <sys/epoll.h>
-#include <unistd.h>
-
-int
-epoll_create(int size)
-{
-	return (syscall(__NR_epoll_create, size));
-}
-
-int
-epoll_ctl(int epfd, int op, int fd, struct epoll_event *event)
-{
-
-	return (syscall(__NR_epoll_ctl, epfd, op, fd, event));
-}
-
-int
-epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout)
-{
-	return (syscall(__NR_epoll_wait, epfd, events, maxevents, timeout));
-}
diff --git a/base/third_party/libevent/evbuffer.c b/base/third_party/libevent/evbuffer.c
deleted file mode 100644
index f2179a5..0000000
--- a/base/third_party/libevent/evbuffer.c
+++ /dev/null
@@ -1,455 +0,0 @@
-/*
- * Copyright (c) 2002-2004 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <sys/types.h>
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#ifdef HAVE_STDARG_H
-#include <stdarg.h>
-#endif
-
-#ifdef WIN32
-#include <winsock2.h>
-#endif
-
-#include "evutil.h"
-#include "event.h"
-
-/* prototypes */
-
-void bufferevent_read_pressure_cb(struct evbuffer *, size_t, size_t, void *);
-
-static int
-bufferevent_add(struct event *ev, int timeout)
-{
-	struct timeval tv, *ptv = NULL;
-
-	if (timeout) {
-		evutil_timerclear(&tv);
-		tv.tv_sec = timeout;
-		ptv = &tv;
-	}
-
-	return (event_add(ev, ptv));
-}
-
-/* 
- * This callback is executed when the size of the input buffer changes.
- * We use it to apply back pressure on the reading side.
- */
-
-void
-bufferevent_read_pressure_cb(struct evbuffer *buf, size_t old, size_t now,
-    void *arg) {
-	struct bufferevent *bufev = arg;
-	/* 
-	 * If we are below the watermark then reschedule reading if it's
-	 * still enabled.
-	 */
-	if (bufev->wm_read.high == 0 || now < bufev->wm_read.high) {
-		evbuffer_setcb(buf, NULL, NULL);
-
-		if (bufev->enabled & EV_READ)
-			bufferevent_add(&bufev->ev_read, bufev->timeout_read);
-	}
-}
-
-static void
-bufferevent_readcb(int fd, short event, void *arg)
-{
-	struct bufferevent *bufev = arg;
-	int res = 0;
-	short what = EVBUFFER_READ;
-	size_t len;
-	int howmuch = -1;
-
-	if (event == EV_TIMEOUT) {
-		what |= EVBUFFER_TIMEOUT;
-		goto error;
-	}
-
-	/*
-	 * If we have a high watermark configured then we don't want to
-	 * read more data than would make us reach the watermark.
-	 */
-	if (bufev->wm_read.high != 0) {
-		howmuch = bufev->wm_read.high - EVBUFFER_LENGTH(bufev->input);
-		/* we might have lowered the watermark, stop reading */
-		if (howmuch <= 0) {
-			struct evbuffer *buf = bufev->input;
-			event_del(&bufev->ev_read);
-			evbuffer_setcb(buf,
-			    bufferevent_read_pressure_cb, bufev);
-			return;
-		}
-	}
-
-	res = evbuffer_read(bufev->input, fd, howmuch);
-	if (res == -1) {
-		if (errno == EAGAIN || errno == EINTR)
-			goto reschedule;
-		/* error case */
-		what |= EVBUFFER_ERROR;
-	} else if (res == 0) {
-		/* eof case */
-		what |= EVBUFFER_EOF;
-	}
-
-	if (res <= 0)
-		goto error;
-
-	bufferevent_add(&bufev->ev_read, bufev->timeout_read);
-
-	/* See if this callbacks meets the water marks */
-	len = EVBUFFER_LENGTH(bufev->input);
-	if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
-		return;
-	if (bufev->wm_read.high != 0 && len >= bufev->wm_read.high) {
-		struct evbuffer *buf = bufev->input;
-		event_del(&bufev->ev_read);
-
-		/* Now schedule a callback for us when the buffer changes */
-		evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
-	}
-
-	/* Invoke the user callback - must always be called last */
-	if (bufev->readcb != NULL)
-		(*bufev->readcb)(bufev, bufev->cbarg);
-	return;
-
- reschedule:
-	bufferevent_add(&bufev->ev_read, bufev->timeout_read);
-	return;
-
- error:
-	(*bufev->errorcb)(bufev, what, bufev->cbarg);
-}
-
-static void
-bufferevent_writecb(int fd, short event, void *arg)
-{
-	struct bufferevent *bufev = arg;
-	int res = 0;
-	short what = EVBUFFER_WRITE;
-
-	if (event == EV_TIMEOUT) {
-		what |= EVBUFFER_TIMEOUT;
-		goto error;
-	}
-
-	if (EVBUFFER_LENGTH(bufev->output)) {
-	    res = evbuffer_write(bufev->output, fd);
-	    if (res == -1) {
-#ifndef WIN32
-/*todo. evbuffer uses WriteFile when WIN32 is set. WIN32 system calls do not
- *set errno. thus this error checking is not portable*/
-		    if (errno == EAGAIN ||
-			errno == EINTR ||
-			errno == EINPROGRESS)
-			    goto reschedule;
-		    /* error case */
-		    what |= EVBUFFER_ERROR;
-
-#else
-				goto reschedule;
-#endif
-
-	    } else if (res == 0) {
-		    /* eof case */
-		    what |= EVBUFFER_EOF;
-	    }
-	    if (res <= 0)
-		    goto error;
-	}
-
-	if (EVBUFFER_LENGTH(bufev->output) != 0)
-		bufferevent_add(&bufev->ev_write, bufev->timeout_write);
-
-	/*
-	 * Invoke the user callback if our buffer is drained or below the
-	 * low watermark.
-	 */
-	if (bufev->writecb != NULL &&
-	    EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low)
-		(*bufev->writecb)(bufev, bufev->cbarg);
-
-	return;
-
- reschedule:
-	if (EVBUFFER_LENGTH(bufev->output) != 0)
-		bufferevent_add(&bufev->ev_write, bufev->timeout_write);
-	return;
-
- error:
-	(*bufev->errorcb)(bufev, what, bufev->cbarg);
-}
-
-/*
- * Create a new buffered event object.
- *
- * The read callback is invoked whenever we read new data.
- * The write callback is invoked whenever the output buffer is drained.
- * The error callback is invoked on a write/read error or on EOF.
- *
- * Both read and write callbacks maybe NULL.  The error callback is not
- * allowed to be NULL and have to be provided always.
- */
-
-struct bufferevent *
-bufferevent_new(int fd, evbuffercb readcb, evbuffercb writecb,
-    everrorcb errorcb, void *cbarg)
-{
-	struct bufferevent *bufev;
-
-	if ((bufev = calloc(1, sizeof(struct bufferevent))) == NULL)
-		return (NULL);
-
-	if ((bufev->input = evbuffer_new()) == NULL) {
-		free(bufev);
-		return (NULL);
-	}
-
-	if ((bufev->output = evbuffer_new()) == NULL) {
-		evbuffer_free(bufev->input);
-		free(bufev);
-		return (NULL);
-	}
-
-	event_set(&bufev->ev_read, fd, EV_READ, bufferevent_readcb, bufev);
-	event_set(&bufev->ev_write, fd, EV_WRITE, bufferevent_writecb, bufev);
-
-	bufferevent_setcb(bufev, readcb, writecb, errorcb, cbarg);
-
-	/*
-	 * Set to EV_WRITE so that using bufferevent_write is going to
-	 * trigger a callback.  Reading needs to be explicitly enabled
-	 * because otherwise no data will be available.
-	 */
-	bufev->enabled = EV_WRITE;
-
-	return (bufev);
-}
-
-void
-bufferevent_setcb(struct bufferevent *bufev,
-    evbuffercb readcb, evbuffercb writecb, everrorcb errorcb, void *cbarg)
-{
-	bufev->readcb = readcb;
-	bufev->writecb = writecb;
-	bufev->errorcb = errorcb;
-
-	bufev->cbarg = cbarg;
-}
-
-void
-bufferevent_setfd(struct bufferevent *bufev, int fd)
-{
-	event_del(&bufev->ev_read);
-	event_del(&bufev->ev_write);
-
-	event_set(&bufev->ev_read, fd, EV_READ, bufferevent_readcb, bufev);
-	event_set(&bufev->ev_write, fd, EV_WRITE, bufferevent_writecb, bufev);
-	if (bufev->ev_base != NULL) {
-		event_base_set(bufev->ev_base, &bufev->ev_read);
-		event_base_set(bufev->ev_base, &bufev->ev_write);
-	}
-
-	/* might have to manually trigger event registration */
-}
-
-int
-bufferevent_priority_set(struct bufferevent *bufev, int priority)
-{
-	if (event_priority_set(&bufev->ev_read, priority) == -1)
-		return (-1);
-	if (event_priority_set(&bufev->ev_write, priority) == -1)
-		return (-1);
-
-	return (0);
-}
-
-/* Closing the file descriptor is the responsibility of the caller */
-
-void
-bufferevent_free(struct bufferevent *bufev)
-{
-	event_del(&bufev->ev_read);
-	event_del(&bufev->ev_write);
-
-	evbuffer_free(bufev->input);
-	evbuffer_free(bufev->output);
-
-	free(bufev);
-}
-
-/*
- * Returns 0 on success;
- *        -1 on failure.
- */
-
-int
-bufferevent_write(struct bufferevent *bufev, const void *data, size_t size)
-{
-	int res;
-
-	res = evbuffer_add(bufev->output, data, size);
-
-	if (res == -1)
-		return (res);
-
-	/* If everything is okay, we need to schedule a write */
-	if (size > 0 && (bufev->enabled & EV_WRITE))
-		bufferevent_add(&bufev->ev_write, bufev->timeout_write);
-
-	return (res);
-}
-
-int
-bufferevent_write_buffer(struct bufferevent *bufev, struct evbuffer *buf)
-{
-	int res;
-
-	res = bufferevent_write(bufev, buf->buffer, buf->off);
-	if (res != -1)
-		evbuffer_drain(buf, buf->off);
-
-	return (res);
-}
-
-size_t
-bufferevent_read(struct bufferevent *bufev, void *data, size_t size)
-{
-	struct evbuffer *buf = bufev->input;
-
-	if (buf->off < size)
-		size = buf->off;
-
-	/* Copy the available data to the user buffer */
-	memcpy(data, buf->buffer, size);
-
-	if (size)
-		evbuffer_drain(buf, size);
-
-	return (size);
-}
-
-int
-bufferevent_enable(struct bufferevent *bufev, short event)
-{
-	if (event & EV_READ) {
-		if (bufferevent_add(&bufev->ev_read, bufev->timeout_read) == -1)
-			return (-1);
-	}
-	if (event & EV_WRITE) {
-		if (bufferevent_add(&bufev->ev_write, bufev->timeout_write) == -1)
-			return (-1);
-	}
-
-	bufev->enabled |= event;
-	return (0);
-}
-
-int
-bufferevent_disable(struct bufferevent *bufev, short event)
-{
-	if (event & EV_READ) {
-		if (event_del(&bufev->ev_read) == -1)
-			return (-1);
-	}
-	if (event & EV_WRITE) {
-		if (event_del(&bufev->ev_write) == -1)
-			return (-1);
-	}
-
-	bufev->enabled &= ~event;
-	return (0);
-}
-
-/*
- * Sets the read and write timeout for a buffered event.
- */
-
-void
-bufferevent_settimeout(struct bufferevent *bufev,
-    int timeout_read, int timeout_write) {
-	bufev->timeout_read = timeout_read;
-	bufev->timeout_write = timeout_write;
-
-	if (event_pending(&bufev->ev_read, EV_READ, NULL))
-		bufferevent_add(&bufev->ev_read, timeout_read);
-	if (event_pending(&bufev->ev_write, EV_WRITE, NULL))
-		bufferevent_add(&bufev->ev_write, timeout_write);
-}
-
-/*
- * Sets the water marks
- */
-
-void
-bufferevent_setwatermark(struct bufferevent *bufev, short events,
-    size_t lowmark, size_t highmark)
-{
-	if (events & EV_READ) {
-		bufev->wm_read.low = lowmark;
-		bufev->wm_read.high = highmark;
-	}
-
-	if (events & EV_WRITE) {
-		bufev->wm_write.low = lowmark;
-		bufev->wm_write.high = highmark;
-	}
-
-	/* If the watermarks changed then see if we should call read again */
-	bufferevent_read_pressure_cb(bufev->input,
-	    0, EVBUFFER_LENGTH(bufev->input), bufev);
-}
-
-int
-bufferevent_base_set(struct event_base *base, struct bufferevent *bufev)
-{
-	int res;
-
-	bufev->ev_base = base;
-
-	res = event_base_set(base, &bufev->ev_read);
-	if (res == -1)
-		return (res);
-
-	res = event_base_set(base, &bufev->ev_write);
-	return (res);
-}
diff --git a/base/third_party/libevent/evdns.3 b/base/third_party/libevent/evdns.3
deleted file mode 100644
index 10414fa..0000000
--- a/base/third_party/libevent/evdns.3
+++ /dev/null
@@ -1,322 +0,0 @@
-.\"
-.\" Copyright (c) 2006 Niels Provos <provos@citi.umich.edu>
-.\" All rights reserved.
-.\"
-.\" Redistribution and use in source and binary forms, with or without
-.\" modification, are permitted provided that the following conditions
-.\" are met:
-.\"
-.\" 1. Redistributions of source code must retain the above copyright
-.\"    notice, this list of conditions and the following disclaimer.
-.\" 2. Redistributions in binary form must reproduce the above copyright
-.\"    notice, this list of conditions and the following disclaimer in the
-.\"    documentation and/or other materials provided with the distribution.
-.\" 3. The name of the author may not be used to endorse or promote products
-.\"    derived from this software without specific prior written permission.
-.\"
-.\" THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
-.\" INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
-.\" AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
-.\" THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-.\" EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-.\" PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
-.\" OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-.\" WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-.\" OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-.\" ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-.\"
-.Dd October 7, 2006
-.Dt EVDNS 3
-.Os
-.Sh NAME
-.Nm evdns_init
-.Nm evdns_shutdown
-.Nm evdns_err_to_string
-.Nm evdns_nameserver_add
-.Nm evdns_count_nameservers
-.Nm evdns_clear_nameservers_and_suspend
-.Nm evdns_resume
-.Nm evdns_nameserver_ip_add
-.Nm evdns_resolve_ipv4
-.Nm evdns_resolve_reverse
-.Nm evdns_resolv_conf_parse
-.Nm evdns_config_windows_nameservers
-.Nm evdns_search_clear
-.Nm evdns_search_add
-.Nm evdns_search_ndots_set
-.Nm evdns_set_log_fn
-.Nd asynchronous functions for DNS resolution.
-.Sh SYNOPSIS
-.Fd #include <sys/time.h>
-.Fd #include <event.h>
-.Fd #include <evdns.h>
-.Ft int
-.Fn evdns_init
-.Ft void
-.Fn evdns_shutdown "int fail_requests"
-.Ft "const char *"
-.Fn evdns_err_to_string "int err"
-.Ft int
-.Fn evdns_nameserver_add "unsigned long int address"
-.Ft int
-.Fn evdns_count_nameservers
-.Ft int
-.Fn evdns_clear_nameservers_and_suspend
-.Ft int
-.Fn evdns_resume
-.Ft int
-.Fn evdns_nameserver_ip_add(const char *ip_as_string);
-.Ft int
-.Fn evdns_resolve_ipv4 "const char *name" "int flags" "evdns_callback_type callback" "void *ptr"
-.Ft int
-.Fn evdns_resolve_reverse "struct in_addr *in" "int flags" "evdns_callback_type callback" "void *ptr"
-.Ft int
-.Fn evdns_resolv_conf_parse "int flags" "const char *"
-.Ft void
-.Fn evdns_search_clear
-.Ft void
-.Fn evdns_search_add "const char *domain"
-.Ft void
-.Fn evdns_search_ndots_set "const int ndots"
-.Ft void
-.Fn evdns_set_log_fn "evdns_debug_log_fn_type fn"
-.Ft int
-.Fn evdns_config_windows_nameservers
-.Sh DESCRIPTION
-Welcome, gentle reader
-.Pp
-Async DNS lookups are really a whole lot harder than they should be,
-mostly stemming from the fact that the libc resolver has never been
-very good at them. Before you use this library you should see if libc
-can do the job for you with the modern async call getaddrinfo_a
-(see http://www.imperialviolet.org/page25.html#e498). Otherwise,
-please continue.
-.Pp
-This code is based on libevent and you must call event_init before
-any of the APIs in this file. You must also seed the OpenSSL random
-source if you are using OpenSSL for ids (see below).
-.Pp
-This library is designed to be included and shipped with your source
-code. You statically link with it. You should also test for the
-existence of strtok_r and define HAVE_STRTOK_R if you have it.
-.Pp
-The DNS protocol requires a good source of id numbers and these
-numbers should be unpredictable for spoofing reasons. There are
-three methods for generating them here and you must define exactly
-one of them. In increasing order of preference:
-.Pp
-.Bl -tag -width "DNS_USE_GETTIMEOFDAY_FOR_ID" -compact -offset indent
-.It DNS_USE_GETTIMEOFDAY_FOR_ID
-Using the bottom 16 bits of the usec result from gettimeofday. This
-is a pretty poor solution but should work anywhere.
-.It DNS_USE_CPU_CLOCK_FOR_ID
-Using the bottom 16 bits of the nsec result from the CPU's time
-counter. This is better, but may not work everywhere. Requires
-POSIX realtime support and you'll need to link against -lrt on
-glibc systems at least.
-.It DNS_USE_OPENSSL_FOR_ID
-Uses the OpenSSL RAND_bytes call to generate the data. You must
-have seeded the pool before making any calls to this library.
-.El
-.Pp
-The library keeps track of the state of nameservers and will avoid
-them when they go down. Otherwise it will round robin between them.
-.Pp
-Quick start guide:
-  #include "evdns.h"
-  void callback(int result, char type, int count, int ttl,
-	 void *addresses, void *arg);
-  evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
-  evdns_resolve("www.hostname.com", 0, callback, NULL);
-.Pp
-When the lookup is complete the callback function is called. The
-first argument will be one of the DNS_ERR_* defines in evdns.h.
-Hopefully it will be DNS_ERR_NONE, in which case type will be
-DNS_IPv4_A, count will be the number of IP addresses, ttl is the time
-which the data can be cached for (in seconds), addresses will point
-to an array of uint32_t's and arg will be whatever you passed to
-evdns_resolve.
-.Pp
-Searching:
-.Pp
-In order for this library to be a good replacement for glibc's resolver it
-supports searching. This involves setting a list of default domains, in
-which names will be queried for. The number of dots in the query name
-determines the order in which this list is used.
-.Pp
-Searching appears to be a single lookup from the point of view of the API,
-although many DNS queries may be generated from a single call to
-evdns_resolve. Searching can also drastically slow down the resolution
-of names.
-.Pp
-To disable searching:
-.Bl -enum -compact -offset indent
-.It
-Never set it up. If you never call
-.Fn evdns_resolv_conf_parse,
-.Fn evdns_init,
-or
-.Fn evdns_search_add
-then no searching will occur.
-.It
-If you do call
-.Fn evdns_resolv_conf_parse
-then don't pass
-.Va DNS_OPTION_SEARCH
-(or
-.Va DNS_OPTIONS_ALL,
-which implies it).
-.It
-When calling
-.Fn evdns_resolve,
-pass the
-.Va DNS_QUERY_NO_SEARCH
-flag.
-.El
-.Pp
-The order of searches depends on the number of dots in the name. If the
-number is greater than the ndots setting then the names is first tried
-globally. Otherwise each search domain is appended in turn.
-.Pp
-The ndots setting can either be set from a resolv.conf, or by calling
-evdns_search_ndots_set.
-.Pp
-For example, with ndots set to 1 (the default) and a search domain list of
-["myhome.net"]:
- Query: www
- Order: www.myhome.net, www.
-.Pp
- Query: www.abc
- Order: www.abc., www.abc.myhome.net
-.Pp
-.Sh API reference
-.Pp
-.Bl -tag -width 0123456
-.It Ft int Fn evdns_init
-Initializes support for non-blocking name resolution by calling
-.Fn evdns_resolv_conf_parse
-on UNIX and
-.Fn evdns_config_windows_nameservers
-on Windows.
-.It Ft int Fn evdns_nameserver_add "unsigned long int address"
-Add a nameserver. The address should be an IP address in
-network byte order. The type of address is chosen so that
-it matches in_addr.s_addr.
-Returns non-zero on error.
-.It Ft int Fn evdns_nameserver_ip_add "const char *ip_as_string"
-This wraps the above function by parsing a string as an IP
-address and adds it as a nameserver.
-Returns non-zero on error
-.It Ft int Fn evdns_resolve "const char *name" "int flags" "evdns_callback_type callback" "void *ptr"
-Resolve a name. The name parameter should be a DNS name.
-The flags parameter should be 0, or DNS_QUERY_NO_SEARCH
-which disables searching for this query. (see defn of
-searching above).
-.Pp
-The callback argument is a function which is called when
-this query completes and ptr is an argument which is passed
-to that callback function.
-.Pp
-Returns non-zero on error
-.It Ft void Fn evdns_search_clear
-Clears the list of search domains
-.It Ft void Fn evdns_search_add "const char *domain"
-Add a domain to the list of search domains
-.It Ft void Fn evdns_search_ndots_set "int ndots"
-Set the number of dots which, when found in a name, causes
-the first query to be without any search domain.
-.It Ft int Fn evdns_count_nameservers "void"
-Return the number of configured nameservers (not necessarily the
-number of running nameservers).  This is useful for double-checking
-whether our calls to the various nameserver configuration functions
-have been successful.
-.It Ft int Fn evdns_clear_nameservers_and_suspend "void"
-Remove all currently configured nameservers, and suspend all pending
-resolves.  Resolves will not necessarily be re-attempted until
-evdns_resume() is called.
-.It Ft int Fn evdns_resume "void"
-Re-attempt resolves left in limbo after an earlier call to
-evdns_clear_nameservers_and_suspend().
-.It Ft int Fn evdns_config_windows_nameservers "void"
-Attempt to configure a set of nameservers based on platform settings on
-a win32 host.  Preferentially tries to use GetNetworkParams; if that fails,
-looks in the registry.  Returns 0 on success, nonzero on failure.
-.It Ft int Fn evdns_resolv_conf_parse "int flags" "const char *filename"
-Parse a resolv.conf like file from the given filename.
-.Pp
-See the man page for resolv.conf for the format of this file.
-The flags argument determines what information is parsed from
-this file:
-.Bl -tag -width "DNS_OPTION_NAMESERVERS" -offset indent -compact -nested
-.It DNS_OPTION_SEARCH
-domain, search and ndots options
-.It DNS_OPTION_NAMESERVERS
-nameserver lines
-.It DNS_OPTION_MISC
-timeout and attempts options
-.It DNS_OPTIONS_ALL
-all of the above
-.El
-.Pp
-The following directives are not parsed from the file:
-  sortlist, rotate, no-check-names, inet6, debug
-.Pp
-Returns non-zero on error:
-.Bl -tag -width "0" -offset indent -compact -nested
-.It 0
-no errors
-.It 1
-failed to open file
-.It 2
-failed to stat file
-.It 3
-file too large
-.It 4
-out of memory
-.It 5
-short read from file
-.El
-.El
-.Sh Internals:
-Requests are kept in two queues. The first is the inflight queue. In
-this queue requests have an allocated transaction id and nameserver.
-They will soon be transmitted if they haven't already been.
-.Pp
-The second is the waiting queue. The size of the inflight ring is
-limited and all other requests wait in waiting queue for space. This
-bounds the number of concurrent requests so that we don't flood the
-nameserver. Several algorithms require a full walk of the inflight
-queue and so bounding its size keeps thing going nicely under huge
-(many thousands of requests) loads.
-.Pp
-If a nameserver loses too many requests it is considered down and we
-try not to use it. After a while we send a probe to that nameserver
-(a lookup for google.com) and, if it replies, we consider it working
-again. If the nameserver fails a probe we wait longer to try again
-with the next probe.
-.Sh SEE ALSO
-.Xr event 3 ,
-.Xr gethostbyname 3 ,
-.Xr resolv.conf 5
-.Sh HISTORY
-The
-.Nm evdns
-API was developed by Adam Langley on top of the
-.Nm libevent
-API.
-The code was integrate into
-.Nm Tor
-by Nick Mathewson and finally put into
-.Nm libevent
-itself by Niels Provos.
-.Sh AUTHORS
-The
-.Nm evdns
-API and code was written by Adam Langley with significant
-contributions by Nick Mathewson.
-.Sh BUGS
-This documentation is neither complete nor authoritative.
-If you are in doubt about the usage of this API then
-check the source code to find out how it works, write
-up the missing piece of documentation and send it to
-me for inclusion in this man page.
diff --git a/base/third_party/libevent/evdns.c b/base/third_party/libevent/evdns.c
deleted file mode 100644
index 05fe594..0000000
--- a/base/third_party/libevent/evdns.c
+++ /dev/null
@@ -1,3192 +0,0 @@
-/* $Id: evdns.c 6979 2006-08-04 18:31:13Z nickm $ */
-
-/* The original version of this module was written by Adam Langley; for
- * a history of modifications, check out the subversion logs.
- *
- * When editing this module, try to keep it re-mergeable by Adam.  Don't
- * reformat the whitespace, add Tor dependencies, or so on.
- *
- * TODO:
- *   - Support IPv6 and PTR records.
- *   - Replace all externally visible magic numbers with #defined constants.
- *   - Write doccumentation for APIs of all external functions.
- */
-
-/* Async DNS Library
- * Adam Langley <agl@imperialviolet.org>
- * http://www.imperialviolet.org/eventdns.html
- * Public Domain code
- *
- * This software is Public Domain. To view a copy of the public domain dedication,
- * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
- * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
- *
- * I ask and expect, but do not require, that all derivative works contain an
- * attribution similar to:
- * 	Parts developed by Adam Langley <agl@imperialviolet.org>
- *
- * You may wish to replace the word "Parts" with something else depending on
- * the amount of original code.
- *
- * (Derivative works does not include programs which link against, run or include
- * the source verbatim in their source distributions)
- *
- * Version: 0.1b
- */
-
-#include <sys/types.h>
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef DNS_USE_FTIME_FOR_ID
-#include <sys/timeb.h>
-#endif
-
-#ifndef DNS_USE_CPU_CLOCK_FOR_ID
-#ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
-#ifndef DNS_USE_OPENSSL_FOR_ID
-#ifndef DNS_USE_FTIME_FOR_ID
-#error Must configure at least one id generation method.
-#error Please see the documentation.
-#endif
-#endif
-#endif
-#endif
-
-/* #define _POSIX_C_SOURCE 200507 */
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE
-#endif
-
-#ifdef DNS_USE_CPU_CLOCK_FOR_ID
-#ifdef DNS_USE_OPENSSL_FOR_ID
-#error Multiple id options selected
-#endif
-#ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
-#error Multiple id options selected
-#endif
-#include <time.h>
-#endif
-
-#ifdef DNS_USE_OPENSSL_FOR_ID
-#ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
-#error Multiple id options selected
-#endif
-#include <openssl/rand.h>
-#endif
-
-#ifndef _FORTIFY_SOURCE
-#define _FORTIFY_SOURCE 3
-#endif
-
-#include <string.h>
-#include <fcntl.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#ifdef HAVE_STDINT_H
-#include <stdint.h>
-#endif
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <assert.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#include <limits.h>
-#include <sys/stat.h>
-#include <ctype.h>
-#include <stdio.h>
-#include <stdarg.h>
-
-#include "evdns.h"
-#include "evutil.h"
-#include "log.h"
-#ifdef WIN32
-#include <winsock2.h>
-#include <windows.h>
-#include <iphlpapi.h>
-#include <io.h>
-#else
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#endif
-
-#ifdef HAVE_NETINET_IN6_H
-#include <netinet/in6.h>
-#endif
-
-#define EVDNS_LOG_DEBUG 0
-#define EVDNS_LOG_WARN 1
-
-#ifndef HOST_NAME_MAX
-#define HOST_NAME_MAX 255
-#endif
-
-#include <stdio.h>
-
-#undef MIN
-#define MIN(a,b) ((a)<(b)?(a):(b))
-
-#ifdef __USE_ISOC99B
-/* libevent doesn't work without this */
-typedef ev_uint8_t u_char;
-typedef unsigned int uint;
-#endif
-#include "event.h"
-
-#define u64 ev_uint64_t
-#define u32 ev_uint32_t
-#define u16 ev_uint16_t
-#define u8  ev_uint8_t
-
-#ifdef WIN32
-#define open _open
-#define read _read
-#define close _close
-#define strdup _strdup
-#endif
-
-#define MAX_ADDRS 32  /* maximum number of addresses from a single packet */
-/* which we bother recording */
-
-#define TYPE_A         EVDNS_TYPE_A
-#define TYPE_CNAME     5
-#define TYPE_PTR       EVDNS_TYPE_PTR
-#define TYPE_AAAA      EVDNS_TYPE_AAAA
-
-#define CLASS_INET     EVDNS_CLASS_INET
-
-#ifdef HAVE_SETFD
-#define FD_CLOSEONEXEC(x) do { \
-	if (fcntl(x, F_SETFD, 1) == -1) \
-		event_warn("fcntl(%d, F_SETFD)", x); \
-	} while (0)
-#else
-#define FD_CLOSEONEXEC(x) (void)0
-#endif
-
-struct request {
-	u8 *request;  /* the dns packet data */
-	unsigned int request_len;
-	int reissue_count;
-	int tx_count;  /* the number of times that this packet has been sent */
-	unsigned int request_type; /* TYPE_PTR or TYPE_A */
-	void *user_pointer;  /* the pointer given to us for this request */
-	evdns_callback_type user_callback;
-	struct nameserver *ns;  /* the server which we last sent it */
-
-	/* elements used by the searching code */
-	int search_index;
-	struct search_state *search_state;
-	char *search_origname;  /* needs to be free()ed */
-	int search_flags;
-
-	/* these objects are kept in a circular list */
-	struct request *next, *prev;
-
-	struct event timeout_event;
-
-	u16 trans_id;  /* the transaction id */
-	char request_appended;  /* true if the request pointer is data which follows this struct */
-	char transmit_me;  /* needs to be transmitted */
-};
-
-#ifndef HAVE_STRUCT_IN6_ADDR
-struct in6_addr {
-	u8 s6_addr[16];
-};
-#endif
-
-struct reply {
-	unsigned int type;
-	unsigned int have_answer;
-	union {
-		struct {
-			u32 addrcount;
-			u32 addresses[MAX_ADDRS];
-		} a;
-		struct {
-			u32 addrcount;
-			struct in6_addr addresses[MAX_ADDRS];
-		} aaaa;
-		struct {
-			char name[HOST_NAME_MAX];
-		} ptr;
-	} data;
-};
-
-struct nameserver {
-	int socket;  /* a connected UDP socket */
-	u32 address;
-	u16 port;
-	int failed_times;  /* number of times which we have given this server a chance */
-	int timedout;  /* number of times in a row a request has timed out */
-	struct event event;
-	/* these objects are kept in a circular list */
-	struct nameserver *next, *prev;
-	struct event timeout_event;  /* used to keep the timeout for */
-				     /* when we next probe this server. */
-				     /* Valid if state == 0 */
-	char state;  /* zero if we think that this server is down */
-	char choked;  /* true if we have an EAGAIN from this server's socket */
-	char write_waiting;  /* true if we are waiting for EV_WRITE events */
-};
-
-static struct request *req_head = NULL, *req_waiting_head = NULL;
-static struct nameserver *server_head = NULL;
-
-/* Represents a local port where we're listening for DNS requests. Right now, */
-/* only UDP is supported. */
-struct evdns_server_port {
-	int socket; /* socket we use to read queries and write replies. */
-	int refcnt; /* reference count. */
-	char choked; /* Are we currently blocked from writing? */
-	char closing; /* Are we trying to close this port, pending writes? */
-	evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
-	void *user_data; /* Opaque pointer passed to user_callback */
-	struct event event; /* Read/write event */
-	/* circular list of replies that we want to write. */
-	struct server_request *pending_replies;
-};
-
-/* Represents part of a reply being built.	(That is, a single RR.) */
-struct server_reply_item {
-	struct server_reply_item *next; /* next item in sequence. */
-	char *name; /* name part of the RR */
-	u16 type : 16; /* The RR type */
-	u16 class : 16; /* The RR class (usually CLASS_INET) */
-	u32 ttl; /* The RR TTL */
-	char is_name; /* True iff data is a label */
-	u16 datalen; /* Length of data; -1 if data is a label */
-	void *data; /* The contents of the RR */
-};
-
-/* Represents a request that we've received as a DNS server, and holds */
-/* the components of the reply as we're constructing it. */
-struct server_request {
-	/* Pointers to the next and previous entries on the list of replies */
-	/* that we're waiting to write.	 Only set if we have tried to respond */
-	/* and gotten EAGAIN. */
-	struct server_request *next_pending;
-	struct server_request *prev_pending;
-
-	u16 trans_id; /* Transaction id. */
-	struct evdns_server_port *port; /* Which port received this request on? */
-	struct sockaddr_storage addr; /* Where to send the response */
-	socklen_t addrlen; /* length of addr */
-
-	int n_answer; /* how many answer RRs have been set? */
-	int n_authority; /* how many authority RRs have been set? */
-	int n_additional; /* how many additional RRs have been set? */
-
-	struct server_reply_item *answer; /* linked list of answer RRs */
-	struct server_reply_item *authority; /* linked list of authority RRs */
-	struct server_reply_item *additional; /* linked list of additional RRs */
-
-	/* Constructed response.  Only set once we're ready to send a reply. */
-	/* Once this is set, the RR fields are cleared, and no more should be set. */
-	char *response;
-	size_t response_len;
-
-	/* Caller-visible fields: flags, questions. */
-	struct evdns_server_request base;
-};
-
-/* helper macro */
-#define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
-
-/* Given a pointer to an evdns_server_request, get the corresponding */
-/* server_request. */
-#define TO_SERVER_REQUEST(base_ptr)										\
-	((struct server_request*)											\
-	 (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
-
-/* The number of good nameservers that we have */
-static int global_good_nameservers = 0;
-
-/* inflight requests are contained in the req_head list */
-/* and are actually going out across the network */
-static int global_requests_inflight = 0;
-/* requests which aren't inflight are in the waiting list */
-/* and are counted here */
-static int global_requests_waiting = 0;
-
-static int global_max_requests_inflight = 64;
-
-static struct timeval global_timeout = {5, 0};  /* 5 seconds */
-static int global_max_reissues = 1;  /* a reissue occurs when we get some errors from the server */
-static int global_max_retransmits = 3;  /* number of times we'll retransmit a request which timed out */
-/* number of timeouts in a row before we consider this server to be down */
-static int global_max_nameserver_timeout = 3;
-
-/* These are the timeout values for nameservers. If we find a nameserver is down */
-/* we try to probe it at intervals as given below. Values are in seconds. */
-static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
-static const int global_nameserver_timeouts_length = sizeof(global_nameserver_timeouts)/sizeof(struct timeval);
-
-static struct nameserver *nameserver_pick(void);
-static void evdns_request_insert(struct request *req, struct request **head);
-static void nameserver_ready_callback(int fd, short events, void *arg);
-static int evdns_transmit(void);
-static int evdns_request_transmit(struct request *req);
-static void nameserver_send_probe(struct nameserver *const ns);
-static void search_request_finished(struct request *const);
-static int search_try_next(struct request *const req);
-static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
-static void evdns_requests_pump_waiting_queue(void);
-static u16 transaction_id_pick(void);
-static struct request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
-static void request_submit(struct request *const req);
-
-static int server_request_free(struct server_request *req);
-static void server_request_free_answers(struct server_request *req);
-static void server_port_free(struct evdns_server_port *port);
-static void server_port_ready_callback(int fd, short events, void *arg);
-
-static int strtoint(const char *const str);
-
-#ifdef WIN32
-static int
-last_error(int sock)
-{
-	int optval, optvallen=sizeof(optval);
-	int err = WSAGetLastError();
-	if (err == WSAEWOULDBLOCK && sock >= 0) {
-		if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
-			       &optvallen))
-			return err;
-		if (optval)
-			return optval;
-	}
-	return err;
-
-}
-static int
-error_is_eagain(int err)
-{
-	return err == EAGAIN || err == WSAEWOULDBLOCK;
-}
-static int
-inet_aton(const char *c, struct in_addr *addr)
-{
-	ev_uint32_t r;
-	if (strcmp(c, "255.255.255.255") == 0) {
-		addr->s_addr = 0xffffffffu;
-	} else {
-		r = inet_addr(c);
-		if (r == INADDR_NONE)
-			return 0;
-		addr->s_addr = r;
-	}
-	return 1;
-}
-#else
-#define last_error(sock) (errno)
-#define error_is_eagain(err) ((err) == EAGAIN)
-#endif
-#define CLOSE_SOCKET(s) EVUTIL_CLOSESOCKET(s)
-
-#define ISSPACE(c) isspace((int)(unsigned char)(c))
-#define ISDIGIT(c) isdigit((int)(unsigned char)(c))
-
-static const char *
-debug_ntoa(u32 address)
-{
-	static char buf[32];
-	u32 a = ntohl(address);
-	evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
-                      (int)(u8)((a>>24)&0xff),
-                      (int)(u8)((a>>16)&0xff),
-                      (int)(u8)((a>>8 )&0xff),
-  		      (int)(u8)((a    )&0xff));
-	return buf;
-}
-
-static evdns_debug_log_fn_type evdns_log_fn = NULL;
-
-void
-evdns_set_log_fn(evdns_debug_log_fn_type fn)
-{
-  evdns_log_fn = fn;
-}
-
-#ifdef __GNUC__
-#define EVDNS_LOG_CHECK  __attribute__ ((format(printf, 2, 3)))
-#else
-#define EVDNS_LOG_CHECK
-#endif
-
-static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
-static void
-_evdns_log(int warn, const char *fmt, ...)
-{
-  va_list args;
-  static char buf[512];
-  if (!evdns_log_fn)
-    return;
-  va_start(args,fmt);
-  evutil_vsnprintf(buf, sizeof(buf), fmt, args);
-  buf[sizeof(buf)-1] = '\0';
-  evdns_log_fn(warn, buf);
-  va_end(args);
-}
-
-#define log _evdns_log
-
-/* This walks the list of inflight requests to find the */
-/* one with a matching transaction id. Returns NULL on */
-/* failure */
-static struct request *
-request_find_from_trans_id(u16 trans_id) {
-	struct request *req = req_head, *const started_at = req_head;
-
-	if (req) {
-		do {
-			if (req->trans_id == trans_id) return req;
-			req = req->next;
-		} while (req != started_at);
-	}
-
-	return NULL;
-}
-
-/* a libevent callback function which is called when a nameserver */
-/* has gone down and we want to test if it has came back to life yet */
-static void
-nameserver_prod_callback(int fd, short events, void *arg) {
-	struct nameserver *const ns = (struct nameserver *) arg;
-        (void)fd;
-        (void)events;
-
-	nameserver_send_probe(ns);
-}
-
-/* a libevent callback which is called when a nameserver probe (to see if */
-/* it has come back to life) times out. We increment the count of failed_times */
-/* and wait longer to send the next probe packet. */
-static void
-nameserver_probe_failed(struct nameserver *const ns) {
-	const struct timeval * timeout;
-	(void) evtimer_del(&ns->timeout_event);
-	if (ns->state == 1) {
-		/* This can happen if the nameserver acts in a way which makes us mark */
-		/* it as bad and then starts sending good replies. */
-		return;
-	}
-
-	timeout =
-	  &global_nameserver_timeouts[MIN(ns->failed_times,
-					  global_nameserver_timeouts_length - 1)];
-	ns->failed_times++;
-
-	if (evtimer_add(&ns->timeout_event, (struct timeval *) timeout) < 0) {
-          log(EVDNS_LOG_WARN,
-              "Error from libevent when adding timer event for %s",
-              debug_ntoa(ns->address));
-          /* ???? Do more? */
-        }
-}
-
-/* called when a nameserver has been deemed to have failed. For example, too */
-/* many packets have timed out etc */
-static void
-nameserver_failed(struct nameserver *const ns, const char *msg) {
-	struct request *req, *started_at;
-	/* if this nameserver has already been marked as failed */
-	/* then don't do anything */
-	if (!ns->state) return;
-
-	log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
-            debug_ntoa(ns->address), msg);
-	global_good_nameservers--;
-	assert(global_good_nameservers >= 0);
-	if (global_good_nameservers == 0) {
-		log(EVDNS_LOG_WARN, "All nameservers have failed");
-	}
-
-	ns->state = 0;
-	ns->failed_times = 1;
-
-	if (evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
-		log(EVDNS_LOG_WARN,
-		    "Error from libevent when adding timer event for %s",
-		    debug_ntoa(ns->address));
-		/* ???? Do more? */
-        }
-
-	/* walk the list of inflight requests to see if any can be reassigned to */
-	/* a different server. Requests in the waiting queue don't have a */
-	/* nameserver assigned yet */
-
-	/* if we don't have *any* good nameservers then there's no point */
-	/* trying to reassign requests to one */
-	if (!global_good_nameservers) return;
-
-	req = req_head;
-	started_at = req_head;
-	if (req) {
-		do {
-			if (req->tx_count == 0 && req->ns == ns) {
-				/* still waiting to go out, can be moved */
-				/* to another server */
-				req->ns = nameserver_pick();
-			}
-			req = req->next;
-		} while (req != started_at);
-	}
-}
-
-static void
-nameserver_up(struct nameserver *const ns) {
-	if (ns->state) return;
-	log(EVDNS_LOG_WARN, "Nameserver %s is back up",
-	    debug_ntoa(ns->address));
-	evtimer_del(&ns->timeout_event);
-	ns->state = 1;
-	ns->failed_times = 0;
-	ns->timedout = 0;
-	global_good_nameservers++;
-}
-
-static void
-request_trans_id_set(struct request *const req, const u16 trans_id) {
-	req->trans_id = trans_id;
-	*((u16 *) req->request) = htons(trans_id);
-}
-
-/* Called to remove a request from a list and dealloc it. */
-/* head is a pointer to the head of the list it should be */
-/* removed from or NULL if the request isn't in a list. */
-static void
-request_finished(struct request *const req, struct request **head) {
-	if (head) {
-		if (req->next == req) {
-			/* only item in the list */
-			*head = NULL;
-		} else {
-			req->next->prev = req->prev;
-			req->prev->next = req->next;
-			if (*head == req) *head = req->next;
-		}
-	}
-
-	log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
-	    (unsigned long) req);
-	evtimer_del(&req->timeout_event);
-
-	search_request_finished(req);
-	global_requests_inflight--;
-
-	if (!req->request_appended) {
-		/* need to free the request data on it's own */
-		free(req->request);
-	} else {
-		/* the request data is appended onto the header */
-		/* so everything gets free()ed when we: */
-	}
-
-	free(req);
-
-	evdns_requests_pump_waiting_queue();
-}
-
-/* This is called when a server returns a funny error code. */
-/* We try the request again with another server. */
-/* */
-/* return: */
-/*   0 ok */
-/*   1 failed/reissue is pointless */
-static int
-request_reissue(struct request *req) {
-	const struct nameserver *const last_ns = req->ns;
-	/* the last nameserver should have been marked as failing */
-	/* by the caller of this function, therefore pick will try */
-	/* not to return it */
-	req->ns = nameserver_pick();
-	if (req->ns == last_ns) {
-		/* ... but pick did return it */
-		/* not a lot of point in trying again with the */
-		/* same server */
-		return 1;
-	}
-
-	req->reissue_count++;
-	req->tx_count = 0;
-	req->transmit_me = 1;
-
-	return 0;
-}
-
-/* this function looks for space on the inflight queue and promotes */
-/* requests from the waiting queue if it can. */
-static void
-evdns_requests_pump_waiting_queue(void) {
-	while (global_requests_inflight < global_max_requests_inflight &&
-	    global_requests_waiting) {
-		struct request *req;
-		/* move a request from the waiting queue to the inflight queue */
-		assert(req_waiting_head);
-		if (req_waiting_head->next == req_waiting_head) {
-			/* only one item in the queue */
-			req = req_waiting_head;
-			req_waiting_head = NULL;
-		} else {
-			req = req_waiting_head;
-			req->next->prev = req->prev;
-			req->prev->next = req->next;
-			req_waiting_head = req->next;
-		}
-
-		global_requests_waiting--;
-		global_requests_inflight++;
-
-		req->ns = nameserver_pick();
-		request_trans_id_set(req, transaction_id_pick());
-
-		evdns_request_insert(req, &req_head);
-		evdns_request_transmit(req);
-		evdns_transmit();
-	}
-}
-
-static void
-reply_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply) {
-	switch (req->request_type) {
-	case TYPE_A:
-		if (reply)
-			req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
-							   reply->data.a.addrcount, ttl,
-						 reply->data.a.addresses,
-							   req->user_pointer);
-		else
-			req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
-		return;
-	case TYPE_PTR:
-		if (reply) {
-			char *name = reply->data.ptr.name;
-			req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
-							   &name, req->user_pointer);
-		} else {
-			req->user_callback(err, 0, 0, 0, NULL,
-							   req->user_pointer);
-		}
-		return;
-	case TYPE_AAAA:
-		if (reply)
-			req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
-							   reply->data.aaaa.addrcount, ttl,
-							   reply->data.aaaa.addresses,
-							   req->user_pointer);
-		else
-			req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
-                return;
-	}
-	assert(0);
-}
-
-/* this processes a parsed reply packet */
-static void
-reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
-	int error;
-	static const int error_codes[] = {
-		DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST,
-		DNS_ERR_NOTIMPL, DNS_ERR_REFUSED
-	};
-
-	if (flags & 0x020f || !reply || !reply->have_answer) {
-		/* there was an error */
-		if (flags & 0x0200) {
-			error = DNS_ERR_TRUNCATED;
-		} else {
-			u16 error_code = (flags & 0x000f) - 1;
-			if (error_code > 4) {
-				error = DNS_ERR_UNKNOWN;
-			} else {
-				error = error_codes[error_code];
-			}
-		}
-
-		switch(error) {
-		case DNS_ERR_NOTIMPL:
-		case DNS_ERR_REFUSED:
-			/* we regard these errors as marking a bad nameserver */
-			if (req->reissue_count < global_max_reissues) {
-				char msg[64];
-				evutil_snprintf(msg, sizeof(msg),
-				    "Bad response %d (%s)",
-					 error, evdns_err_to_string(error));
-				nameserver_failed(req->ns, msg);
-				if (!request_reissue(req)) return;
-			}
-			break;
-		case DNS_ERR_SERVERFAILED:
-			/* rcode 2 (servfailed) sometimes means "we
-			 * are broken" and sometimes (with some binds)
-			 * means "that request was very confusing."
-			 * Treat this as a timeout, not a failure.
-			 */
-			log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver %s; "
-				"will allow the request to time out.",
-				debug_ntoa(req->ns->address));
-			break;
-		default:
-			/* we got a good reply from the nameserver */
-			nameserver_up(req->ns);
-		}
-
-		if (req->search_state && req->request_type != TYPE_PTR) {
-			/* if we have a list of domains to search in,
-			 * try the next one */
-			if (!search_try_next(req)) {
-				/* a new request was issued so this
-				 * request is finished and */
-				/* the user callback will be made when
-				 * that request (or a */
-				/* child of it) finishes. */
-				request_finished(req, &req_head);
-				return;
-			}
-		}
-
-		/* all else failed. Pass the failure up */
-		reply_callback(req, 0, error, NULL);
-		request_finished(req, &req_head);
-	} else {
-		/* all ok, tell the user */
-		reply_callback(req, ttl, 0, reply);
-		nameserver_up(req->ns);
-		request_finished(req, &req_head);
-	}
-}
-
-static int
-name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
-	int name_end = -1;
-	int j = *idx;
-	int ptr_count = 0;
-#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
-#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
-#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
-
-	char *cp = name_out;
-	const char *const end = name_out + name_out_len;
-
-	/* Normally, names are a series of length prefixed strings terminated */
-	/* with a length of 0 (the lengths are u8's < 63). */
-	/* However, the length can start with a pair of 1 bits and that */
-	/* means that the next 14 bits are a pointer within the current */
-	/* packet. */
-
-	for(;;) {
-		u8 label_len;
-		if (j >= length) return -1;
-		GET8(label_len);
-		if (!label_len) break;
-		if (label_len & 0xc0) {
-			u8 ptr_low;
-			GET8(ptr_low);
-			if (name_end < 0) name_end = j;
-			j = (((int)label_len & 0x3f) << 8) + ptr_low;
-			/* Make sure that the target offset is in-bounds. */
-			if (j < 0 || j >= length) return -1;
-			/* If we've jumped more times than there are characters in the
-			 * message, we must have a loop. */
-			if (++ptr_count > length) return -1;
-			continue;
-		}
-		if (label_len > 63) return -1;
-		if (cp != name_out) {
-			if (cp + 1 >= end) return -1;
-			*cp++ = '.';
-		}
-		if (cp + label_len >= end) return -1;
-		memcpy(cp, packet + j, label_len);
-		cp += label_len;
-		j += label_len;
-	}
-	if (cp >= end) return -1;
-	*cp = '\0';
-	if (name_end < 0)
-		*idx = j;
-	else
-		*idx = name_end;
-	return 0;
- err:
-	return -1;
-}
-
-/* parses a raw request from a nameserver */
-static int
-reply_parse(u8 *packet, int length) {
-	int j = 0, k = 0;  /* index into packet */
-	u16 _t;  /* used by the macros */
-	u32 _t32;  /* used by the macros */
-	char tmp_name[256], cmp_name[256]; /* used by the macros */
-
-	u16 trans_id, questions, answers, authority, additional, datalength;
-        u16 flags = 0;
-	u32 ttl, ttl_r = 0xffffffff;
-	struct reply reply;
-	struct request *req = NULL;
-	unsigned int i;
-
-	GET16(trans_id);
-	GET16(flags);
-	GET16(questions);
-	GET16(answers);
-	GET16(authority);
-	GET16(additional);
-	(void) authority; /* suppress "unused variable" warnings. */
-	(void) additional; /* suppress "unused variable" warnings. */
-
-	req = request_find_from_trans_id(trans_id);
-	if (!req) return -1;
-
-	memset(&reply, 0, sizeof(reply));
-
-	/* If it's not an answer, it doesn't correspond to any request. */
-	if (!(flags & 0x8000)) return -1;  /* must be an answer */
-	if (flags & 0x020f) {
-		/* there was an error */
-		goto err;
-	}
-	/* if (!answers) return; */  /* must have an answer of some form */
-
-	/* This macro skips a name in the DNS reply. */
-#define SKIP_NAME \
-	do { tmp_name[0] = '\0';				\
-		if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
-			goto err;				\
-	} while(0)
-#define TEST_NAME \
-	do { tmp_name[0] = '\0';				\
-		cmp_name[0] = '\0';				\
-		k = j;						\
-		if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
-			goto err;					\
-		if (name_parse(req->request, req->request_len, &k, cmp_name, sizeof(cmp_name))<0)	\
-			goto err;				\
-		if (memcmp(tmp_name, cmp_name, strlen (tmp_name)) != 0)	\
-			return (-1); /* we ignore mismatching names */	\
-	} while(0)
-
-	reply.type = req->request_type;
-
-	/* skip over each question in the reply */
-	for (i = 0; i < questions; ++i) {
-		/* the question looks like
-		 *   <label:name><u16:type><u16:class>
-		 */
-		TEST_NAME;
-		j += 4;
-		if (j > length) goto err;
-	}
-
-	/* now we have the answer section which looks like
-	 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
-	 */
-
-	for (i = 0; i < answers; ++i) {
-		u16 type, class;
-
-		SKIP_NAME;
-		GET16(type);
-		GET16(class);
-		GET32(ttl);
-		GET16(datalength);
-
-		if (type == TYPE_A && class == CLASS_INET) {
-			int addrcount, addrtocopy;
-			if (req->request_type != TYPE_A) {
-				j += datalength; continue;
-			}
-			if ((datalength & 3) != 0) /* not an even number of As. */
-			    goto err;
-			addrcount = datalength >> 2;
-			addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
-
-			ttl_r = MIN(ttl_r, ttl);
-			/* we only bother with the first four addresses. */
-			if (j + 4*addrtocopy > length) goto err;
-			memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
-				   packet + j, 4*addrtocopy);
-			j += 4*addrtocopy;
-			reply.data.a.addrcount += addrtocopy;
-			reply.have_answer = 1;
-			if (reply.data.a.addrcount == MAX_ADDRS) break;
-		} else if (type == TYPE_PTR && class == CLASS_INET) {
-			if (req->request_type != TYPE_PTR) {
-				j += datalength; continue;
-			}
-			if (name_parse(packet, length, &j, reply.data.ptr.name,
-						   sizeof(reply.data.ptr.name))<0)
-				goto err;
-			ttl_r = MIN(ttl_r, ttl);
-			reply.have_answer = 1;
-			break;
-		} else if (type == TYPE_AAAA && class == CLASS_INET) {
-			int addrcount, addrtocopy;
-			if (req->request_type != TYPE_AAAA) {
-				j += datalength; continue;
-			}
-			if ((datalength & 15) != 0) /* not an even number of AAAAs. */
-				goto err;
-			addrcount = datalength >> 4;  /* each address is 16 bytes long */
-			addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
-			ttl_r = MIN(ttl_r, ttl);
-
-			/* we only bother with the first four addresses. */
-			if (j + 16*addrtocopy > length) goto err;
-			memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
-				   packet + j, 16*addrtocopy);
-			reply.data.aaaa.addrcount += addrtocopy;
-			j += 16*addrtocopy;
-			reply.have_answer = 1;
-			if (reply.data.aaaa.addrcount == MAX_ADDRS) break;
-		} else {
-			/* skip over any other type of resource */
-			j += datalength;
-		}
-	}
-
-	reply_handle(req, flags, ttl_r, &reply);
-	return 0;
- err:
-	if (req)
-		reply_handle(req, flags, 0, NULL);
-	return -1;
-}
-
-/* Parse a raw request (packet,length) sent to a nameserver port (port) from */
-/* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
-/* callback. */
-static int
-request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, socklen_t addrlen)
-{
-	int j = 0;	/* index into packet */
-	u16 _t;	 /* used by the macros */
-	char tmp_name[256]; /* used by the macros */
-
-	int i;
-	u16 trans_id, flags, questions, answers, authority, additional;
-	struct server_request *server_req = NULL;
-
-	/* Get the header fields */
-	GET16(trans_id);
-	GET16(flags);
-	GET16(questions);
-	GET16(answers);
-	GET16(authority);
-	GET16(additional);
-
-	if (flags & 0x8000) return -1; /* Must not be an answer. */
-	flags &= 0x0110; /* Only RD and CD get preserved. */
-
-	server_req = malloc(sizeof(struct server_request));
-	if (server_req == NULL) return -1;
-	memset(server_req, 0, sizeof(struct server_request));
-
-	server_req->trans_id = trans_id;
-	memcpy(&server_req->addr, addr, addrlen);
-	server_req->addrlen = addrlen;
-
-	server_req->base.flags = flags;
-	server_req->base.nquestions = 0;
-	server_req->base.questions = malloc(sizeof(struct evdns_server_question *) * questions);
-	if (server_req->base.questions == NULL)
-		goto err;
-
-	for (i = 0; i < questions; ++i) {
-		u16 type, class;
-		struct evdns_server_question *q;
-		int namelen;
-		if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
-			goto err;
-		GET16(type);
-		GET16(class);
-		namelen = strlen(tmp_name);
-		q = malloc(sizeof(struct evdns_server_question) + namelen);
-		if (!q)
-			goto err;
-		q->type = type;
-		q->dns_question_class = class;
-		memcpy(q->name, tmp_name, namelen+1);
-		server_req->base.questions[server_req->base.nquestions++] = q;
-	}
-
-	/* Ignore answers, authority, and additional. */
-
-	server_req->port = port;
-	port->refcnt++;
-
-	/* Only standard queries are supported. */
-	if (flags & 0x7800) {
-		evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
-		return -1;
-	}
-
-	port->user_callback(&(server_req->base), port->user_data);
-
-	return 0;
-err:
-	if (server_req) {
-		if (server_req->base.questions) {
-			for (i = 0; i < server_req->base.nquestions; ++i)
-				free(server_req->base.questions[i]);
-			free(server_req->base.questions);
-		}
-		free(server_req);
-	}
-	return -1;
-
-#undef SKIP_NAME
-#undef GET32
-#undef GET16
-#undef GET8
-}
-
-static u16
-default_transaction_id_fn(void)
-{
-	u16 trans_id;
-#ifdef DNS_USE_CPU_CLOCK_FOR_ID
-	struct timespec ts;
-	static int clkid = -1;
-	if (clkid == -1) {
-		clkid = CLOCK_REALTIME;
-#ifdef CLOCK_MONOTONIC
-		if (clock_gettime(CLOCK_MONOTONIC, &ts) != -1)
-			clkid = CLOCK_MONOTONIC;
-#endif
-	}
-	if (clock_gettime(clkid, &ts) == -1)
-		event_err(1, "clock_gettime");
-	trans_id = ts.tv_nsec & 0xffff;
-#endif
-
-#ifdef DNS_USE_FTIME_FOR_ID
-	struct _timeb tb;
-	_ftime(&tb);
-	trans_id = tb.millitm & 0xffff;
-#endif
-
-#ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
-	struct timeval tv;
-	evutil_gettimeofday(&tv, NULL);
-	trans_id = tv.tv_usec & 0xffff;
-#endif
-
-#ifdef DNS_USE_OPENSSL_FOR_ID
-	if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
-		/* in the case that the RAND call fails we back */
-		/* down to using gettimeofday. */
-		/*
-		  struct timeval tv;
-		  evutil_gettimeofday(&tv, NULL);
-		  trans_id = tv.tv_usec & 0xffff;
-		*/
-		abort();
-	}
-#endif
-	return trans_id;
-}
-
-static ev_uint16_t (*trans_id_function)(void) = default_transaction_id_fn;
-
-void
-evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void))
-{
-	if (fn)
-		trans_id_function = fn;
-	else
-		trans_id_function = default_transaction_id_fn;
-}
-
-/* Try to choose a strong transaction id which isn't already in flight */
-static u16
-transaction_id_pick(void) {
-	for (;;) {
-		u16 trans_id = trans_id_function();
-
-		if (trans_id == 0xffff) continue;
-
-		if (request_find_from_trans_id(trans_id) == NULL)
-			return trans_id;
-	}
-}
-
-/* choose a namesever to use. This function will try to ignore */
-/* nameservers which we think are down and load balance across the rest */
-/* by updating the server_head global each time. */
-static struct nameserver *
-nameserver_pick(void) {
-	struct nameserver *started_at = server_head, *picked;
-	if (!server_head) return NULL;
-
-	/* if we don't have any good nameservers then there's no */
-	/* point in trying to find one. */
-	if (!global_good_nameservers) {
-		server_head = server_head->next;
-		return server_head;
-	}
-
-	/* remember that nameservers are in a circular list */
-	for (;;) {
-		if (server_head->state) {
-			/* we think this server is currently good */
-			picked = server_head;
-			server_head = server_head->next;
-			return picked;
-		}
-
-		server_head = server_head->next;
-		if (server_head == started_at) {
-			/* all the nameservers seem to be down */
-			/* so we just return this one and hope for the */
-			/* best */
-			assert(global_good_nameservers == 0);
-			picked = server_head;
-			server_head = server_head->next;
-			return picked;
-		}
-	}
-}
-
-static int
-address_is_correct(struct nameserver *ns, struct sockaddr *sa, socklen_t slen)
-{
-	struct sockaddr_in *sin = (struct sockaddr_in*) sa;
-	if (sa->sa_family != AF_INET || slen != sizeof(struct sockaddr_in))
-		return 0;
-	if (sin->sin_addr.s_addr != ns->address)
-		return 0;
-	return 1;
-}
-
-/* this is called when a namesever socket is ready for reading */
-static void
-nameserver_read(struct nameserver *ns) {
-	u8 packet[1500];
-	struct sockaddr_storage ss;
-	socklen_t addrlen = sizeof(ss);
-
-	for (;;) {
-          	const int r = recvfrom(ns->socket, packet, sizeof(packet), 0,
-		    (struct sockaddr*)&ss, &addrlen);
-		if (r < 0) {
-			int err = last_error(ns->socket);
-			if (error_is_eagain(err)) return;
-			nameserver_failed(ns, strerror(err));
-			return;
-		}
-		if (!address_is_correct(ns, (struct sockaddr*)&ss, addrlen)) {
-			log(EVDNS_LOG_WARN, "Address mismatch on received "
-			    "DNS packet.");
-			return;
-		}
-		ns->timedout = 0;
-		reply_parse(packet, r);
-	}
-}
-
-/* Read a packet from a DNS client on a server port s, parse it, and */
-/* act accordingly. */
-static void
-server_port_read(struct evdns_server_port *s) {
-	u8 packet[1500];
-	struct sockaddr_storage addr;
-	socklen_t addrlen;
-	int r;
-
-	for (;;) {
-		addrlen = sizeof(struct sockaddr_storage);
-		r = recvfrom(s->socket, packet, sizeof(packet), 0,
-					 (struct sockaddr*) &addr, &addrlen);
-		if (r < 0) {
-			int err = last_error(s->socket);
-			if (error_is_eagain(err)) return;
-			log(EVDNS_LOG_WARN, "Error %s (%d) while reading request.",
-				strerror(err), err);
-			return;
-		}
-		request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
-	}
-}
-
-/* Try to write all pending replies on a given DNS server port. */
-static void
-server_port_flush(struct evdns_server_port *port)
-{
-	while (port->pending_replies) {
-		struct server_request *req = port->pending_replies;
-		int r = sendto(port->socket, req->response, req->response_len, 0,
-			   (struct sockaddr*) &req->addr, req->addrlen);
-		if (r < 0) {
-			int err = last_error(port->socket);
-			if (error_is_eagain(err))
-				return;
-			log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", strerror(err), err);
-		}
-		if (server_request_free(req)) {
-			/* we released the last reference to req->port. */
-			return;
-		}
-	}
-
-	/* We have no more pending requests; stop listening for 'writeable' events. */
-	(void) event_del(&port->event);
-	event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
-			  server_port_ready_callback, port);
-	if (event_add(&port->event, NULL) < 0) {
-		log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
-		/* ???? Do more? */
-	}
-}
-
-/* set if we are waiting for the ability to write to this server. */
-/* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
-/* we stop these events. */
-static void
-nameserver_write_waiting(struct nameserver *ns, char waiting) {
-	if (ns->write_waiting == waiting) return;
-
-	ns->write_waiting = waiting;
-	(void) event_del(&ns->event);
-	event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
-			nameserver_ready_callback, ns);
-	if (event_add(&ns->event, NULL) < 0) {
-          log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
-              debug_ntoa(ns->address));
-          /* ???? Do more? */
-        }
-}
-
-/* a callback function. Called by libevent when the kernel says that */
-/* a nameserver socket is ready for writing or reading */
-static void
-nameserver_ready_callback(int fd, short events, void *arg) {
-	struct nameserver *ns = (struct nameserver *) arg;
-        (void)fd;
-
-	if (events & EV_WRITE) {
-		ns->choked = 0;
-		if (!evdns_transmit()) {
-			nameserver_write_waiting(ns, 0);
-		}
-	}
-	if (events & EV_READ) {
-		nameserver_read(ns);
-	}
-}
-
-/* a callback function. Called by libevent when the kernel says that */
-/* a server socket is ready for writing or reading. */
-static void
-server_port_ready_callback(int fd, short events, void *arg) {
-	struct evdns_server_port *port = (struct evdns_server_port *) arg;
-	(void) fd;
-
-	if (events & EV_WRITE) {
-		port->choked = 0;
-		server_port_flush(port);
-	}
-	if (events & EV_READ) {
-		server_port_read(port);
-	}
-}
-
-/* This is an inefficient representation; only use it via the dnslabel_table_*
- * functions, so that is can be safely replaced with something smarter later. */
-#define MAX_LABELS 128
-/* Structures used to implement name compression */
-struct dnslabel_entry { char *v; off_t pos; };
-struct dnslabel_table {
-	int n_labels; /* number of current entries */
-	/* map from name to position in message */
-	struct dnslabel_entry labels[MAX_LABELS];
-};
-
-/* Initialize dnslabel_table. */
-static void
-dnslabel_table_init(struct dnslabel_table *table)
-{
-	table->n_labels = 0;
-}
-
-/* Free all storage held by table, but not the table itself. */
-static void
-dnslabel_clear(struct dnslabel_table *table)
-{
-	int i;
-	for (i = 0; i < table->n_labels; ++i)
-		free(table->labels[i].v);
-	table->n_labels = 0;
-}
-
-/* return the position of the label in the current message, or -1 if the label */
-/* hasn't been used yet. */
-static int
-dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
-{
-	int i;
-	for (i = 0; i < table->n_labels; ++i) {
-		if (!strcmp(label, table->labels[i].v))
-			return table->labels[i].pos;
-	}
-	return -1;
-}
-
-/* remember that we've used the label at position pos */
-static int
-dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
-{
-	char *v;
-	int p;
-	if (table->n_labels == MAX_LABELS)
-		return (-1);
-	v = strdup(label);
-	if (v == NULL)
-		return (-1);
-	p = table->n_labels++;
-	table->labels[p].v = v;
-	table->labels[p].pos = pos;
-
-	return (0);
-}
-
-/* Converts a string to a length-prefixed set of DNS labels, starting */
-/* at buf[j]. name and buf must not overlap. name_len should be the length */
-/* of name.	 table is optional, and is used for compression. */
-/* */
-/* Input: abc.def */
-/* Output: <3>abc<3>def<0> */
-/* */
-/* Returns the first index after the encoded name, or negative on error. */
-/*	 -1	 label was > 63 bytes */
-/*	 -2	 name too long to fit in buffer. */
-/* */
-static off_t
-dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
-				  const char *name, const int name_len,
-				  struct dnslabel_table *table) {
-	const char *end = name + name_len;
-	int ref = 0;
-	u16 _t;
-
-#define APPEND16(x) do {						   \
-		if (j + 2 > (off_t)buf_len)				   \
-			goto overflow;						   \
-		_t = htons(x);							   \
-		memcpy(buf + j, &_t, 2);				   \
-		j += 2;									   \
-	} while (0)
-#define APPEND32(x) do {						   \
-		if (j + 4 > (off_t)buf_len)				   \
-			goto overflow;						   \
-		_t32 = htonl(x);						   \
-		memcpy(buf + j, &_t32, 4);				   \
-		j += 4;									   \
-	} while (0)
-
-	if (name_len > 255) return -2;
-
-	for (;;) {
-		const char *const start = name;
-		if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
-			APPEND16(ref | 0xc000);
-			return j;
-		}
-		name = strchr(name, '.');
-		if (!name) {
-			const unsigned int label_len = end - start;
-			if (label_len > 63) return -1;
-			if ((size_t)(j+label_len+1) > buf_len) return -2;
-			if (table) dnslabel_table_add(table, start, j);
-			buf[j++] = label_len;
-
-			memcpy(buf + j, start, end - start);
-			j += end - start;
-			break;
-		} else {
-			/* append length of the label. */
-			const unsigned int label_len = name - start;
-			if (label_len > 63) return -1;
-			if ((size_t)(j+label_len+1) > buf_len) return -2;
-			if (table) dnslabel_table_add(table, start, j);
-			buf[j++] = label_len;
-
-			memcpy(buf + j, start, name - start);
-			j += name - start;
-			/* hop over the '.' */
-			name++;
-		}
-	}
-
-	/* the labels must be terminated by a 0. */
-	/* It's possible that the name ended in a . */
-	/* in which case the zero is already there */
-	if (!j || buf[j-1]) buf[j++] = 0;
-	return j;
- overflow:
-	return (-2);
-}
-
-/* Finds the length of a dns request for a DNS name of the given */
-/* length. The actual request may be smaller than the value returned */
-/* here */
-static int
-evdns_request_len(const int name_len) {
-	return 96 + /* length of the DNS standard header */
-		name_len + 2 +
-		4;  /* space for the resource type */
-}
-
-/* build a dns request packet into buf. buf should be at least as long */
-/* as evdns_request_len told you it should be. */
-/* */
-/* Returns the amount of space used. Negative on error. */
-static int
-evdns_request_data_build(const char *const name, const int name_len,
-    const u16 trans_id, const u16 type, const u16 class,
-    u8 *const buf, size_t buf_len) {
-	off_t j = 0;  /* current offset into buf */
-	u16 _t;  /* used by the macros */
-
-	APPEND16(trans_id);
-	APPEND16(0x0100);  /* standard query, recusion needed */
-	APPEND16(1);  /* one question */
-	APPEND16(0);  /* no answers */
-	APPEND16(0);  /* no authority */
-	APPEND16(0);  /* no additional */
-
-	j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
-	if (j < 0) {
-		return (int)j;
-	}
-	
-	APPEND16(type);
-	APPEND16(class);
-
-	return (int)j;
- overflow:
-	return (-1);
-}
-
-/* exported function */
-struct evdns_server_port *
-evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type cb, void *user_data)
-{
-	struct evdns_server_port *port;
-	if (!(port = malloc(sizeof(struct evdns_server_port))))
-		return NULL;
-	memset(port, 0, sizeof(struct evdns_server_port));
-
-	assert(!is_tcp); /* TCP sockets not yet implemented */
-	port->socket = socket;
-	port->refcnt = 1;
-	port->choked = 0;
-	port->closing = 0;
-	port->user_callback = cb;
-	port->user_data = user_data;
-	port->pending_replies = NULL;
-
-	event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
-			  server_port_ready_callback, port);
-	event_add(&port->event, NULL); /* check return. */
-	return port;
-}
-
-/* exported function */
-void
-evdns_close_server_port(struct evdns_server_port *port)
-{
-	if (--port->refcnt == 0)
-		server_port_free(port);
-	port->closing = 1;
-}
-
-/* exported function */
-int
-evdns_server_request_add_reply(struct evdns_server_request *_req, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data)
-{
-	struct server_request *req = TO_SERVER_REQUEST(_req);
-	struct server_reply_item **itemp, *item;
-	int *countp;
-
-	if (req->response) /* have we already answered? */
-		return (-1);
-
-	switch (section) {
-	case EVDNS_ANSWER_SECTION:
-		itemp = &req->answer;
-		countp = &req->n_answer;
-		break;
-	case EVDNS_AUTHORITY_SECTION:
-		itemp = &req->authority;
-		countp = &req->n_authority;
-		break;
-	case EVDNS_ADDITIONAL_SECTION:
-		itemp = &req->additional;
-		countp = &req->n_additional;
-		break;
-	default:
-		return (-1);
-	}
-	while (*itemp) {
-		itemp = &((*itemp)->next);
-	}
-	item = malloc(sizeof(struct server_reply_item));
-	if (!item)
-		return -1;
-	item->next = NULL;
-	if (!(item->name = strdup(name))) {
-		free(item);
-		return -1;
-	}
-	item->type = type;
-	item->dns_question_class = class;
-	item->ttl = ttl;
-	item->is_name = is_name != 0;
-	item->datalen = 0;
-	item->data = NULL;
-	if (data) {
-		if (item->is_name) {
-			if (!(item->data = strdup(data))) {
-				free(item->name);
-				free(item);
-				return -1;
-			}
-			item->datalen = (u16)-1;
-		} else {
-			if (!(item->data = malloc(datalen))) {
-				free(item->name);
-				free(item);
-				return -1;
-			}
-			item->datalen = datalen;
-			memcpy(item->data, data, datalen);
-		}
-	}
-
-	*itemp = item;
-	++(*countp);
-	return 0;
-}
-
-/* exported function */
-int
-evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
-{
-	return evdns_server_request_add_reply(
-		  req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
-		  ttl, n*4, 0, addrs);
-}
-
-/* exported function */
-int
-evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
-{
-	return evdns_server_request_add_reply(
-		  req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
-		  ttl, n*16, 0, addrs);
-}
-
-/* exported function */
-int
-evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
-{
-	u32 a;
-	char buf[32];
-	assert(in || inaddr_name);
-	assert(!(in && inaddr_name));
-	if (in) {
-		a = ntohl(in->s_addr);
-		evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
-				(int)(u8)((a	)&0xff),
-				(int)(u8)((a>>8 )&0xff),
-				(int)(u8)((a>>16)&0xff),
-				(int)(u8)((a>>24)&0xff));
-		inaddr_name = buf;
-	}
-	return evdns_server_request_add_reply(
-		  req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
-		  ttl, -1, 1, hostname);
-}
-
-/* exported function */
-int
-evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
-{
-	return evdns_server_request_add_reply(
-		  req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
-		  ttl, -1, 1, cname);
-}
-
-
-static int
-evdns_server_request_format_response(struct server_request *req, int err)
-{
-	unsigned char buf[1500];
-	size_t buf_len = sizeof(buf);
-	off_t j = 0, r;
-	u16 _t;
-	u32 _t32;
-	int i;
-	u16 flags;
-	struct dnslabel_table table;
-
-	if (err < 0 || err > 15) return -1;
-
-	/* Set response bit and error code; copy OPCODE and RD fields from
-	 * question; copy RA and AA if set by caller. */
-	flags = req->base.flags;
-	flags |= (0x8000 | err);
-
-	dnslabel_table_init(&table);
-	APPEND16(req->trans_id);
-	APPEND16(flags);
-	APPEND16(req->base.nquestions);
-	APPEND16(req->n_answer);
-	APPEND16(req->n_authority);
-	APPEND16(req->n_additional);
-
-	/* Add questions. */
-	for (i=0; i < req->base.nquestions; ++i) {
-		const char *s = req->base.questions[i]->name;
-		j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
-		if (j < 0) {
-			dnslabel_clear(&table);
-			return (int) j;
-		}
-		APPEND16(req->base.questions[i]->type);
-		APPEND16(req->base.questions[i]->dns_question_class);
-	}
-
-	/* Add answer, authority, and additional sections. */
-	for (i=0; i<3; ++i) {
-		struct server_reply_item *item;
-		if (i==0)
-			item = req->answer;
-		else if (i==1)
-			item = req->authority;
-		else
-			item = req->additional;
-		while (item) {
-			r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
-			if (r < 0)
-				goto overflow;
-			j = r;
-
-			APPEND16(item->type);
-			APPEND16(item->dns_question_class);
-			APPEND32(item->ttl);
-			if (item->is_name) {
-				off_t len_idx = j, name_start;
-				j += 2;
-				name_start = j;
-				r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
-				if (r < 0)
-					goto overflow;
-				j = r;
-				_t = htons( (short) (j-name_start) );
-				memcpy(buf+len_idx, &_t, 2);
-			} else {
-				APPEND16(item->datalen);
-				if (j+item->datalen > (off_t)buf_len)
-					goto overflow;
-				memcpy(buf+j, item->data, item->datalen);
-				j += item->datalen;
-			}
-			item = item->next;
-		}
-	}
-
-	if (j > 512) {
-overflow:
-		j = 512;
-		buf[2] |= 0x02; /* set the truncated bit. */
-	}
-
-	req->response_len = j;
-
-	if (!(req->response = malloc(req->response_len))) {
-		server_request_free_answers(req);
-		dnslabel_clear(&table);
-		return (-1);
-	}
-	memcpy(req->response, buf, req->response_len);
-	server_request_free_answers(req);
-	dnslabel_clear(&table);
-	return (0);
-}
-
-/* exported function */
-int
-evdns_server_request_respond(struct evdns_server_request *_req, int err)
-{
-	struct server_request *req = TO_SERVER_REQUEST(_req);
-	struct evdns_server_port *port = req->port;
-	int r;
-	if (!req->response) {
-		if ((r = evdns_server_request_format_response(req, err))<0)
-			return r;
-	}
-
-	r = sendto(port->socket, req->response, req->response_len, 0,
-			   (struct sockaddr*) &req->addr, req->addrlen);
-	if (r<0) {
-		int sock_err = last_error(port->socket);
-		if (! error_is_eagain(sock_err))
-			return -1;
-
-		if (port->pending_replies) {
-			req->prev_pending = port->pending_replies->prev_pending;
-			req->next_pending = port->pending_replies;
-			req->prev_pending->next_pending =
-				req->next_pending->prev_pending = req;
-		} else {
-			req->prev_pending = req->next_pending = req;
-			port->pending_replies = req;
-			port->choked = 1;
-
-			(void) event_del(&port->event);
-			event_set(&port->event, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
-
-			if (event_add(&port->event, NULL) < 0) {
-				log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
-			}
-
-		}
-
-		return 1;
-	}
-	if (server_request_free(req))
-		return 0;
-
-	if (port->pending_replies)
-		server_port_flush(port);
-
-	return 0;
-}
-
-/* Free all storage held by RRs in req. */
-static void
-server_request_free_answers(struct server_request *req)
-{
-	struct server_reply_item *victim, *next, **list;
-	int i;
-	for (i = 0; i < 3; ++i) {
-		if (i==0)
-			list = &req->answer;
-		else if (i==1)
-			list = &req->authority;
-		else
-			list = &req->additional;
-
-		victim = *list;
-		while (victim) {
-			next = victim->next;
-			free(victim->name);
-			if (victim->data)
-				free(victim->data);
-			free(victim);
-			victim = next;
-		}
-		*list = NULL;
-	}
-}
-
-/* Free all storage held by req, and remove links to it. */
-/* return true iff we just wound up freeing the server_port. */
-static int
-server_request_free(struct server_request *req)
-{
-	int i, rc=1;
-	if (req->base.questions) {
-		for (i = 0; i < req->base.nquestions; ++i)
-			free(req->base.questions[i]);
-		free(req->base.questions);
-	}
-
-	if (req->port) {
-		if (req->port->pending_replies == req) {
-			if (req->next_pending)
-				req->port->pending_replies = req->next_pending;
-			else
-				req->port->pending_replies = NULL;
-		}
-		rc = --req->port->refcnt;
-	}
-
-	if (req->response) {
-		free(req->response);
-	}
-
-	server_request_free_answers(req);
-
-	if (req->next_pending && req->next_pending != req) {
-		req->next_pending->prev_pending = req->prev_pending;
-		req->prev_pending->next_pending = req->next_pending;
-	}
-
-	if (rc == 0) {
-		server_port_free(req->port);
-		free(req);
-		return (1);
-	}
-	free(req);
-	return (0);
-}
-
-/* Free all storage held by an evdns_server_port.  Only called when  */
-static void
-server_port_free(struct evdns_server_port *port)
-{
-	assert(port);
-	assert(!port->refcnt);
-	assert(!port->pending_replies);
-	if (port->socket > 0) {
-		CLOSE_SOCKET(port->socket);
-		port->socket = -1;
-	}
-	(void) event_del(&port->event);
-	/* XXXX actually free the port? -NM */
-}
-
-/* exported function */
-int
-evdns_server_request_drop(struct evdns_server_request *_req)
-{
-	struct server_request *req = TO_SERVER_REQUEST(_req);
-	server_request_free(req);
-	return 0;
-}
-
-/* exported function */
-int
-evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
-{
-	struct server_request *req = TO_SERVER_REQUEST(_req);
-	if (addr_len < (int)req->addrlen)
-		return -1;
-	memcpy(sa, &(req->addr), req->addrlen);
-	return req->addrlen;
-}
-
-#undef APPEND16
-#undef APPEND32
-
-/* this is a libevent callback function which is called when a request */
-/* has timed out. */
-static void
-evdns_request_timeout_callback(int fd, short events, void *arg) {
-	struct request *const req = (struct request *) arg;
-        (void) fd;
-        (void) events;
-
-	log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
-
-	req->ns->timedout++;
-	if (req->ns->timedout > global_max_nameserver_timeout) {
-		req->ns->timedout = 0;
-		nameserver_failed(req->ns, "request timed out.");
-	}
-
-	(void) evtimer_del(&req->timeout_event);
-	if (req->tx_count >= global_max_retransmits) {
-		/* this request has failed */
-		reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
-		request_finished(req, &req_head);
-	} else {
-		/* retransmit it */
-		evdns_request_transmit(req);
-	}
-}
-
-/* try to send a request to a given server. */
-/* */
-/* return: */
-/*   0 ok */
-/*   1 temporary failure */
-/*   2 other failure */
-static int
-evdns_request_transmit_to(struct request *req, struct nameserver *server) {
-	struct sockaddr_in sin;
-	int r;
-	memset(&sin, 0, sizeof(sin));
-	sin.sin_addr.s_addr = req->ns->address;
-	sin.sin_port = req->ns->port;
-	sin.sin_family = AF_INET;
-
-	r = sendto(server->socket, req->request, req->request_len, 0,
-	    (struct sockaddr*)&sin, sizeof(sin));
-	if (r < 0) {
-		int err = last_error(server->socket);
-		if (error_is_eagain(err)) return 1;
-		nameserver_failed(req->ns, strerror(err));
-		return 2;
-	} else if (r != (int)req->request_len) {
-		return 1;  /* short write */
-	} else {
-		return 0;
-	}
-}
-
-/* try to send a request, updating the fields of the request */
-/* as needed */
-/* */
-/* return: */
-/*   0 ok */
-/*   1 failed */
-static int
-evdns_request_transmit(struct request *req) {
-	int retcode = 0, r;
-
-	/* if we fail to send this packet then this flag marks it */
-	/* for evdns_transmit */
-	req->transmit_me = 1;
-	if (req->trans_id == 0xffff) abort();
-
-	if (req->ns->choked) {
-		/* don't bother trying to write to a socket */
-		/* which we have had EAGAIN from */
-		return 1;
-	}
-
-	r = evdns_request_transmit_to(req, req->ns);
-	switch (r) {
-	case 1:
-		/* temp failure */
-		req->ns->choked = 1;
-		nameserver_write_waiting(req->ns, 1);
-		return 1;
-	case 2:
-		/* failed in some other way */
-		retcode = 1;
-		/* fall through */
-	default:
-		/* all ok */
-		log(EVDNS_LOG_DEBUG,
-		    "Setting timeout for request %lx", (unsigned long) req);
-		if (evtimer_add(&req->timeout_event, &global_timeout) < 0) {
-                  log(EVDNS_LOG_WARN,
-		      "Error from libevent when adding timer for request %lx",
-                      (unsigned long) req);
-                  /* ???? Do more? */
-                }
-		req->tx_count++;
-		req->transmit_me = 0;
-		return retcode;
-	}
-}
-
-static void
-nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
-	struct nameserver *const ns = (struct nameserver *) arg;
-        (void) type;
-        (void) count;
-        (void) ttl;
-        (void) addresses;
-
-	if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
-		/* this is a good reply */
-		nameserver_up(ns);
-	} else nameserver_probe_failed(ns);
-}
-
-static void
-nameserver_send_probe(struct nameserver *const ns) {
-	struct request *req;
-	/* here we need to send a probe to a given nameserver */
-	/* in the hope that it is up now. */
-
-  	log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntoa(ns->address));
-
-	req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
-        if (!req) return;
-	/* we force this into the inflight queue no matter what */
-	request_trans_id_set(req, transaction_id_pick());
-	req->ns = ns;
-	request_submit(req);
-}
-
-/* returns: */
-/*   0 didn't try to transmit anything */
-/*   1 tried to transmit something */
-static int
-evdns_transmit(void) {
-	char did_try_to_transmit = 0;
-
-	if (req_head) {
-		struct request *const started_at = req_head, *req = req_head;
-		/* first transmit all the requests which are currently waiting */
-		do {
-			if (req->transmit_me) {
-				did_try_to_transmit = 1;
-				evdns_request_transmit(req);
-			}
-
-			req = req->next;
-		} while (req != started_at);
-	}
-
-	return did_try_to_transmit;
-}
-
-/* exported function */
-int
-evdns_count_nameservers(void)
-{
-	const struct nameserver *server = server_head;
-	int n = 0;
-	if (!server)
-		return 0;
-	do {
-		++n;
-		server = server->next;
-	} while (server != server_head);
-	return n;
-}
-
-/* exported function */
-int
-evdns_clear_nameservers_and_suspend(void)
-{
-	struct nameserver *server = server_head, *started_at = server_head;
-	struct request *req = req_head, *req_started_at = req_head;
-
-	if (!server)
-		return 0;
-	while (1) {
-		struct nameserver *next = server->next;
-		(void) event_del(&server->event);
-		if (evtimer_initialized(&server->timeout_event))
-			(void) evtimer_del(&server->timeout_event);
-		if (server->socket >= 0)
-			CLOSE_SOCKET(server->socket);
-		free(server);
-		if (next == started_at)
-			break;
-		server = next;
-	}
-	server_head = NULL;
-	global_good_nameservers = 0;
-
-	while (req) {
-		struct request *next = req->next;
-		req->tx_count = req->reissue_count = 0;
-		req->ns = NULL;
-		/* ???? What to do about searches? */
-		(void) evtimer_del(&req->timeout_event);
-		req->trans_id = 0;
-		req->transmit_me = 0;
-
-		global_requests_waiting++;
-		evdns_request_insert(req, &req_waiting_head);
-		/* We want to insert these suspended elements at the front of
-		 * the waiting queue, since they were pending before any of
-		 * the waiting entries were added.  This is a circular list,
-		 * so we can just shift the start back by one.*/
-		req_waiting_head = req_waiting_head->prev;
-
-		if (next == req_started_at)
-			break;
-		req = next;
-	}
-	req_head = NULL;
-	global_requests_inflight = 0;
-
-	return 0;
-}
-
-
-/* exported function */
-int
-evdns_resume(void)
-{
-	evdns_requests_pump_waiting_queue();
-	return 0;
-}
-
-static int
-_evdns_nameserver_add_impl(unsigned long int address, int port) {
-	/* first check to see if we already have this nameserver */
-
-	const struct nameserver *server = server_head, *const started_at = server_head;
-	struct nameserver *ns;
-	int err = 0;
-	if (server) {
-		do {
-			if (server->address == address) return 3;
-			server = server->next;
-		} while (server != started_at);
-	}
-
-	ns = (struct nameserver *) malloc(sizeof(struct nameserver));
-        if (!ns) return -1;
-
-	memset(ns, 0, sizeof(struct nameserver));
-
-	evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
-
-	ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
-	if (ns->socket < 0) { err = 1; goto out1; }
-	FD_CLOSEONEXEC(ns->socket);
-	evutil_make_socket_nonblocking(ns->socket);
-
-	ns->address = address;
-	ns->port = htons(port);
-	ns->state = 1;
-	event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
-	if (event_add(&ns->event, NULL) < 0) {
-          err = 2;
-          goto out2;
-        }
-
-	log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntoa(address));
-
-	/* insert this nameserver into the list of them */
-	if (!server_head) {
-		ns->next = ns->prev = ns;
-		server_head = ns;
-	} else {
-		ns->next = server_head->next;
-		ns->prev = server_head;
-		server_head->next = ns;
-		if (server_head->prev == server_head) {
-			server_head->prev = ns;
-		}
-	}
-
-	global_good_nameservers++;
-
-	return 0;
-
-out2:
-	CLOSE_SOCKET(ns->socket);
-out1:
-	free(ns);
-	log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntoa(address), err);
-	return err;
-}
-
-/* exported function */
-int
-evdns_nameserver_add(unsigned long int address) {
-	return _evdns_nameserver_add_impl(address, 53);
-}
-
-/* exported function */
-int
-evdns_nameserver_ip_add(const char *ip_as_string) {
-	struct in_addr ina;
-	int port;
-	char buf[20];
-	const char *cp;
-	cp = strchr(ip_as_string, ':');
-	if (! cp) {
-		cp = ip_as_string;
-		port = 53;
-	} else {
-		port = strtoint(cp+1);
-		if (port < 0 || port > 65535) {
-			return 4;
-		}
-		if ((cp-ip_as_string) >= (int)sizeof(buf)) {
-			return 4;
-		}
-		memcpy(buf, ip_as_string, cp-ip_as_string);
-		buf[cp-ip_as_string] = '\0';
-		cp = buf;
-	}
-	if (!inet_aton(cp, &ina)) {
-		return 4;
-	}
-	return _evdns_nameserver_add_impl(ina.s_addr, port);
-}
-
-/* insert into the tail of the queue */
-static void
-evdns_request_insert(struct request *req, struct request **head) {
-	if (!*head) {
-		*head = req;
-		req->next = req->prev = req;
-		return;
-	}
-
-	req->prev = (*head)->prev;
-	req->prev->next = req;
-	req->next = *head;
-	(*head)->prev = req;
-}
-
-static int
-string_num_dots(const char *s) {
-	int count = 0;
-	while ((s = strchr(s, '.'))) {
-		s++;
-		count++;
-	}
-	return count;
-}
-
-static struct request *
-request_new(int type, const char *name, int flags,
-    evdns_callback_type callback, void *user_ptr) {
-	const char issuing_now =
-	    (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
-
-	const int name_len = strlen(name);
-	const int request_max_len = evdns_request_len(name_len);
-	const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
-	/* the request data is alloced in a single block with the header */
-	struct request *const req =
-	    (struct request *) malloc(sizeof(struct request) + request_max_len);
-	int rlen;
-        (void) flags;
-
-        if (!req) return NULL;
-	memset(req, 0, sizeof(struct request));
-
-	evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
-
-	/* request data lives just after the header */
-	req->request = ((u8 *) req) + sizeof(struct request);
-	/* denotes that the request data shouldn't be free()ed */
-	req->request_appended = 1;
-	rlen = evdns_request_data_build(name, name_len, trans_id,
-	    type, CLASS_INET, req->request, request_max_len);
-	if (rlen < 0)
-		goto err1;
-	req->request_len = rlen;
-	req->trans_id = trans_id;
-	req->tx_count = 0;
-	req->request_type = type;
-	req->user_pointer = user_ptr;
-	req->user_callback = callback;
-	req->ns = issuing_now ? nameserver_pick() : NULL;
-	req->next = req->prev = NULL;
-
-	return req;
-err1:
-	free(req);
-	return NULL;
-}
-
-static void
-request_submit(struct request *const req) {
-	if (req->ns) {
-		/* if it has a nameserver assigned then this is going */
-		/* straight into the inflight queue */
-		evdns_request_insert(req, &req_head);
-		global_requests_inflight++;
-		evdns_request_transmit(req);
-	} else {
-		evdns_request_insert(req, &req_waiting_head);
-		global_requests_waiting++;
-	}
-}
-
-/* exported function */
-int evdns_resolve_ipv4(const char *name, int flags,
-    evdns_callback_type callback, void *ptr) {
-	log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
-	if (flags & DNS_QUERY_NO_SEARCH) {
-		struct request *const req =
-			request_new(TYPE_A, name, flags, callback, ptr);
-		if (req == NULL)
-			return (1);
-		request_submit(req);
-		return (0);
-	} else {
-		return (search_request_new(TYPE_A, name, flags, callback, ptr));
-	}
-}
-
-/* exported function */
-int evdns_resolve_ipv6(const char *name, int flags,
-					   evdns_callback_type callback, void *ptr) {
-	log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
-	if (flags & DNS_QUERY_NO_SEARCH) {
-		struct request *const req =
-			request_new(TYPE_AAAA, name, flags, callback, ptr);
-		if (req == NULL)
-			return (1);
-		request_submit(req);
-		return (0);
-	} else {
-		return (search_request_new(TYPE_AAAA, name, flags, callback, ptr));
-	}
-}
-
-int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
-	char buf[32];
-	struct request *req;
-	u32 a;
-	assert(in);
-	a = ntohl(in->s_addr);
-	evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
-			(int)(u8)((a	)&0xff),
-			(int)(u8)((a>>8 )&0xff),
-			(int)(u8)((a>>16)&0xff),
-			(int)(u8)((a>>24)&0xff));
-	log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
-	req = request_new(TYPE_PTR, buf, flags, callback, ptr);
-	if (!req) return 1;
-	request_submit(req);
-	return 0;
-}
-
-int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
-	/* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
-	char buf[73];
-	char *cp;
-	struct request *req;
-	int i;
-	assert(in);
-	cp = buf;
-	for (i=15; i >= 0; --i) {
-		u8 byte = in->s6_addr[i];
-		*cp++ = "0123456789abcdef"[byte & 0x0f];
-		*cp++ = '.';
-		*cp++ = "0123456789abcdef"[byte >> 4];
-		*cp++ = '.';
-	}
-	assert(cp + strlen("ip6.arpa") < buf+sizeof(buf));
-	memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
-	log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
-	req = request_new(TYPE_PTR, buf, flags, callback, ptr);
-	if (!req) return 1;
-	request_submit(req);
-	return 0;
-}
-
-/*/////////////////////////////////////////////////////////////////// */
-/* Search support */
-/* */
-/* the libc resolver has support for searching a number of domains */
-/* to find a name. If nothing else then it takes the single domain */
-/* from the gethostname() call. */
-/* */
-/* It can also be configured via the domain and search options in a */
-/* resolv.conf. */
-/* */
-/* The ndots option controls how many dots it takes for the resolver */
-/* to decide that a name is non-local and so try a raw lookup first. */
-
-struct search_domain {
-	int len;
-	struct search_domain *next;
-	/* the text string is appended to this structure */
-};
-
-struct search_state {
-	int refcount;
-	int ndots;
-	int num_domains;
-	struct search_domain *head;
-};
-
-static struct search_state *global_search_state = NULL;
-
-static void
-search_state_decref(struct search_state *const state) {
-	if (!state) return;
-	state->refcount--;
-	if (!state->refcount) {
-		struct search_domain *next, *dom;
-		for (dom = state->head; dom; dom = next) {
-			next = dom->next;
-			free(dom);
-		}
-		free(state);
-	}
-}
-
-static struct search_state *
-search_state_new(void) {
-	struct search_state *state = (struct search_state *) malloc(sizeof(struct search_state));
-        if (!state) return NULL;
-	memset(state, 0, sizeof(struct search_state));
-	state->refcount = 1;
-	state->ndots = 1;
-
-	return state;
-}
-
-static void
-search_postfix_clear(void) {
-	search_state_decref(global_search_state);
-
-	global_search_state = search_state_new();
-}
-
-/* exported function */
-void
-evdns_search_clear(void) {
-	search_postfix_clear();
-}
-
-static void
-search_postfix_add(const char *domain) {
-	int domain_len;
-	struct search_domain *sdomain;
-	while (domain[0] == '.') domain++;
-	domain_len = strlen(domain);
-
-	if (!global_search_state) global_search_state = search_state_new();
-        if (!global_search_state) return;
-	global_search_state->num_domains++;
-
-	sdomain = (struct search_domain *) malloc(sizeof(struct search_domain) + domain_len);
-        if (!sdomain) return;
-	memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
-	sdomain->next = global_search_state->head;
-	sdomain->len = domain_len;
-
-	global_search_state->head = sdomain;
-}
-
-/* reverse the order of members in the postfix list. This is needed because, */
-/* when parsing resolv.conf we push elements in the wrong order */
-static void
-search_reverse(void) {
-	struct search_domain *cur, *prev = NULL, *next;
-	cur = global_search_state->head;
-	while (cur) {
-		next = cur->next;
-		cur->next = prev;
-		prev = cur;
-		cur = next;
-	}
-
-	global_search_state->head = prev;
-}
-
-/* exported function */
-void
-evdns_search_add(const char *domain) {
-	search_postfix_add(domain);
-}
-
-/* exported function */
-void
-evdns_search_ndots_set(const int ndots) {
-	if (!global_search_state) global_search_state = search_state_new();
-        if (!global_search_state) return;
-	global_search_state->ndots = ndots;
-}
-
-static void
-search_set_from_hostname(void) {
-	char hostname[HOST_NAME_MAX + 1], *domainname;
-
-	search_postfix_clear();
-	if (gethostname(hostname, sizeof(hostname))) return;
-	domainname = strchr(hostname, '.');
-	if (!domainname) return;
-	search_postfix_add(domainname);
-}
-
-/* warning: returns malloced string */
-static char *
-search_make_new(const struct search_state *const state, int n, const char *const base_name) {
-	const int base_len = strlen(base_name);
-	const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
-	struct search_domain *dom;
-
-	for (dom = state->head; dom; dom = dom->next) {
-		if (!n--) {
-			/* this is the postfix we want */
-			/* the actual postfix string is kept at the end of the structure */
-			const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
-			const int postfix_len = dom->len;
-			char *const newname = (char *) malloc(base_len + need_to_append_dot + postfix_len + 1);
-                        if (!newname) return NULL;
-			memcpy(newname, base_name, base_len);
-			if (need_to_append_dot) newname[base_len] = '.';
-			memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
-			newname[base_len + need_to_append_dot + postfix_len] = 0;
-			return newname;
-		}
-	}
-
-	/* we ran off the end of the list and still didn't find the requested string */
-	abort();
-	return NULL; /* unreachable; stops warnings in some compilers. */
-}
-
-static int
-search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
-	assert(type == TYPE_A || type == TYPE_AAAA);
-	if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
-	     global_search_state &&
-		 global_search_state->num_domains) {
-		/* we have some domains to search */
-		struct request *req;
-		if (string_num_dots(name) >= global_search_state->ndots) {
-			req = request_new(type, name, flags, user_callback, user_arg);
-			if (!req) return 1;
-			req->search_index = -1;
-		} else {
-			char *const new_name = search_make_new(global_search_state, 0, name);
-                        if (!new_name) return 1;
-			req = request_new(type, new_name, flags, user_callback, user_arg);
-			free(new_name);
-			if (!req) return 1;
-			req->search_index = 0;
-		}
-		req->search_origname = strdup(name);
-		req->search_state = global_search_state;
-		req->search_flags = flags;
-		global_search_state->refcount++;
-		request_submit(req);
-		return 0;
-	} else {
-		struct request *const req = request_new(type, name, flags, user_callback, user_arg);
-		if (!req) return 1;
-		request_submit(req);
-		return 0;
-	}
-}
-
-/* this is called when a request has failed to find a name. We need to check */
-/* if it is part of a search and, if so, try the next name in the list */
-/* returns: */
-/*   0 another request has been submitted */
-/*   1 no more requests needed */
-static int
-search_try_next(struct request *const req) {
-	if (req->search_state) {
-		/* it is part of a search */
-		char *new_name;
-		struct request *newreq;
-		req->search_index++;
-		if (req->search_index >= req->search_state->num_domains) {
-			/* no more postfixes to try, however we may need to try */
-			/* this name without a postfix */
-			if (string_num_dots(req->search_origname) < req->search_state->ndots) {
-				/* yep, we need to try it raw */
-				newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
-				log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
-				if (newreq) {
-					request_submit(newreq);
-					return 0;
-				}
-			}
-			return 1;
-		}
-
-		new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
-                if (!new_name) return 1;
-		log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
-		newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
-		free(new_name);
-		if (!newreq) return 1;
-		newreq->search_origname = req->search_origname;
-		req->search_origname = NULL;
-		newreq->search_state = req->search_state;
-		newreq->search_flags = req->search_flags;
-		newreq->search_index = req->search_index;
-		newreq->search_state->refcount++;
-		request_submit(newreq);
-		return 0;
-	}
-	return 1;
-}
-
-static void
-search_request_finished(struct request *const req) {
-	if (req->search_state) {
-		search_state_decref(req->search_state);
-		req->search_state = NULL;
-	}
-	if (req->search_origname) {
-		free(req->search_origname);
-		req->search_origname = NULL;
-	}
-}
-
-/*/////////////////////////////////////////////////////////////////// */
-/* Parsing resolv.conf files */
-
-static void
-evdns_resolv_set_defaults(int flags) {
-	/* if the file isn't found then we assume a local resolver */
-	if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
-	if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1");
-}
-
-#ifndef HAVE_STRTOK_R
-static char *
-strtok_r(char *s, const char *delim, char **state) {
-	return strtok(s, delim);
-}
-#endif
-
-/* helper version of atoi which returns -1 on error */
-static int
-strtoint(const char *const str) {
-	char *endptr;
-	const int r = strtol(str, &endptr, 10);
-	if (*endptr) return -1;
-	return r;
-}
-
-/* helper version of atoi that returns -1 on error and clips to bounds. */
-static int
-strtoint_clipped(const char *const str, int min, int max)
-{
-	int r = strtoint(str);
-	if (r == -1)
-		return r;
-	else if (r<min)
-		return min;
-	else if (r>max)
-		return max;
-	else
-		return r;
-}
-
-/* exported function */
-int
-evdns_set_option(const char *option, const char *val, int flags)
-{
-	if (!strncmp(option, "ndots:", 6)) {
-		const int ndots = strtoint(val);
-		if (ndots == -1) return -1;
-		if (!(flags & DNS_OPTION_SEARCH)) return 0;
-		log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
-		if (!global_search_state) global_search_state = search_state_new();
-		if (!global_search_state) return -1;
-		global_search_state->ndots = ndots;
-	} else if (!strncmp(option, "timeout:", 8)) {
-		const int timeout = strtoint(val);
-		if (timeout == -1) return -1;
-		if (!(flags & DNS_OPTION_MISC)) return 0;
-		log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
-		global_timeout.tv_sec = timeout;
-	} else if (!strncmp(option, "max-timeouts:", 12)) {
-		const int maxtimeout = strtoint_clipped(val, 1, 255);
-		if (maxtimeout == -1) return -1;
-		if (!(flags & DNS_OPTION_MISC)) return 0;
-		log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
-			maxtimeout);
-		global_max_nameserver_timeout = maxtimeout;
-	} else if (!strncmp(option, "max-inflight:", 13)) {
-		const int maxinflight = strtoint_clipped(val, 1, 65000);
-		if (maxinflight == -1) return -1;
-		if (!(flags & DNS_OPTION_MISC)) return 0;
-		log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
-			maxinflight);
-		global_max_requests_inflight = maxinflight;
-	} else if (!strncmp(option, "attempts:", 9)) {
-		int retries = strtoint(val);
-		if (retries == -1) return -1;
-		if (retries > 255) retries = 255;
-		if (!(flags & DNS_OPTION_MISC)) return 0;
-		log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
-		global_max_retransmits = retries;
-	}
-	return 0;
-}
-
-static void
-resolv_conf_parse_line(char *const start, int flags) {
-	char *strtok_state;
-	static const char *const delims = " \t";
-#define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
-
-	char *const first_token = strtok_r(start, delims, &strtok_state);
-	if (!first_token) return;
-
-	if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
-		const char *const nameserver = NEXT_TOKEN;
-		struct in_addr ina;
-
-		if (nameserver && inet_aton(nameserver, &ina)) {
-			/* address is valid */
-			evdns_nameserver_add(ina.s_addr);
-		}
-	} else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
-		const char *const domain = NEXT_TOKEN;
-		if (domain) {
-			search_postfix_clear();
-			search_postfix_add(domain);
-		}
-	} else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
-		const char *domain;
-		search_postfix_clear();
-
-		while ((domain = NEXT_TOKEN)) {
-			search_postfix_add(domain);
-		}
-		search_reverse();
-	} else if (!strcmp(first_token, "options")) {
-		const char *option;
-		while ((option = NEXT_TOKEN)) {
-			const char *val = strchr(option, ':');
-			evdns_set_option(option, val ? val+1 : "", flags);
-		}
-	}
-#undef NEXT_TOKEN
-}
-
-/* exported function */
-/* returns: */
-/*   0 no errors */
-/*   1 failed to open file */
-/*   2 failed to stat file */
-/*   3 file too large */
-/*   4 out of memory */
-/*   5 short read from file */
-int
-evdns_resolv_conf_parse(int flags, const char *const filename) {
-	struct stat st;
-	int fd, n, r;
-	u8 *resolv;
-	char *start;
-	int err = 0;
-
-	log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
-
-	fd = open(filename, O_RDONLY);
-	if (fd < 0) {
-		evdns_resolv_set_defaults(flags);
-		return 1;
-	}
-
-	if (fstat(fd, &st)) { err = 2; goto out1; }
-	if (!st.st_size) {
-		evdns_resolv_set_defaults(flags);
-		err = (flags & DNS_OPTION_NAMESERVERS) ? 6 : 0;
-		goto out1;
-	}
-	if (st.st_size > 65535) { err = 3; goto out1; }  /* no resolv.conf should be any bigger */
-
-	resolv = (u8 *) malloc((size_t)st.st_size + 1);
-	if (!resolv) { err = 4; goto out1; }
-
-	n = 0;
-	while ((r = read(fd, resolv+n, (size_t)st.st_size-n)) > 0) {
-		n += r;
-		if (n == st.st_size)
-			break;
-		assert(n < st.st_size);
- 	}
-	if (r < 0) { err = 5; goto out2; }
-	resolv[n] = 0;	 /* we malloced an extra byte; this should be fine. */
-
-	start = (char *) resolv;
-	for (;;) {
-		char *const newline = strchr(start, '\n');
-		if (!newline) {
-			resolv_conf_parse_line(start, flags);
-			break;
-		} else {
-			*newline = 0;
-			resolv_conf_parse_line(start, flags);
-			start = newline + 1;
-		}
-	}
-
-	if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
-		/* no nameservers were configured. */
-		evdns_nameserver_ip_add("127.0.0.1");
-		err = 6;
-	}
-	if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
-		search_set_from_hostname();
-	}
-
-out2:
-	free(resolv);
-out1:
-	close(fd);
-	return err;
-}
-
-#ifdef WIN32
-/* Add multiple nameservers from a space-or-comma-separated list. */
-static int
-evdns_nameserver_ip_add_line(const char *ips) {
-	const char *addr;
-	char *buf;
-	int r;
-	while (*ips) {
-		while (ISSPACE(*ips) || *ips == ',' || *ips == '\t')
-			++ips;
-		addr = ips;
-		while (ISDIGIT(*ips) || *ips == '.' || *ips == ':')
-			++ips;
-		buf = malloc(ips-addr+1);
-		if (!buf) return 4;
-		memcpy(buf, addr, ips-addr);
-		buf[ips-addr] = '\0';
-		r = evdns_nameserver_ip_add(buf);
-		free(buf);
-		if (r) return r;
-	}
-	return 0;
-}
-
-typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
-
-/* Use the windows GetNetworkParams interface in iphlpapi.dll to */
-/* figure out what our nameservers are. */
-static int
-load_nameservers_with_getnetworkparams(void)
-{
-	/* Based on MSDN examples and inspection of  c-ares code. */
-	FIXED_INFO *fixed;
-	HMODULE handle = 0;
-	ULONG size = sizeof(FIXED_INFO);
-	void *buf = NULL;
-	int status = 0, r, added_any;
-	IP_ADDR_STRING *ns;
-	GetNetworkParams_fn_t fn;
-
-	if (!(handle = LoadLibraryA("iphlpapi.dll"))) {
-		log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
-		status = -1;
-		goto done;
-	}
-	if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
-		log(EVDNS_LOG_WARN, "Could not get address of function.");
-		status = -1;
-		goto done;
-	}
-
-	buf = malloc(size);
-	if (!buf) { status = 4; goto done; }
-	fixed = buf;
-	r = fn(fixed, &size);
-	if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
-		status = -1;
-		goto done;
-	}
-	if (r != ERROR_SUCCESS) {
-		free(buf);
-		buf = malloc(size);
-		if (!buf) { status = 4; goto done; }
-		fixed = buf;
-		r = fn(fixed, &size);
-		if (r != ERROR_SUCCESS) {
-			log(EVDNS_LOG_DEBUG, "fn() failed.");
-			status = -1;
-			goto done;
-		}
-	}
-
-	assert(fixed);
-	added_any = 0;
-	ns = &(fixed->DnsServerList);
-	while (ns) {
-		r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
-		if (r) {
-			log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
-				(ns->IpAddress.String),(int)GetLastError());
-			status = r;
-			goto done;
-		} else {
-			log(EVDNS_LOG_DEBUG,"Succesfully added %s as nameserver",ns->IpAddress.String);
-		}
-
-		added_any++;
-		ns = ns->Next;
-	}
-
-	if (!added_any) {
-		log(EVDNS_LOG_DEBUG, "No nameservers added.");
-		status = -1;
-	}
-
- done:
-	if (buf)
-		free(buf);
-	if (handle)
-		FreeLibrary(handle);
-	return status;
-}
-
-static int
-config_nameserver_from_reg_key(HKEY key, const char *subkey)
-{
-	char *buf;
-	DWORD bufsz = 0, type = 0;
-	int status = 0;
-
-	if (RegQueryValueExA(key, subkey, 0, &type, NULL, &bufsz)
-	    != ERROR_MORE_DATA)
-		return -1;
-	if (!(buf = malloc(bufsz)))
-		return -1;
-
-	if (RegQueryValueExA(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
-	    == ERROR_SUCCESS && bufsz > 1) {
-		status = evdns_nameserver_ip_add_line(buf);
-	}
-
-	free(buf);
-	return status;
-}
-
-#define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
-#define WIN_NS_9X_KEY  SERVICES_KEY "VxD\\MSTCP"
-#define WIN_NS_NT_KEY  SERVICES_KEY "Tcpip\\Parameters"
-
-static int
-load_nameservers_from_registry(void)
-{
-	int found = 0;
-	int r;
-#define TRY(k, name) \
-	if (!found && config_nameserver_from_reg_key(k,name) == 0) {	\
-		log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
-		found = 1;						\
-	} else if (!found) {						\
-		log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
-		    #k,#name);						\
-	}
-
-	if (((int)GetVersion()) > 0) { /* NT */
-		HKEY nt_key = 0, interfaces_key = 0;
-
-		if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
-				 KEY_READ, &nt_key) != ERROR_SUCCESS) {
-			log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
-			return -1;
-		}
-		r = RegOpenKeyExA(nt_key, "Interfaces", 0,
-			     KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
-			     &interfaces_key);
-		if (r != ERROR_SUCCESS) {
-			log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
-			return -1;
-		}
-		TRY(nt_key, "NameServer");
-		TRY(nt_key, "DhcpNameServer");
-		TRY(interfaces_key, "NameServer");
-		TRY(interfaces_key, "DhcpNameServer");
-		RegCloseKey(interfaces_key);
-		RegCloseKey(nt_key);
-	} else {
-		HKEY win_key = 0;
-		if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
-				 KEY_READ, &win_key) != ERROR_SUCCESS) {
-			log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
-			return -1;
-		}
-		TRY(win_key, "NameServer");
-		RegCloseKey(win_key);
-	}
-
-	if (found == 0) {
-		log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
-	}
-
-	return found ? 0 : -1;
-#undef TRY
-}
-
-int
-evdns_config_windows_nameservers(void)
-{
-	if (load_nameservers_with_getnetworkparams() == 0)
-		return 0;
-	return load_nameservers_from_registry();
-}
-#endif
-
-int
-evdns_init(void)
-{
-	int res = 0;
-#ifdef WIN32
-	res = evdns_config_windows_nameservers();
-#else
-	res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
-#endif
-
-	return (res);
-}
-
-const char *
-evdns_err_to_string(int err)
-{
-    switch (err) {
-	case DNS_ERR_NONE: return "no error";
-	case DNS_ERR_FORMAT: return "misformatted query";
-	case DNS_ERR_SERVERFAILED: return "server failed";
-	case DNS_ERR_NOTEXIST: return "name does not exist";
-	case DNS_ERR_NOTIMPL: return "query not implemented";
-	case DNS_ERR_REFUSED: return "refused";
-
-	case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
-	case DNS_ERR_UNKNOWN: return "unknown";
-	case DNS_ERR_TIMEOUT: return "request timed out";
-	case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
-	default: return "[Unknown error code]";
-    }
-}
-
-void
-evdns_shutdown(int fail_requests)
-{
-	struct nameserver *server, *server_next;
-	struct search_domain *dom, *dom_next;
-
-	while (req_head) {
-		if (fail_requests)
-			reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
-		request_finished(req_head, &req_head);
-	}
-	while (req_waiting_head) {
-		if (fail_requests)
-			reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
-		request_finished(req_waiting_head, &req_waiting_head);
-	}
-	global_requests_inflight = global_requests_waiting = 0;
-
-	for (server = server_head; server; server = server_next) {
-		server_next = server->next;
-		if (server->socket >= 0)
-			CLOSE_SOCKET(server->socket);
-		(void) event_del(&server->event);
-		if (server->state == 0)
-                        (void) event_del(&server->timeout_event);
-		free(server);
-		if (server_next == server_head)
-			break;
-	}
-	server_head = NULL;
-	global_good_nameservers = 0;
-
-	if (global_search_state) {
-		for (dom = global_search_state->head; dom; dom = dom_next) {
-			dom_next = dom->next;
-			free(dom);
-		}
-		free(global_search_state);
-		global_search_state = NULL;
-	}
-	evdns_log_fn = NULL;
-}
-
-#ifdef EVDNS_MAIN
-void
-main_callback(int result, char type, int count, int ttl,
-			  void *addrs, void *orig) {
-	char *n = (char*)orig;
-	int i;
-	for (i = 0; i < count; ++i) {
-		if (type == DNS_IPv4_A) {
-			printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
-		} else if (type == DNS_PTR) {
-			printf("%s: %s\n", n, ((char**)addrs)[i]);
-		}
-	}
-	if (!count) {
-		printf("%s: No answer (%d)\n", n, result);
-	}
-	fflush(stdout);
-}
-void
-evdns_server_callback(struct evdns_server_request *req, void *data)
-{
-	int i, r;
-	(void)data;
-	/* dummy; give 192.168.11.11 as an answer for all A questions,
-	 *	give foo.bar.example.com as an answer for all PTR questions. */
-	for (i = 0; i < req->nquestions; ++i) {
-		u32 ans = htonl(0xc0a80b0bUL);
-		if (req->questions[i]->type == EVDNS_TYPE_A &&
-			req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
-			printf(" -- replying for %s (A)\n", req->questions[i]->name);
-			r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
-										  1, &ans, 10);
-			if (r<0)
-				printf("eeep, didn't work.\n");
-		} else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
-				   req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
-			printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
-			r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
-											"foo.bar.example.com", 10);
-		} else {
-			printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
-				   req->questions[i]->type, req->questions[i]->dns_question_class);
-		}
-	}
-
-	r = evdns_request_respond(req, 0);
-	if (r<0)
-		printf("eeek, couldn't send reply.\n");
-}
-
-void
-logfn(int is_warn, const char *msg) {
-  (void) is_warn;
-  fprintf(stderr, "%s\n", msg);
-}
-int
-main(int c, char **v) {
-	int idx;
-	int reverse = 0, verbose = 1, servertest = 0;
-	if (c<2) {
-		fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
-		fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
-		return 1;
-	}
-	idx = 1;
-	while (idx < c && v[idx][0] == '-') {
-		if (!strcmp(v[idx], "-x"))
-			reverse = 1;
-		else if (!strcmp(v[idx], "-v"))
-			verbose = 1;
-		else if (!strcmp(v[idx], "-servertest"))
-			servertest = 1;
-		else
-			fprintf(stderr, "Unknown option %s\n", v[idx]);
-		++idx;
-	}
-	event_init();
-	if (verbose)
-		evdns_set_log_fn(logfn);
-	evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
-	if (servertest) {
-		int sock;
-		struct sockaddr_in my_addr;
-		sock = socket(PF_INET, SOCK_DGRAM, 0);
-                evutil_make_socket_nonblocking(sock);
-		my_addr.sin_family = AF_INET;
-		my_addr.sin_port = htons(10053);
-		my_addr.sin_addr.s_addr = INADDR_ANY;
-		if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
-			perror("bind");
-			exit(1);
-		}
-		evdns_add_server_port(sock, 0, evdns_server_callback, NULL);
-	}
-	for (; idx < c; ++idx) {
-		if (reverse) {
-			struct in_addr addr;
-			if (!inet_aton(v[idx], &addr)) {
-				fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
-				continue;
-			}
-			fprintf(stderr, "resolving %s...\n",v[idx]);
-			evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
-		} else {
-			fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
-			evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);
-		}
-	}
-	fflush(stdout);
-	event_dispatch();
-	return 0;
-}
-#endif
diff --git a/base/third_party/libevent/evdns.h b/base/third_party/libevent/evdns.h
deleted file mode 100644
index fca4ac3..0000000
--- a/base/third_party/libevent/evdns.h
+++ /dev/null
@@ -1,528 +0,0 @@
-/*
- * Copyright (c) 2006 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
- * The original DNS code is due to Adam Langley with heavy
- * modifications by Nick Mathewson.  Adam put his DNS software in the
- * public domain.  You can find his original copyright below.  Please,
- * aware that the code as part of libevent is governed by the 3-clause
- * BSD license above.
- *
- * This software is Public Domain. To view a copy of the public domain dedication,
- * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
- * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
- *
- * I ask and expect, but do not require, that all derivative works contain an
- * attribution similar to:
- * 	Parts developed by Adam Langley <agl@imperialviolet.org>
- *
- * You may wish to replace the word "Parts" with something else depending on
- * the amount of original code.
- *
- * (Derivative works does not include programs which link against, run or include
- * the source verbatim in their source distributions)
- */
-
-/** @file evdns.h
- *
- * Welcome, gentle reader
- *
- * Async DNS lookups are really a whole lot harder than they should be,
- * mostly stemming from the fact that the libc resolver has never been
- * very good at them. Before you use this library you should see if libc
- * can do the job for you with the modern async call getaddrinfo_a
- * (see http://www.imperialviolet.org/page25.html#e498). Otherwise,
- * please continue.
- *
- * This code is based on libevent and you must call event_init before
- * any of the APIs in this file. You must also seed the OpenSSL random
- * source if you are using OpenSSL for ids (see below).
- *
- * This library is designed to be included and shipped with your source
- * code. You statically link with it. You should also test for the
- * existence of strtok_r and define HAVE_STRTOK_R if you have it.
- *
- * The DNS protocol requires a good source of id numbers and these
- * numbers should be unpredictable for spoofing reasons. There are
- * three methods for generating them here and you must define exactly
- * one of them. In increasing order of preference:
- *
- * DNS_USE_GETTIMEOFDAY_FOR_ID:
- *   Using the bottom 16 bits of the usec result from gettimeofday. This
- *   is a pretty poor solution but should work anywhere.
- * DNS_USE_CPU_CLOCK_FOR_ID:
- *   Using the bottom 16 bits of the nsec result from the CPU's time
- *   counter. This is better, but may not work everywhere. Requires
- *   POSIX realtime support and you'll need to link against -lrt on
- *   glibc systems at least.
- * DNS_USE_OPENSSL_FOR_ID:
- *   Uses the OpenSSL RAND_bytes call to generate the data. You must
- *   have seeded the pool before making any calls to this library.
- *
- * The library keeps track of the state of nameservers and will avoid
- * them when they go down. Otherwise it will round robin between them.
- *
- * Quick start guide:
- *   #include "evdns.h"
- *   void callback(int result, char type, int count, int ttl,
- *		 void *addresses, void *arg);
- *   evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
- *   evdns_resolve("www.hostname.com", 0, callback, NULL);
- *
- * When the lookup is complete the callback function is called. The
- * first argument will be one of the DNS_ERR_* defines in evdns.h.
- * Hopefully it will be DNS_ERR_NONE, in which case type will be
- * DNS_IPv4_A, count will be the number of IP addresses, ttl is the time
- * which the data can be cached for (in seconds), addresses will point
- * to an array of uint32_t's and arg will be whatever you passed to
- * evdns_resolve.
- *
- * Searching:
- *
- * In order for this library to be a good replacement for glibc's resolver it
- * supports searching. This involves setting a list of default domains, in
- * which names will be queried for. The number of dots in the query name
- * determines the order in which this list is used.
- *
- * Searching appears to be a single lookup from the point of view of the API,
- * although many DNS queries may be generated from a single call to
- * evdns_resolve. Searching can also drastically slow down the resolution
- * of names.
- *
- * To disable searching:
- *   1. Never set it up. If you never call evdns_resolv_conf_parse or
- *   evdns_search_add then no searching will occur.
- *
- *   2. If you do call evdns_resolv_conf_parse then don't pass
- *   DNS_OPTION_SEARCH (or DNS_OPTIONS_ALL, which implies it).
- *
- *   3. When calling evdns_resolve, pass the DNS_QUERY_NO_SEARCH flag.
- *
- * The order of searches depends on the number of dots in the name. If the
- * number is greater than the ndots setting then the names is first tried
- * globally. Otherwise each search domain is appended in turn.
- *
- * The ndots setting can either be set from a resolv.conf, or by calling
- * evdns_search_ndots_set.
- *
- * For example, with ndots set to 1 (the default) and a search domain list of
- * ["myhome.net"]:
- *  Query: www
- *  Order: www.myhome.net, www.
- *
- *  Query: www.abc
- *  Order: www.abc., www.abc.myhome.net
- *
- * Internals:
- *
- * Requests are kept in two queues. The first is the inflight queue. In
- * this queue requests have an allocated transaction id and nameserver.
- * They will soon be transmitted if they haven't already been.
- *
- * The second is the waiting queue. The size of the inflight ring is
- * limited and all other requests wait in waiting queue for space. This
- * bounds the number of concurrent requests so that we don't flood the
- * nameserver. Several algorithms require a full walk of the inflight
- * queue and so bounding its size keeps thing going nicely under huge
- * (many thousands of requests) loads.
- *
- * If a nameserver loses too many requests it is considered down and we
- * try not to use it. After a while we send a probe to that nameserver
- * (a lookup for google.com) and, if it replies, we consider it working
- * again. If the nameserver fails a probe we wait longer to try again
- * with the next probe.
- */
-
-#ifndef EVENTDNS_H
-#define EVENTDNS_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* For integer types. */
-#include "evutil.h"
-
-/** Error codes 0-5 are as described in RFC 1035. */
-#define DNS_ERR_NONE 0
-/** The name server was unable to interpret the query */
-#define DNS_ERR_FORMAT 1
-/** The name server was unable to process this query due to a problem with the
- * name server */
-#define DNS_ERR_SERVERFAILED 2
-/** The domain name does not exist */
-#define DNS_ERR_NOTEXIST 3
-/** The name server does not support the requested kind of query */
-#define DNS_ERR_NOTIMPL 4
-/** The name server refuses to reform the specified operation for policy
- * reasons */
-#define DNS_ERR_REFUSED 5
-/** The reply was truncated or ill-formated */
-#define DNS_ERR_TRUNCATED 65
-/** An unknown error occurred */
-#define DNS_ERR_UNKNOWN 66
-/** Communication with the server timed out */
-#define DNS_ERR_TIMEOUT 67
-/** The request was canceled because the DNS subsystem was shut down. */
-#define DNS_ERR_SHUTDOWN 68
-
-#define DNS_IPv4_A 1
-#define DNS_PTR 2
-#define DNS_IPv6_AAAA 3
-
-#define DNS_QUERY_NO_SEARCH 1
-
-#define DNS_OPTION_SEARCH 1
-#define DNS_OPTION_NAMESERVERS 2
-#define DNS_OPTION_MISC 4
-#define DNS_OPTIONS_ALL 7
-
-/**
- * The callback that contains the results from a lookup.
- * - type is either DNS_IPv4_A or DNS_PTR or DNS_IPv6_AAAA
- * - count contains the number of addresses of form type
- * - ttl is the number of seconds the resolution may be cached for.
- * - addresses needs to be cast according to type
- */
-typedef void (*evdns_callback_type) (int result, char type, int count, int ttl, void *addresses, void *arg);
-
-/**
-  Initialize the asynchronous DNS library.
-
-  This function initializes support for non-blocking name resolution by
-  calling evdns_resolv_conf_parse() on UNIX and
-  evdns_config_windows_nameservers() on Windows.
-
-  @return 0 if successful, or -1 if an error occurred
-  @see evdns_shutdown()
- */
-int evdns_init(void);
-
-
-/**
-  Shut down the asynchronous DNS resolver and terminate all active requests.
-
-  If the 'fail_requests' option is enabled, all active requests will return
-  an empty result with the error flag set to DNS_ERR_SHUTDOWN. Otherwise,
-  the requests will be silently discarded.
-
-  @param fail_requests if zero, active requests will be aborted; if non-zero,
-		active requests will return DNS_ERR_SHUTDOWN.
-  @see evdns_init()
- */
-void evdns_shutdown(int fail_requests);
-
-
-/**
-  Convert a DNS error code to a string.
-
-  @param err the DNS error code
-  @return a string containing an explanation of the error code
-*/
-const char *evdns_err_to_string(int err);
-
-
-/**
-  Add a nameserver.
-
-  The address should be an IPv4 address in network byte order.
-  The type of address is chosen so that it matches in_addr.s_addr.
-
-  @param address an IP address in network byte order
-  @return 0 if successful, or -1 if an error occurred
-  @see evdns_nameserver_ip_add()
- */
-int evdns_nameserver_add(unsigned long int address);
-
-
-/**
-  Get the number of configured nameservers.
-
-  This returns the number of configured nameservers (not necessarily the
-  number of running nameservers).  This is useful for double-checking
-  whether our calls to the various nameserver configuration functions
-  have been successful.
-
-  @return the number of configured nameservers
-  @see evdns_nameserver_add()
- */
-int evdns_count_nameservers(void);
-
-
-/**
-  Remove all configured nameservers, and suspend all pending resolves.
-
-  Resolves will not necessarily be re-attempted until evdns_resume() is called.
-
-  @return 0 if successful, or -1 if an error occurred
-  @see evdns_resume()
- */
-int evdns_clear_nameservers_and_suspend(void);
-
-
-/**
-  Resume normal operation and continue any suspended resolve requests.
-
-  Re-attempt resolves left in limbo after an earlier call to
-  evdns_clear_nameservers_and_suspend().
-
-  @return 0 if successful, or -1 if an error occurred
-  @see evdns_clear_nameservers_and_suspend()
- */
-int evdns_resume(void);
-
-
-/**
-  Add a nameserver.
-
-  This wraps the evdns_nameserver_add() function by parsing a string as an IP
-  address and adds it as a nameserver.
-
-  @return 0 if successful, or -1 if an error occurred
-  @see evdns_nameserver_add()
- */
-int evdns_nameserver_ip_add(const char *ip_as_string);
-
-
-/**
-  Lookup an A record for a given name.
-
-  @param name a DNS hostname
-  @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
-  @param callback a callback function to invoke when the request is completed
-  @param ptr an argument to pass to the callback function
-  @return 0 if successful, or -1 if an error occurred
-  @see evdns_resolve_ipv6(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6()
- */
-int evdns_resolve_ipv4(const char *name, int flags, evdns_callback_type callback, void *ptr);
-
-
-/**
-  Lookup an AAAA record for a given name.
-
-  @param name a DNS hostname
-  @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
-  @param callback a callback function to invoke when the request is completed
-  @param ptr an argument to pass to the callback function
-  @return 0 if successful, or -1 if an error occurred
-  @see evdns_resolve_ipv4(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6()
- */
-int evdns_resolve_ipv6(const char *name, int flags, evdns_callback_type callback, void *ptr);
-
-struct in_addr;
-struct in6_addr;
-
-/**
-  Lookup a PTR record for a given IP address.
-
-  @param in an IPv4 address
-  @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
-  @param callback a callback function to invoke when the request is completed
-  @param ptr an argument to pass to the callback function
-  @return 0 if successful, or -1 if an error occurred
-  @see evdns_resolve_reverse_ipv6()
- */
-int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr);
-
-
-/**
-  Lookup a PTR record for a given IPv6 address.
-
-  @param in an IPv6 address
-  @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
-  @param callback a callback function to invoke when the request is completed
-  @param ptr an argument to pass to the callback function
-  @return 0 if successful, or -1 if an error occurred
-  @see evdns_resolve_reverse_ipv6()
- */
-int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr);
-
-
-/**
-  Set the value of a configuration option.
-
-  The currently available configuration options are:
-
-    ndots, timeout, max-timeouts, max-inflight, and attempts
-
-  @param option the name of the configuration option to be modified
-  @param val the value to be set
-  @param flags either 0 | DNS_OPTION_SEARCH | DNS_OPTION_MISC
-  @return 0 if successful, or -1 if an error occurred
- */
-int evdns_set_option(const char *option, const char *val, int flags);
-
-
-/**
-  Parse a resolv.conf file.
-
-  The 'flags' parameter determines what information is parsed from the
-  resolv.conf file. See the man page for resolv.conf for the format of this
-  file.
-
-  The following directives are not parsed from the file: sortlist, rotate,
-  no-check-names, inet6, debug.
-
-  If this function encounters an error, the possible return values are: 1 =
-  failed to open file, 2 = failed to stat file, 3 = file too large, 4 = out of
-  memory, 5 = short read from file, 6 = no nameservers listed in the file
-
-  @param flags any of DNS_OPTION_NAMESERVERS|DNS_OPTION_SEARCH|DNS_OPTION_MISC|
-         DNS_OPTIONS_ALL
-  @param filename the path to the resolv.conf file
-  @return 0 if successful, or various positive error codes if an error
-          occurred (see above)
-  @see resolv.conf(3), evdns_config_windows_nameservers()
- */
-int evdns_resolv_conf_parse(int flags, const char *const filename);
-
-
-/**
-  Obtain nameserver information using the Windows API.
-
-  Attempt to configure a set of nameservers based on platform settings on
-  a win32 host.  Preferentially tries to use GetNetworkParams; if that fails,
-  looks in the registry.
-
-  @return 0 if successful, or -1 if an error occurred
-  @see evdns_resolv_conf_parse()
- */
-#ifdef WIN32
-int evdns_config_windows_nameservers(void);
-#endif
-
-
-/**
-  Clear the list of search domains.
- */
-void evdns_search_clear(void);
-
-
-/**
-  Add a domain to the list of search domains
-
-  @param domain the domain to be added to the search list
- */
-void evdns_search_add(const char *domain);
-
-
-/**
-  Set the 'ndots' parameter for searches.
-
-  Sets the number of dots which, when found in a name, causes
-  the first query to be without any search domain.
-
-  @param ndots the new ndots parameter
- */
-void evdns_search_ndots_set(const int ndots);
-
-/**
-  A callback that is invoked when a log message is generated
-
-  @param is_warning indicates if the log message is a 'warning'
-  @param msg the content of the log message
- */
-typedef void (*evdns_debug_log_fn_type)(int is_warning, const char *msg);
-
-
-/**
-  Set the callback function to handle log messages.
-
-  @param fn the callback to be invoked when a log message is generated
- */
-void evdns_set_log_fn(evdns_debug_log_fn_type fn);
-
-/**
-   Set a callback that will be invoked to generate transaction IDs.  By
-   default, we pick transaction IDs based on the current clock time.
-
-   @param fn the new callback, or NULL to use the default.
- */
-void evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void));
-
-#define DNS_NO_SEARCH 1
-
-/*
- * Structures and functions used to implement a DNS server.
- */
-
-struct evdns_server_request {
-	int flags;
-	int nquestions;
-	struct evdns_server_question **questions;
-};
-struct evdns_server_question {
-	int type;
-#ifdef __cplusplus
-	int dns_question_class;
-#else
-	/* You should refer to this field as "dns_question_class".  The
-	 * name "class" works in C for backward compatibility, and will be
-	 * removed in a future version. (1.5 or later). */
-	int class;
-#define dns_question_class class
-#endif
-	char name[1];
-};
-typedef void (*evdns_request_callback_fn_type)(struct evdns_server_request *, void *);
-#define EVDNS_ANSWER_SECTION 0
-#define EVDNS_AUTHORITY_SECTION 1
-#define EVDNS_ADDITIONAL_SECTION 2
-
-#define EVDNS_TYPE_A	   1
-#define EVDNS_TYPE_NS	   2
-#define EVDNS_TYPE_CNAME   5
-#define EVDNS_TYPE_SOA	   6
-#define EVDNS_TYPE_PTR	  12
-#define EVDNS_TYPE_MX	  15
-#define EVDNS_TYPE_TXT	  16
-#define EVDNS_TYPE_AAAA	  28
-
-#define EVDNS_QTYPE_AXFR 252
-#define EVDNS_QTYPE_ALL	 255
-
-#define EVDNS_CLASS_INET   1
-
-struct evdns_server_port *evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type callback, void *user_data);
-void evdns_close_server_port(struct evdns_server_port *port);
-
-int evdns_server_request_add_reply(struct evdns_server_request *req, int section, const char *name, int type, int dns_class, int ttl, int datalen, int is_name, const char *data);
-int evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl);
-int evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl);
-int evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl);
-int evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl);
-
-int evdns_server_request_respond(struct evdns_server_request *req, int err);
-int evdns_server_request_drop(struct evdns_server_request *req);
-struct sockaddr;
-int evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif  /* !EVENTDNS_H */
diff --git a/base/third_party/libevent/event-config.h b/base/third_party/libevent/event-config.h
deleted file mode 100644
index bbd23f1..0000000
--- a/base/third_party/libevent/event-config.h
+++ /dev/null
@@ -1,24 +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.
-
-// This file is Chromium-specific, and brings in the appropriate
-// event-config.h depending on your platform.
-
-#if defined(__native_client_nonsfi__)
-#include "base/third_party/libevent/nacl_nonsfi/event-config.h"
-#elif defined(__APPLE__)
-#include "base/third_party/libevent/mac/event-config.h"
-#elif defined(ANDROID)
-#include "base/third_party/libevent/android/event-config.h"
-#elif defined(__linux__)
-#include "base/third_party/libevent/linux/event-config.h"
-#elif defined(__FreeBSD__)
-#include "base/third_party/libevent/freebsd/event-config.h"
-#elif defined(__sun)
-#include "base/third_party/libevent/solaris/event-config.h"
-#elif defined(_AIX)
-#include "base/third_party/libevent/aix/event-config.h"
-#else
-#error generate event-config.h for your platform
-#endif
diff --git a/base/third_party/libevent/event-internal.h b/base/third_party/libevent/event-internal.h
deleted file mode 100644
index b7f0040..0000000
--- a/base/third_party/libevent/event-internal.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (c) 2000-2004 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef _EVENT_INTERNAL_H_
-#define _EVENT_INTERNAL_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "config.h"
-#include "min_heap.h"
-#include "evsignal.h"
-
-struct eventop {
-	const char *name;
-	void *(*init)(struct event_base *);
-	int (*add)(void *, struct event *);
-	int (*del)(void *, struct event *);
-	int (*dispatch)(struct event_base *, void *, struct timeval *);
-	void (*dealloc)(struct event_base *, void *);
-	/* set if we need to reinitialize the event base */
-	int need_reinit;
-};
-
-struct event_base {
-	const struct eventop *evsel;
-	void *evbase;
-	int event_count;		/* counts number of total events */
-	int event_count_active;	/* counts number of active events */
-
-	int event_gotterm;		/* Set to terminate loop */
-	int event_break;		/* Set to terminate loop immediately */
-
-	/* active event management */
-	struct event_list **activequeues;
-	int nactivequeues;
-
-	/* signal handling info */
-	struct evsignal_info sig;
-
-	struct event_list eventqueue;
-	struct timeval event_tv;
-
-	struct min_heap timeheap;
-
-	struct timeval tv_cache;
-};
-
-/* Internal use only: Functions that might be missing from <sys/queue.h> */
-#ifndef HAVE_TAILQFOREACH
-#define	TAILQ_FIRST(head)		((head)->tqh_first)
-#define	TAILQ_END(head)			NULL
-#define	TAILQ_NEXT(elm, field)		((elm)->field.tqe_next)
-#define TAILQ_FOREACH(var, head, field)					\
-	for((var) = TAILQ_FIRST(head);					\
-	    (var) != TAILQ_END(head);					\
-	    (var) = TAILQ_NEXT(var, field))
-#define	TAILQ_INSERT_BEFORE(listelm, elm, field) do {			\
-	(elm)->field.tqe_prev = (listelm)->field.tqe_prev;		\
-	(elm)->field.tqe_next = (listelm);				\
-	*(listelm)->field.tqe_prev = (elm);				\
-	(listelm)->field.tqe_prev = &(elm)->field.tqe_next;		\
-} while (0)
-#endif /* TAILQ_FOREACH */
-
-int _evsignal_set_handler(struct event_base *base, int evsignal,
-			  void (*fn)(int));
-int _evsignal_restore_handler(struct event_base *base, int evsignal);
-
-/* defined in evutil.c */
-const char *evutil_getenv(const char *varname);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _EVENT_INTERNAL_H_ */
diff --git a/base/third_party/libevent/event.3 b/base/third_party/libevent/event.3
deleted file mode 100644
index 5b33ec6..0000000
--- a/base/third_party/libevent/event.3
+++ /dev/null
@@ -1,624 +0,0 @@
-.\"	$OpenBSD: event.3,v 1.4 2002/07/12 18:50:48 provos Exp $
-.\"
-.\" Copyright (c) 2000 Artur Grabowski <art@openbsd.org>
-.\" All rights reserved.
-.\"
-.\" Redistribution and use in source and binary forms, with or without
-.\" modification, are permitted provided that the following conditions
-.\" are met:
-.\"
-.\" 1. Redistributions of source code must retain the above copyright
-.\"    notice, this list of conditions and the following disclaimer.
-.\" 2. Redistributions in binary form must reproduce the above copyright
-.\"    notice, this list of conditions and the following disclaimer in the
-.\"    documentation and/or other materials provided with the distribution.
-.\" 3. The name of the author may not be used to endorse or promote products
-.\"    derived from this software without specific prior written permission.
-.\"
-.\" THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
-.\" INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
-.\" AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
-.\" THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-.\" EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-.\" PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
-.\" OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-.\" WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-.\" OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-.\" ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-.\"
-.Dd August 8, 2000
-.Dt EVENT 3
-.Os
-.Sh NAME
-.Nm event_init ,
-.Nm event_dispatch ,
-.Nm event_loop ,
-.Nm event_loopexit ,
-.Nm event_loopbreak ,
-.Nm event_set ,
-.Nm event_base_dispatch ,
-.Nm event_base_loop ,
-.Nm event_base_loopexit ,
-.Nm event_base_loopbreak ,
-.Nm event_base_set ,
-.Nm event_base_free ,
-.Nm event_add ,
-.Nm event_del ,
-.Nm event_once ,
-.Nm event_base_once ,
-.Nm event_pending ,
-.Nm event_initialized ,
-.Nm event_priority_init ,
-.Nm event_priority_set ,
-.Nm evtimer_set ,
-.Nm evtimer_add ,
-.Nm evtimer_del ,
-.Nm evtimer_pending ,
-.Nm evtimer_initialized ,
-.Nm signal_set ,
-.Nm signal_add ,
-.Nm signal_del ,
-.Nm signal_pending ,
-.Nm signal_initialized ,
-.Nm bufferevent_new ,
-.Nm bufferevent_free ,
-.Nm bufferevent_write ,
-.Nm bufferevent_write_buffer ,
-.Nm bufferevent_read ,
-.Nm bufferevent_enable ,
-.Nm bufferevent_disable ,
-.Nm bufferevent_settimeout ,
-.Nm bufferevent_base_set ,
-.Nm evbuffer_new ,
-.Nm evbuffer_free ,
-.Nm evbuffer_add ,
-.Nm evbuffer_add_buffer ,
-.Nm evbuffer_add_printf ,
-.Nm evbuffer_add_vprintf ,
-.Nm evbuffer_drain ,
-.Nm evbuffer_write ,
-.Nm evbuffer_read ,
-.Nm evbuffer_find ,
-.Nm evbuffer_readline ,
-.Nm evhttp_new ,
-.Nm evhttp_bind_socket ,
-.Nm evhttp_free
-.Nd execute a function when a specific event occurs
-.Sh SYNOPSIS
-.Fd #include <sys/time.h>
-.Fd #include <event.h>
-.Ft "struct event_base *"
-.Fn "event_init" "void"
-.Ft int
-.Fn "event_dispatch" "void"
-.Ft int
-.Fn "event_loop" "int flags"
-.Ft int
-.Fn "event_loopexit" "struct timeval *tv"
-.Ft int
-.Fn "event_loopbreak" "void"
-.Ft void
-.Fn "event_set" "struct event *ev" "int fd" "short event" "void (*fn)(int, short, void *)" "void *arg"
-.Ft int
-.Fn "event_base_dispatch" "struct event_base *base"
-.Ft int
-.Fn "event_base_loop" "struct event_base *base" "int flags"
-.Ft int
-.Fn "event_base_loopexit" "struct event_base *base" "struct timeval *tv"
-.Ft int
-.Fn "event_base_loopbreak" "struct event_base *base"
-.Ft int
-.Fn "event_base_set" "struct event_base *base" "struct event *"
-.Ft void
-.Fn "event_base_free" "struct event_base *base"
-.Ft int
-.Fn "event_add" "struct event *ev" "struct timeval *tv"
-.Ft int
-.Fn "event_del" "struct event *ev"
-.Ft int
-.Fn "event_once" "int fd" "short event" "void (*fn)(int, short, void *)" "void *arg" "struct timeval *tv"
-.Ft int
-.Fn "event_base_once" "struct event_base *base" "int fd" "short event" "void (*fn)(int, short, void *)" "void *arg" "struct timeval *tv"
-.Ft int
-.Fn "event_pending" "struct event *ev" "short event" "struct timeval *tv"
-.Ft int
-.Fn "event_initialized" "struct event *ev"
-.Ft int
-.Fn "event_priority_init" "int npriorities"
-.Ft int
-.Fn "event_priority_set" "struct event *ev" "int priority"
-.Ft void
-.Fn "evtimer_set" "struct event *ev" "void (*fn)(int, short, void *)" "void *arg"
-.Ft void
-.Fn "evtimer_add" "struct event *ev" "struct timeval *"
-.Ft void
-.Fn "evtimer_del" "struct event *ev"
-.Ft int
-.Fn "evtimer_pending" "struct event *ev" "struct timeval *tv"
-.Ft int
-.Fn "evtimer_initialized" "struct event *ev"
-.Ft void
-.Fn "signal_set" "struct event *ev" "int signal" "void (*fn)(int, short, void *)" "void *arg"
-.Ft void
-.Fn "signal_add" "struct event *ev" "struct timeval *"
-.Ft void
-.Fn "signal_del" "struct event *ev"
-.Ft int
-.Fn "signal_pending" "struct event *ev" "struct timeval *tv"
-.Ft int
-.Fn "signal_initialized" "struct event *ev"
-.Ft "struct bufferevent *"
-.Fn "bufferevent_new" "int fd" "evbuffercb readcb" "evbuffercb writecb" "everrorcb" "void *cbarg"
-.Ft void
-.Fn "bufferevent_free" "struct bufferevent *bufev"
-.Ft int
-.Fn "bufferevent_write" "struct bufferevent *bufev" "void *data" "size_t size"
-.Ft int
-.Fn "bufferevent_write_buffer" "struct bufferevent *bufev" "struct evbuffer *buf"
-.Ft size_t
-.Fn "bufferevent_read" "struct bufferevent *bufev" "void *data" "size_t size"
-.Ft int
-.Fn "bufferevent_enable" "struct bufferevent *bufev" "short event"
-.Ft int
-.Fn "bufferevent_disable" "struct bufferevent *bufev" "short event"
-.Ft void
-.Fn "bufferevent_settimeout" "struct bufferevent *bufev" "int timeout_read" "int timeout_write"
-.Ft int
-.Fn "bufferevent_base_set" "struct event_base *base" "struct bufferevent *bufev"
-.Ft "struct evbuffer *"
-.Fn "evbuffer_new" "void"
-.Ft void
-.Fn "evbuffer_free" "struct evbuffer *buf"
-.Ft int
-.Fn "evbuffer_add" "struct evbuffer *buf" "const void *data" "size_t size"
-.Ft int
-.Fn "evbuffer_add_buffer" "struct evbuffer *dst" "struct evbuffer *src"
-.Ft int
-.Fn "evbuffer_add_printf" "struct evbuffer *buf" "const char *fmt" "..."
-.Ft int
-.Fn "evbuffer_add_vprintf" "struct evbuffer *buf" "const char *fmt" "va_list ap"
-.Ft void
-.Fn "evbuffer_drain" "struct evbuffer *buf" "size_t size"
-.Ft int
-.Fn "evbuffer_write" "struct evbuffer *buf" "int fd"
-.Ft int
-.Fn "evbuffer_read" "struct evbuffer *buf" "int fd" "int size"
-.Ft "u_char *"
-.Fn "evbuffer_find" "struct evbuffer *buf" "const u_char *data" "size_t size"
-.Ft "char *"
-.Fn "evbuffer_readline" "struct evbuffer *buf"
-.Ft "struct evhttp *"
-.Fn "evhttp_new" "struct event_base *base"
-.Ft int
-.Fn "evhttp_bind_socket" "struct evhttp *http" "const char *address" "u_short port"
-.Ft "void"
-.Fn "evhttp_free" "struct evhttp *http"
-.Ft int
-.Fa (*event_sigcb)(void) ;
-.Ft volatile sig_atomic_t
-.Fa event_gotsig ;
-.Sh DESCRIPTION
-The
-.Nm event
-API provides a mechanism to execute a function when a specific event
-on a file descriptor occurs or after a given time has passed.
-.Pp
-The
-.Nm event
-API needs to be initialized with
-.Fn event_init
-before it can be used.
-.Pp
-In order to process events, an application needs to call
-.Fn event_dispatch .
-This function only returns on error, and should replace the event core
-of the application program.
-.Pp
-The function
-.Fn event_set
-prepares the event structure
-.Fa ev
-to be used in future calls to
-.Fn event_add
-and
-.Fn event_del .
-The event will be prepared to call the function specified by the
-.Fa fn
-argument with an
-.Fa int
-argument indicating the file descriptor, a
-.Fa short
-argument indicating the type of event, and a
-.Fa void *
-argument given in the
-.Fa arg
-argument.
-The
-.Fa fd
-indicates the file descriptor that should be monitored for events.
-The events can be either
-.Va EV_READ ,
-.Va EV_WRITE ,
-or both,
-indicating that an application can read or write from the file descriptor
-respectively without blocking.
-.Pp
-The function
-.Fa fn
-will be called with the file descriptor that triggered the event and
-the type of event which will be either
-.Va EV_TIMEOUT ,
-.Va EV_SIGNAL ,
-.Va EV_READ ,
-or
-.Va EV_WRITE .
-Additionally, an event which has registered interest in more than one of the
-preceeding events, via bitwise-OR to
-.Fn event_set ,
-can provide its callback function with a bitwise-OR of more than one triggered
-event.
-The additional flag
-.Va EV_PERSIST
-makes an
-.Fn event_add
-persistent until
-.Fn event_del
-has been called.
-.Pp
-Once initialized, the
-.Fa ev
-structure can be used repeatedly with
-.Fn event_add
-and
-.Fn event_del
-and does not need to be reinitialized unless the function called and/or
-the argument to it are to be changed.
-However, when an
-.Fa ev
-structure has been added to libevent using
-.Fn event_add
-the structure must persist until the event occurs (assuming
-.Fa EV_PERSIST
-is not set) or is removed
-using
-.Fn event_del .
-You may not reuse the same
-.Fa ev
-structure for multiple monitored descriptors; each descriptor
-needs its own
-.Fa ev .
-.Pp
-The function
-.Fn event_add
-schedules the execution of the
-.Fa ev
-event when the event specified in
-.Fn event_set
-occurs or in at least the time specified in the
-.Fa tv .
-If
-.Fa tv
-is
-.Dv NULL ,
-no timeout occurs and the function will only be called
-if a matching event occurs on the file descriptor.
-The event in the
-.Fa ev
-argument must be already initialized by
-.Fn event_set
-and may not be used in calls to
-.Fn event_set
-until it has timed out or been removed with
-.Fn event_del .
-If the event in the
-.Fa ev
-argument already has a scheduled timeout, the old timeout will be
-replaced by the new one.
-.Pp
-The function
-.Fn event_del
-will cancel the event in the argument
-.Fa ev .
-If the event has already executed or has never been added
-the call will have no effect.
-.Pp
-The functions
-.Fn evtimer_set ,
-.Fn evtimer_add ,
-.Fn evtimer_del ,
-.Fn evtimer_initialized ,
-and
-.Fn evtimer_pending
-are abbreviations for common situations where only a timeout is required.
-The file descriptor passed will be \-1, and the event type will be
-.Va EV_TIMEOUT .
-.Pp
-The functions
-.Fn signal_set ,
-.Fn signal_add ,
-.Fn signal_del ,
-.Fn signal_initialized ,
-and
-.Fn signal_pending
-are abbreviations.
-The event type will be a persistent
-.Va EV_SIGNAL .
-That means
-.Fn signal_set
-adds
-.Va EV_PERSIST .
-.Pp
-In order to avoid races in signal handlers, the
-.Nm event
-API provides two variables:
-.Va event_sigcb
-and
-.Va event_gotsig .
-A signal handler
-sets
-.Va event_gotsig
-to indicate that a signal has been received.
-The application sets
-.Va event_sigcb
-to a callback function.
-After the signal handler sets
-.Va event_gotsig ,
-.Nm event_dispatch
-will execute the callback function to process received signals.
-The callback returns 1 when no events are registered any more.
-It can return \-1 to indicate an error to the
-.Nm event
-library, causing
-.Fn event_dispatch
-to terminate with
-.Va errno
-set to
-.Er EINTR .
-.Pp
-The function
-.Fn event_once
-is similar to
-.Fn event_set .
-However, it schedules a callback to be called exactly once and does not
-require the caller to prepare an
-.Fa event
-structure.
-This function supports
-.Fa EV_TIMEOUT ,
-.Fa EV_READ ,
-and
-.Fa EV_WRITE .
-.Pp
-The
-.Fn event_pending
-function can be used to check if the event specified by
-.Fa event
-is pending to run.
-If
-.Va EV_TIMEOUT
-was specified and
-.Fa tv
-is not
-.Dv NULL ,
-the expiration time of the event will be returned in
-.Fa tv .
-.Pp
-The
-.Fn event_initialized
-macro can be used to check if an event has been initialized.
-.Pp
-The
-.Nm event_loop
-function provides an interface for single pass execution of pending
-events.
-The flags
-.Va EVLOOP_ONCE
-and
-.Va EVLOOP_NONBLOCK
-are recognized.
-The
-.Nm event_loopexit
-function exits from the event loop. The next
-.Fn event_loop
-iteration after the
-given timer expires will complete normally (handling all queued events) then
-exit without blocking for events again. Subsequent invocations of
-.Fn event_loop
-will proceed normally.
-The
-.Nm event_loopbreak
-function exits from the event loop immediately.
-.Fn event_loop
-will abort after the next event is completed;
-.Fn event_loopbreak
-is typically invoked from this event's callback. This behavior is analogous
-to the "break;" statement. Subsequent invocations of
-.Fn event_loop
-will proceed normally.
-.Pp
-It is the responsibility of the caller to provide these functions with
-pre-allocated event structures.
-.Pp
-.Sh EVENT PRIORITIES
-By default
-.Nm libevent
-schedules all active events with the same priority.
-However, sometimes it is desirable to process some events with a higher
-priority than others.
-For that reason,
-.Nm libevent
-supports strict priority queues.
-Active events with a lower priority are always processed before events
-with a higher priority.
-.Pp
-The number of different priorities can be set initially with the
-.Fn event_priority_init
-function.
-This function should be called before the first call to
-.Fn event_dispatch .
-The
-.Fn event_priority_set
-function can be used to assign a priority to an event.
-By default,
-.Nm libevent
-assigns the middle priority to all events unless their priority
-is explicitly set.
-.Sh THREAD SAFE EVENTS
-.Nm Libevent
-has experimental support for thread-safe events.
-When initializing the library via
-.Fn event_init ,
-an event base is returned.
-This event base can be used in conjunction with calls to
-.Fn event_base_set ,
-.Fn event_base_dispatch ,
-.Fn event_base_loop ,
-.Fn event_base_loopexit ,
-.Fn bufferevent_base_set
-and
-.Fn event_base_free .
-.Fn event_base_set
-should be called after preparing an event with
-.Fn event_set ,
-as
-.Fn event_set
-assigns the provided event to the most recently created event base.
-.Fn bufferevent_base_set
-should be called after preparing a bufferevent with
-.Fn bufferevent_new .
-.Fn event_base_free
-should be used to free memory associated with the event base
-when it is no longer needed.
-.Sh BUFFERED EVENTS
-.Nm libevent
-provides an abstraction on top of the regular event callbacks.
-This abstraction is called a
-.Va "buffered event" .
-A buffered event provides input and output buffers that get filled
-and drained automatically.
-The user of a buffered event no longer deals directly with the IO,
-but instead is reading from input and writing to output buffers.
-.Pp
-A new bufferevent is created by
-.Fn bufferevent_new .
-The parameter
-.Fa fd
-specifies the file descriptor from which data is read and written to.
-This file descriptor is not allowed to be a
-.Xr pipe 2 .
-The next three parameters are callbacks.
-The read and write callback have the following form:
-.Ft void
-.Fn "(*cb)" "struct bufferevent *bufev" "void *arg" .
-The error callback has the following form:
-.Ft void
-.Fn "(*cb)" "struct bufferevent *bufev" "short what" "void *arg" .
-The argument is specified by the fourth parameter
-.Fa "cbarg" .
-A
-.Fa bufferevent struct
-pointer is returned on success, NULL on error.
-Both the read and the write callback may be NULL.
-The error callback has to be always provided.
-.Pp
-Once initialized, the bufferevent structure can be used repeatedly with
-bufferevent_enable() and bufferevent_disable().
-The flags parameter can be a combination of
-.Va EV_READ
-and
-.Va EV_WRITE .
-When read enabled the bufferevent will try to read from the file
-descriptor and call the read callback.
-The write callback is executed
-whenever the output buffer is drained below the write low watermark,
-which is
-.Va 0
-by default.
-.Pp
-The
-.Fn bufferevent_write
-function can be used to write data to the file descriptor.
-The data is appended to the output buffer and written to the descriptor
-automatically as it becomes available for writing.
-.Fn bufferevent_write
-returns 0 on success or \-1 on failure.
-The
-.Fn bufferevent_read
-function is used to read data from the input buffer,
-returning the amount of data read.
-.Pp
-If multiple bases are in use, bufferevent_base_set() must be called before
-enabling the bufferevent for the first time.
-.Sh NON-BLOCKING HTTP SUPPORT
-.Nm libevent
-provides a very thin HTTP layer that can be used both to host an HTTP
-server and also to make HTTP requests.
-An HTTP server can be created by calling
-.Fn evhttp_new .
-It can be bound to any port and address with the
-.Fn evhttp_bind_socket
-function.
-When the HTTP server is no longer used, it can be freed via
-.Fn evhttp_free .
-.Pp
-To be notified of HTTP requests, a user needs to register callbacks with the
-HTTP server.
-This can be done by calling
-.Fn evhttp_set_cb .
-The second argument is the URI for which a callback is being registered.
-The corresponding callback will receive an
-.Va struct evhttp_request
-object that contains all information about the request.
-.Pp
-This section does not document all the possible function calls; please
-check
-.Va event.h
-for the public interfaces.
-.Sh ADDITIONAL NOTES
-It is possible to disable support for
-.Va epoll , kqueue , devpoll , poll
-or
-.Va select
-by setting the environment variable
-.Va EVENT_NOEPOLL , EVENT_NOKQUEUE , EVENT_NODEVPOLL , EVENT_NOPOLL
-or
-.Va EVENT_NOSELECT ,
-respectively.
-By setting the environment variable
-.Va EVENT_SHOW_METHOD ,
-.Nm libevent
-displays the kernel notification method that it uses.
-.Sh RETURN VALUES
-Upon successful completion
-.Fn event_add
-and
-.Fn event_del
-return 0.
-Otherwise, \-1 is returned and the global variable errno is
-set to indicate the error.
-.Sh SEE ALSO
-.Xr kqueue 2 ,
-.Xr poll 2 ,
-.Xr select 2 ,
-.Xr evdns 3 ,
-.Xr timeout 9
-.Sh HISTORY
-The
-.Nm event
-API manpage is based on the
-.Xr timeout 9
-manpage by Artur Grabowski.
-The port of
-.Nm libevent
-to Windows is due to Michael A. Davis.
-Support for real-time signals is due to Taral.
-.Sh AUTHORS
-The
-.Nm event
-library was written by Niels Provos.
-.Sh BUGS
-This documentation is neither complete nor authoritative.
-If you are in doubt about the usage of this API then
-check the source code to find out how it works, write
-up the missing piece of documentation and send it to
-me for inclusion in this man page.
diff --git a/base/third_party/libevent/event.c b/base/third_party/libevent/event.c
deleted file mode 100644
index 4aa326e..0000000
--- a/base/third_party/libevent/event.c
+++ /dev/null
@@ -1,998 +0,0 @@
-/*
- * Copyright (c) 2000-2004 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-#endif
-#include <sys/types.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#else 
-#include <sys/_libevent_time.h>
-#endif
-#include <sys/queue.h>
-#include <stdio.h>
-#include <stdlib.h>
-#ifndef WIN32
-#include <unistd.h>
-#endif
-#include <errno.h>
-#include <signal.h>
-#include <string.h>
-#include <assert.h>
-#include <time.h>
-
-#include "event.h"
-#include "event-internal.h"
-#include "evutil.h"
-#include "log.h"
-
-#ifdef HAVE_EVENT_PORTS
-extern const struct eventop evportops;
-#endif
-#ifdef HAVE_SELECT
-extern const struct eventop selectops;
-#endif
-#ifdef HAVE_POLL
-extern const struct eventop pollops;
-#endif
-#ifdef HAVE_EPOLL
-extern const struct eventop epollops;
-#endif
-#ifdef HAVE_WORKING_KQUEUE
-extern const struct eventop kqops;
-#endif
-#ifdef HAVE_DEVPOLL
-extern const struct eventop devpollops;
-#endif
-#ifdef WIN32
-extern const struct eventop win32ops;
-#endif
-
-/* In order of preference */
-static const struct eventop *eventops[] = {
-#ifdef HAVE_EVENT_PORTS
-	&evportops,
-#endif
-#ifdef HAVE_WORKING_KQUEUE
-	&kqops,
-#endif
-#ifdef HAVE_EPOLL
-	&epollops,
-#endif
-#ifdef HAVE_DEVPOLL
-	&devpollops,
-#endif
-#ifdef HAVE_POLL
-	&pollops,
-#endif
-#ifdef HAVE_SELECT
-	&selectops,
-#endif
-#ifdef WIN32
-	&win32ops,
-#endif
-	NULL
-};
-
-/* Global state */
-struct event_base *current_base = NULL;
-extern struct event_base *evsignal_base;
-static int use_monotonic = 1;
-
-/* Prototypes */
-static void	event_queue_insert(struct event_base *, struct event *, int);
-static void	event_queue_remove(struct event_base *, struct event *, int);
-static int	event_haveevents(struct event_base *);
-
-static void	event_process_active(struct event_base *);
-
-static int	timeout_next(struct event_base *, struct timeval **);
-static void	timeout_process(struct event_base *);
-static void	timeout_correct(struct event_base *, struct timeval *);
-
-static int
-gettime(struct event_base *base, struct timeval *tp)
-{
-	if (base->tv_cache.tv_sec) {
-		*tp = base->tv_cache;
-		return (0);
-	}
-
-#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
-	struct timespec	ts;
-
-	if (use_monotonic &&
-	    clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
-		tp->tv_sec = ts.tv_sec;
-		tp->tv_usec = ts.tv_nsec / 1000;
-		return (0);
-	}
-#endif
-
-	use_monotonic = 0;
-
-	return (evutil_gettimeofday(tp, NULL));
-}
-
-struct event_base *
-event_init(void)
-{
-	struct event_base *base = event_base_new();
-
-	if (base != NULL)
-		current_base = base;
-
-	return (base);
-}
-
-struct event_base *
-event_base_new(void)
-{
-	int i;
-	struct event_base *base;
-
-	if ((base = calloc(1, sizeof(struct event_base))) == NULL)
-		event_err(1, "%s: calloc", __func__);
-
-	gettime(base, &base->event_tv);
-	
-	min_heap_ctor(&base->timeheap);
-	TAILQ_INIT(&base->eventqueue);
-	base->sig.ev_signal_pair[0] = -1;
-	base->sig.ev_signal_pair[1] = -1;
-	
-	base->evbase = NULL;
-	for (i = 0; eventops[i] && !base->evbase; i++) {
-		base->evsel = eventops[i];
-
-		base->evbase = base->evsel->init(base);
-	}
-
-	if (base->evbase == NULL)
-		event_errx(1, "%s: no event mechanism available", __func__);
-
-	if (evutil_getenv("EVENT_SHOW_METHOD")) 
-		event_msgx("libevent using: %s\n",
-			   base->evsel->name);
-
-	/* allocate a single active event queue */
-	event_base_priority_init(base, 1);
-
-	return (base);
-}
-
-void
-event_base_free(struct event_base *base)
-{
-	int i, n_deleted=0;
-	struct event *ev;
-
-	if (base == NULL && current_base)
-		base = current_base;
-	if (base == current_base)
-		current_base = NULL;
-
-	/* XXX(niels) - check for internal events first */
-	assert(base);
-	/* Delete all non-internal events. */
-	for (ev = TAILQ_FIRST(&base->eventqueue); ev; ) {
-		struct event *next = TAILQ_NEXT(ev, ev_next);
-		if (!(ev->ev_flags & EVLIST_INTERNAL)) {
-			event_del(ev);
-			++n_deleted;
-		}
-		ev = next;
-	}
-	while ((ev = min_heap_top(&base->timeheap)) != NULL) {
-		event_del(ev);
-		++n_deleted;
-	}
-
-	for (i = 0; i < base->nactivequeues; ++i) {
-		for (ev = TAILQ_FIRST(base->activequeues[i]); ev; ) {
-			struct event *next = TAILQ_NEXT(ev, ev_active_next);
-			if (!(ev->ev_flags & EVLIST_INTERNAL)) {
-				event_del(ev);
-				++n_deleted;
-			}
-			ev = next;
-		}
-	}
-
-	if (n_deleted)
-		event_debug(("%s: %d events were still set in base",
-			__func__, n_deleted));
-
-	if (base->evsel->dealloc != NULL)
-		base->evsel->dealloc(base, base->evbase);
-
-	for (i = 0; i < base->nactivequeues; ++i)
-		assert(TAILQ_EMPTY(base->activequeues[i]));
-
-	assert(min_heap_empty(&base->timeheap));
-	min_heap_dtor(&base->timeheap);
-
-	for (i = 0; i < base->nactivequeues; ++i)
-		free(base->activequeues[i]);
-	free(base->activequeues);
-
-	assert(TAILQ_EMPTY(&base->eventqueue));
-
-	free(base);
-}
-
-/* reinitialized the event base after a fork */
-int
-event_reinit(struct event_base *base)
-{
-	const struct eventop *evsel = base->evsel;
-	void *evbase = base->evbase;
-	int res = 0;
-	struct event *ev;
-
-#if 0
-	/* Right now, reinit always takes effect, since even if the
-	   backend doesn't require it, the signal socketpair code does.
-	 */
-	/* check if this event mechanism requires reinit */
-	if (!evsel->need_reinit)
-		return (0);
-#endif
-
-	/* prevent internal delete */
-	if (base->sig.ev_signal_added) {
-		/* we cannot call event_del here because the base has
-		 * not been reinitialized yet. */
-		event_queue_remove(base, &base->sig.ev_signal,
-		    EVLIST_INSERTED);
-		if (base->sig.ev_signal.ev_flags & EVLIST_ACTIVE)
-			event_queue_remove(base, &base->sig.ev_signal,
-			    EVLIST_ACTIVE);
-		base->sig.ev_signal_added = 0;
-	}
-
-	if (base->evsel->dealloc != NULL)
-		base->evsel->dealloc(base, base->evbase);
-	evbase = base->evbase = evsel->init(base);
-	if (base->evbase == NULL)
-		event_errx(1, "%s: could not reinitialize event mechanism",
-		    __func__);
-
-	TAILQ_FOREACH(ev, &base->eventqueue, ev_next) {
-		if (evsel->add(evbase, ev) == -1)
-			res = -1;
-	}
-
-	return (res);
-}
-
-int
-event_priority_init(int npriorities)
-{
-  return event_base_priority_init(current_base, npriorities);
-}
-
-int
-event_base_priority_init(struct event_base *base, int npriorities)
-{
-	int i;
-
-	if (base->event_count_active)
-		return (-1);
-
-	if (npriorities == base->nactivequeues)
-		return (0);
-
-	if (base->nactivequeues) {
-		for (i = 0; i < base->nactivequeues; ++i) {
-			free(base->activequeues[i]);
-		}
-		free(base->activequeues);
-	}
-
-	/* Allocate our priority queues */
-	base->nactivequeues = npriorities;
-	base->activequeues = (struct event_list **)
-	    calloc(base->nactivequeues, sizeof(struct event_list *));
-	if (base->activequeues == NULL)
-		event_err(1, "%s: calloc", __func__);
-
-	for (i = 0; i < base->nactivequeues; ++i) {
-		base->activequeues[i] = malloc(sizeof(struct event_list));
-		if (base->activequeues[i] == NULL)
-			event_err(1, "%s: malloc", __func__);
-		TAILQ_INIT(base->activequeues[i]);
-	}
-
-	return (0);
-}
-
-int
-event_haveevents(struct event_base *base)
-{
-	return (base->event_count > 0);
-}
-
-/*
- * Active events are stored in priority queues.  Lower priorities are always
- * process before higher priorities.  Low priority events can starve high
- * priority ones.
- */
-
-static void
-event_process_active(struct event_base *base)
-{
-	struct event *ev;
-	struct event_list *activeq = NULL;
-	int i;
-	short ncalls;
-
-	for (i = 0; i < base->nactivequeues; ++i) {
-		if (TAILQ_FIRST(base->activequeues[i]) != NULL) {
-			activeq = base->activequeues[i];
-			break;
-		}
-	}
-
-	assert(activeq != NULL);
-
-	for (ev = TAILQ_FIRST(activeq); ev; ev = TAILQ_FIRST(activeq)) {
-		if (ev->ev_events & EV_PERSIST)
-			event_queue_remove(base, ev, EVLIST_ACTIVE);
-		else
-			event_del(ev);
-		
-		/* Allows deletes to work */
-		ncalls = ev->ev_ncalls;
-		ev->ev_pncalls = &ncalls;
-		while (ncalls) {
-			ncalls--;
-			ev->ev_ncalls = ncalls;
-			(*ev->ev_callback)((int)ev->ev_fd, ev->ev_res, ev->ev_arg);
-			if (base->event_break)
-				return;
-		}
-	}
-}
-
-/*
- * Wait continously for events.  We exit only if no events are left.
- */
-
-int
-event_dispatch(void)
-{
-	return (event_loop(0));
-}
-
-int
-event_base_dispatch(struct event_base *event_base)
-{
-  return (event_base_loop(event_base, 0));
-}
-
-const char *
-event_base_get_method(struct event_base *base)
-{
-	assert(base);
-	return (base->evsel->name);
-}
-
-static void
-event_loopexit_cb(int fd, short what, void *arg)
-{
-	struct event_base *base = arg;
-	base->event_gotterm = 1;
-}
-
-/* not thread safe */
-int
-event_loopexit(const struct timeval *tv)
-{
-	return (event_once(-1, EV_TIMEOUT, event_loopexit_cb,
-		    current_base, tv));
-}
-
-int
-event_base_loopexit(struct event_base *event_base, const struct timeval *tv)
-{
-	return (event_base_once(event_base, -1, EV_TIMEOUT, event_loopexit_cb,
-		    event_base, tv));
-}
-
-/* not thread safe */
-int
-event_loopbreak(void)
-{
-	return (event_base_loopbreak(current_base));
-}
-
-int
-event_base_loopbreak(struct event_base *event_base)
-{
-	if (event_base == NULL)
-		return (-1);
-
-	event_base->event_break = 1;
-	return (0);
-}
-
-
-
-/* not thread safe */
-
-int
-event_loop(int flags)
-{
-	return event_base_loop(current_base, flags);
-}
-
-int
-event_base_loop(struct event_base *base, int flags)
-{
-	const struct eventop *evsel = base->evsel;
-	void *evbase = base->evbase;
-	struct timeval tv;
-	struct timeval *tv_p;
-	int res, done;
-
-	/* clear time cache */
-	base->tv_cache.tv_sec = 0;
-
-	if (base->sig.ev_signal_added)
-		evsignal_base = base;
-	done = 0;
-	while (!done) {
-		/* Terminate the loop if we have been asked to */
-		if (base->event_gotterm) {
-			base->event_gotterm = 0;
-			break;
-		}
-
-		if (base->event_break) {
-			base->event_break = 0;
-			break;
-		}
-
-		timeout_correct(base, &tv);
-
-		tv_p = &tv;
-		if (!base->event_count_active && !(flags & EVLOOP_NONBLOCK)) {
-			timeout_next(base, &tv_p);
-		} else {
-			/* 
-			 * if we have active events, we just poll new events
-			 * without waiting.
-			 */
-			evutil_timerclear(&tv);
-		}
-		
-		/* If we have no events, we just exit */
-		if (!event_haveevents(base)) {
-			event_debug(("%s: no events registered.", __func__));
-			return (1);
-		}
-
-		/* update last old time */
-		gettime(base, &base->event_tv);
-
-		/* clear time cache */
-		base->tv_cache.tv_sec = 0;
-
-		res = evsel->dispatch(base, evbase, tv_p);
-
-		if (res == -1)
-			return (-1);
-		gettime(base, &base->tv_cache);
-
-		timeout_process(base);
-
-		if (base->event_count_active) {
-			event_process_active(base);
-			if (!base->event_count_active && (flags & EVLOOP_ONCE))
-				done = 1;
-		} else if (flags & EVLOOP_NONBLOCK)
-			done = 1;
-	}
-
-	/* clear time cache */
-	base->tv_cache.tv_sec = 0;
-
-	event_debug(("%s: asked to terminate loop.", __func__));
-	return (0);
-}
-
-/* Sets up an event for processing once */
-
-struct event_once {
-	struct event ev;
-
-	void (*cb)(int, short, void *);
-	void *arg;
-};
-
-/* One-time callback, it deletes itself */
-
-static void
-event_once_cb(int fd, short events, void *arg)
-{
-	struct event_once *eonce = arg;
-
-	(*eonce->cb)(fd, events, eonce->arg);
-	free(eonce);
-}
-
-/* not threadsafe, event scheduled once. */
-int
-event_once(int fd, short events,
-    void (*callback)(int, short, void *), void *arg, const struct timeval *tv)
-{
-	return event_base_once(current_base, fd, events, callback, arg, tv);
-}
-
-/* Schedules an event once */
-int
-event_base_once(struct event_base *base, int fd, short events,
-    void (*callback)(int, short, void *), void *arg, const struct timeval *tv)
-{
-	struct event_once *eonce;
-	struct timeval etv;
-	int res;
-
-	/* We cannot support signals that just fire once */
-	if (events & EV_SIGNAL)
-		return (-1);
-
-	if ((eonce = calloc(1, sizeof(struct event_once))) == NULL)
-		return (-1);
-
-	eonce->cb = callback;
-	eonce->arg = arg;
-
-	if (events == EV_TIMEOUT) {
-		if (tv == NULL) {
-			evutil_timerclear(&etv);
-			tv = &etv;
-		}
-
-		evtimer_set(&eonce->ev, event_once_cb, eonce);
-	} else if (events & (EV_READ|EV_WRITE)) {
-		events &= EV_READ|EV_WRITE;
-
-		event_set(&eonce->ev, fd, events, event_once_cb, eonce);
-	} else {
-		/* Bad event combination */
-		free(eonce);
-		return (-1);
-	}
-
-	res = event_base_set(base, &eonce->ev);
-	if (res == 0)
-		res = event_add(&eonce->ev, tv);
-	if (res != 0) {
-		free(eonce);
-		return (res);
-	}
-
-	return (0);
-}
-
-void
-event_set(struct event *ev, int fd, short events,
-	  void (*callback)(int, short, void *), void *arg)
-{
-	/* Take the current base - caller needs to set the real base later */
-	ev->ev_base = current_base;
-
-	ev->ev_callback = callback;
-	ev->ev_arg = arg;
-	ev->ev_fd = fd;
-	ev->ev_events = events;
-	ev->ev_res = 0;
-	ev->ev_flags = EVLIST_INIT;
-	ev->ev_ncalls = 0;
-	ev->ev_pncalls = NULL;
-
-	min_heap_elem_init(ev);
-
-	/* by default, we put new events into the middle priority */
-	if(current_base)
-		ev->ev_pri = current_base->nactivequeues/2;
-}
-
-int
-event_base_set(struct event_base *base, struct event *ev)
-{
-	/* Only innocent events may be assigned to a different base */
-	if (ev->ev_flags != EVLIST_INIT)
-		return (-1);
-
-	ev->ev_base = base;
-	ev->ev_pri = base->nactivequeues/2;
-
-	return (0);
-}
-
-/*
- * Set's the priority of an event - if an event is already scheduled
- * changing the priority is going to fail.
- */
-
-int
-event_priority_set(struct event *ev, int pri)
-{
-	if (ev->ev_flags & EVLIST_ACTIVE)
-		return (-1);
-	if (pri < 0 || pri >= ev->ev_base->nactivequeues)
-		return (-1);
-
-	ev->ev_pri = pri;
-
-	return (0);
-}
-
-/*
- * Checks if a specific event is pending or scheduled.
- */
-
-int
-event_pending(struct event *ev, short event, struct timeval *tv)
-{
-	struct timeval	now, res;
-	int flags = 0;
-
-	if (ev->ev_flags & EVLIST_INSERTED)
-		flags |= (ev->ev_events & (EV_READ|EV_WRITE|EV_SIGNAL));
-	if (ev->ev_flags & EVLIST_ACTIVE)
-		flags |= ev->ev_res;
-	if (ev->ev_flags & EVLIST_TIMEOUT)
-		flags |= EV_TIMEOUT;
-
-	event &= (EV_TIMEOUT|EV_READ|EV_WRITE|EV_SIGNAL);
-
-	/* See if there is a timeout that we should report */
-	if (tv != NULL && (flags & event & EV_TIMEOUT)) {
-		gettime(ev->ev_base, &now);
-		evutil_timersub(&ev->ev_timeout, &now, &res);
-		/* correctly remap to real time */
-		evutil_gettimeofday(&now, NULL);
-		evutil_timeradd(&now, &res, tv);
-	}
-
-	return (flags & event);
-}
-
-int
-event_add(struct event *ev, const struct timeval *tv)
-{
-	struct event_base *base = ev->ev_base;
-	const struct eventop *evsel = base->evsel;
-	void *evbase = base->evbase;
-	int res = 0;
-
-	event_debug((
-		 "event_add: event: %p, %s%s%scall %p",
-		 ev,
-		 ev->ev_events & EV_READ ? "EV_READ " : " ",
-		 ev->ev_events & EV_WRITE ? "EV_WRITE " : " ",
-		 tv ? "EV_TIMEOUT " : " ",
-		 ev->ev_callback));
-
-	assert(!(ev->ev_flags & ~EVLIST_ALL));
-
-	/*
-	 * prepare for timeout insertion further below, if we get a
-	 * failure on any step, we should not change any state.
-	 */
-	if (tv != NULL && !(ev->ev_flags & EVLIST_TIMEOUT)) {
-		if (min_heap_reserve(&base->timeheap,
-			1 + min_heap_size(&base->timeheap)) == -1)
-			return (-1);  /* ENOMEM == errno */
-	}
-
-	if ((ev->ev_events & (EV_READ|EV_WRITE|EV_SIGNAL)) &&
-	    !(ev->ev_flags & (EVLIST_INSERTED|EVLIST_ACTIVE))) {
-		res = evsel->add(evbase, ev);
-		if (res != -1)
-			event_queue_insert(base, ev, EVLIST_INSERTED);
-	}
-
-	/* 
-	 * we should change the timout state only if the previous event
-	 * addition succeeded.
-	 */
-	if (res != -1 && tv != NULL) {
-		struct timeval now;
-
-		/* 
-		 * we already reserved memory above for the case where we
-		 * are not replacing an exisiting timeout.
-		 */
-		if (ev->ev_flags & EVLIST_TIMEOUT)
-			event_queue_remove(base, ev, EVLIST_TIMEOUT);
-
-		/* Check if it is active due to a timeout.  Rescheduling
-		 * this timeout before the callback can be executed
-		 * removes it from the active list. */
-		if ((ev->ev_flags & EVLIST_ACTIVE) &&
-		    (ev->ev_res & EV_TIMEOUT)) {
-			/* See if we are just active executing this
-			 * event in a loop
-			 */
-			if (ev->ev_ncalls && ev->ev_pncalls) {
-				/* Abort loop */
-				*ev->ev_pncalls = 0;
-			}
-			
-			event_queue_remove(base, ev, EVLIST_ACTIVE);
-		}
-
-		gettime(base, &now);
-		evutil_timeradd(&now, tv, &ev->ev_timeout);
-
-		event_debug((
-			 "event_add: timeout in %ld seconds, call %p",
-			 tv->tv_sec, ev->ev_callback));
-
-		event_queue_insert(base, ev, EVLIST_TIMEOUT);
-	}
-
-	return (res);
-}
-
-int
-event_del(struct event *ev)
-{
-	struct event_base *base;
-
-	event_debug(("event_del: %p, callback %p",
-		 ev, ev->ev_callback));
-
-	/* An event without a base has not been added */
-	if (ev->ev_base == NULL)
-		return (-1);
-
-	base = ev->ev_base;
-
-	assert(!(ev->ev_flags & ~EVLIST_ALL));
-
-	/* See if we are just active executing this event in a loop */
-	if (ev->ev_ncalls && ev->ev_pncalls) {
-		/* Abort loop */
-		*ev->ev_pncalls = 0;
-	}
-
-	if (ev->ev_flags & EVLIST_TIMEOUT)
-		event_queue_remove(base, ev, EVLIST_TIMEOUT);
-
-	if (ev->ev_flags & EVLIST_ACTIVE)
-		event_queue_remove(base, ev, EVLIST_ACTIVE);
-
-	if (ev->ev_flags & EVLIST_INSERTED) {
-		event_queue_remove(base, ev, EVLIST_INSERTED);
-		return (base->evsel->del(base->evbase, ev));
-	}
-
-	return (0);
-}
-
-void
-event_active(struct event *ev, int res, short ncalls)
-{
-	/* We get different kinds of events, add them together */
-	if (ev->ev_flags & EVLIST_ACTIVE) {
-		ev->ev_res |= res;
-		return;
-	}
-
-	ev->ev_res = res;
-	ev->ev_ncalls = ncalls;
-	ev->ev_pncalls = NULL;
-	event_queue_insert(ev->ev_base, ev, EVLIST_ACTIVE);
-}
-
-static int
-timeout_next(struct event_base *base, struct timeval **tv_p)
-{
-	struct timeval now;
-	struct event *ev;
-	struct timeval *tv = *tv_p;
-
-	if ((ev = min_heap_top(&base->timeheap)) == NULL) {
-		/* if no time-based events are active wait for I/O */
-		*tv_p = NULL;
-		return (0);
-	}
-
-	if (gettime(base, &now) == -1)
-		return (-1);
-
-	if (evutil_timercmp(&ev->ev_timeout, &now, <=)) {
-		evutil_timerclear(tv);
-		return (0);
-	}
-
-	evutil_timersub(&ev->ev_timeout, &now, tv);
-
-	assert(tv->tv_sec >= 0);
-	assert(tv->tv_usec >= 0);
-
-	event_debug(("timeout_next: in %ld seconds", tv->tv_sec));
-	return (0);
-}
-
-/*
- * Determines if the time is running backwards by comparing the current
- * time against the last time we checked.  Not needed when using clock
- * monotonic.
- */
-
-static void
-timeout_correct(struct event_base *base, struct timeval *tv)
-{
-	struct event **pev;
-	unsigned int size;
-	struct timeval off;
-
-	if (use_monotonic)
-		return;
-
-	/* Check if time is running backwards */
-	gettime(base, tv);
-	if (evutil_timercmp(tv, &base->event_tv, >=)) {
-		base->event_tv = *tv;
-		return;
-	}
-
-	event_debug(("%s: time is running backwards, corrected",
-		    __func__));
-	evutil_timersub(&base->event_tv, tv, &off);
-
-	/*
-	 * We can modify the key element of the node without destroying
-	 * the key, beause we apply it to all in the right order.
-	 */
-	pev = base->timeheap.p;
-	size = base->timeheap.n;
-	for (; size-- > 0; ++pev) {
-		struct timeval *ev_tv = &(**pev).ev_timeout;
-		evutil_timersub(ev_tv, &off, ev_tv);
-	}
-	/* Now remember what the new time turned out to be. */
-	base->event_tv = *tv;
-}
-
-void
-timeout_process(struct event_base *base)
-{
-	struct timeval now;
-	struct event *ev;
-
-	if (min_heap_empty(&base->timeheap))
-		return;
-
-	gettime(base, &now);
-
-	while ((ev = min_heap_top(&base->timeheap))) {
-		if (evutil_timercmp(&ev->ev_timeout, &now, >))
-			break;
-
-		/* delete this event from the I/O queues */
-		event_del(ev);
-
-		event_debug(("timeout_process: call %p",
-			 ev->ev_callback));
-		event_active(ev, EV_TIMEOUT, 1);
-	}
-}
-
-void
-event_queue_remove(struct event_base *base, struct event *ev, int queue)
-{
-	if (!(ev->ev_flags & queue))
-		event_errx(1, "%s: %p(fd %d) not on queue %x", __func__,
-			   ev, ev->ev_fd, queue);
-
-	if (~ev->ev_flags & EVLIST_INTERNAL)
-		base->event_count--;
-
-	ev->ev_flags &= ~queue;
-	switch (queue) {
-	case EVLIST_INSERTED:
-		TAILQ_REMOVE(&base->eventqueue, ev, ev_next);
-		break;
-	case EVLIST_ACTIVE:
-		base->event_count_active--;
-		TAILQ_REMOVE(base->activequeues[ev->ev_pri],
-		    ev, ev_active_next);
-		break;
-	case EVLIST_TIMEOUT:
-		min_heap_erase(&base->timeheap, ev);
-		break;
-	default:
-		event_errx(1, "%s: unknown queue %x", __func__, queue);
-	}
-}
-
-void
-event_queue_insert(struct event_base *base, struct event *ev, int queue)
-{
-	if (ev->ev_flags & queue) {
-		/* Double insertion is possible for active events */
-		if (queue & EVLIST_ACTIVE)
-			return;
-
-		event_errx(1, "%s: %p(fd %d) already on queue %x", __func__,
-			   ev, ev->ev_fd, queue);
-	}
-
-	if (~ev->ev_flags & EVLIST_INTERNAL)
-		base->event_count++;
-
-	ev->ev_flags |= queue;
-	switch (queue) {
-	case EVLIST_INSERTED:
-		TAILQ_INSERT_TAIL(&base->eventqueue, ev, ev_next);
-		break;
-	case EVLIST_ACTIVE:
-		base->event_count_active++;
-		TAILQ_INSERT_TAIL(base->activequeues[ev->ev_pri],
-		    ev,ev_active_next);
-		break;
-	case EVLIST_TIMEOUT: {
-		min_heap_push(&base->timeheap, ev);
-		break;
-	}
-	default:
-		event_errx(1, "%s: unknown queue %x", __func__, queue);
-	}
-}
-
-/* Functions for debugging */
-
-const char *
-event_get_version(void)
-{
-	return (VERSION);
-}
-
-/* 
- * No thread-safe interface needed - the information should be the same
- * for all threads.
- */
-
-const char *
-event_get_method(void)
-{
-	return (current_base->evsel->name);
-}
diff --git a/base/third_party/libevent/event.h b/base/third_party/libevent/event.h
deleted file mode 100644
index f0887b9..0000000
--- a/base/third_party/libevent/event.h
+++ /dev/null
@@ -1,1212 +0,0 @@
-/*
- * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef _EVENT_H_
-#define _EVENT_H_
-
-/** @mainpage
-
-  @section intro Introduction
-
-  libevent is an event notification library for developing scalable network
-  servers.  The libevent API provides a mechanism to execute a callback
-  function when a specific event occurs on a file descriptor or after a
-  timeout has been reached. Furthermore, libevent also support callbacks due
-  to signals or regular timeouts.
-
-  libevent is meant to replace the event loop found in event driven network
-  servers. An application just needs to call event_dispatch() and then add or
-  remove events dynamically without having to change the event loop.
-
-  Currently, libevent supports /dev/poll, kqueue(2), select(2), poll(2) and
-  epoll(4). It also has experimental support for real-time signals. The
-  internal event mechanism is completely independent of the exposed event API,
-  and a simple update of libevent can provide new functionality without having
-  to redesign the applications. As a result, Libevent allows for portable
-  application development and provides the most scalable event notification
-  mechanism available on an operating system. Libevent can also be used for
-  multi-threaded aplications; see Steven Grimm's explanation. Libevent should
-  compile on Linux, *BSD, Mac OS X, Solaris and Windows.
-
-  @section usage Standard usage
-
-  Every program that uses libevent must include the <event.h> header, and pass
-  the -levent flag to the linker.  Before using any of the functions in the
-  library, you must call event_init() or event_base_new() to perform one-time
-  initialization of the libevent library.
-
-  @section event Event notification
-
-  For each file descriptor that you wish to monitor, you must declare an event
-  structure and call event_set() to initialize the members of the structure.
-  To enable notification, you add the structure to the list of monitored
-  events by calling event_add().  The event structure must remain allocated as
-  long as it is active, so it should be allocated on the heap. Finally, you
-  call event_dispatch() to loop and dispatch events.
-
-  @section bufferevent I/O Buffers
-
-  libevent provides an abstraction on top of the regular event callbacks. This
-  abstraction is called a buffered event. A buffered event provides input and
-  output buffers that get filled and drained automatically. The user of a
-  buffered event no longer deals directly with the I/O, but instead is reading
-  from input and writing to output buffers.
-
-  Once initialized via bufferevent_new(), the bufferevent structure can be
-  used repeatedly with bufferevent_enable() and bufferevent_disable().
-  Instead of reading and writing directly to a socket, you would call
-  bufferevent_read() and bufferevent_write().
-
-  When read enabled the bufferevent will try to read from the file descriptor
-  and call the read callback. The write callback is executed whenever the
-  output buffer is drained below the write low watermark, which is 0 by
-  default.
-
-  @section timers Timers
-
-  libevent can also be used to create timers that invoke a callback after a
-  certain amount of time has expired. The evtimer_set() function prepares an
-  event struct to be used as a timer. To activate the timer, call
-  evtimer_add(). Timers can be deactivated by calling evtimer_del().
-
-  @section timeouts Timeouts
-
-  In addition to simple timers, libevent can assign timeout events to file
-  descriptors that are triggered whenever a certain amount of time has passed
-  with no activity on a file descriptor.  The timeout_set() function
-  initializes an event struct for use as a timeout. Once initialized, the
-  event must be activated by using timeout_add().  To cancel the timeout, call
-  timeout_del().
-
-  @section evdns Asynchronous DNS resolution
-
-  libevent provides an asynchronous DNS resolver that should be used instead
-  of the standard DNS resolver functions.  These functions can be imported by
-  including the <evdns.h> header in your program. Before using any of the
-  resolver functions, you must call evdns_init() to initialize the library. To
-  convert a hostname to an IP address, you call the evdns_resolve_ipv4()
-  function.  To perform a reverse lookup, you would call the
-  evdns_resolve_reverse() function.  All of these functions use callbacks to
-  avoid blocking while the lookup is performed.
-
-  @section evhttp Event-driven HTTP servers
-
-  libevent provides a very simple event-driven HTTP server that can be
-  embedded in your program and used to service HTTP requests.
-
-  To use this capability, you need to include the <evhttp.h> header in your
-  program.  You create the server by calling evhttp_new(). Add addresses and
-  ports to listen on with evhttp_bind_socket(). You then register one or more
-  callbacks to handle incoming requests.  Each URI can be assigned a callback
-  via the evhttp_set_cb() function.  A generic callback function can also be
-  registered via evhttp_set_gencb(); this callback will be invoked if no other
-  callbacks have been registered for a given URI.
-
-  @section evrpc A framework for RPC servers and clients
- 
-  libevents provides a framework for creating RPC servers and clients.  It
-  takes care of marshaling and unmarshaling all data structures.
-
-  @section api API Reference
-
-  To browse the complete documentation of the libevent API, click on any of
-  the following links.
-
-  event.h
-  The primary libevent header
-
-  evdns.h
-  Asynchronous DNS resolution
-
-  evhttp.h
-  An embedded libevent-based HTTP server
-
-  evrpc.h
-  A framework for creating RPC servers and clients
-
- */
-
-/** @file event.h
-
-  A library for writing event-driven network servers
-
- */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "event-config.h"
-#ifdef _EVENT_HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif
-#ifdef _EVENT_HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#ifdef _EVENT_HAVE_STDINT_H
-#include <stdint.h>
-#endif
-#include <stdarg.h>
-
-/* For int types. */
-#include "evutil.h"
-
-#ifdef WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-typedef unsigned char u_char;
-typedef unsigned short u_short;
-#endif
-
-#define EVLIST_TIMEOUT	0x01
-#define EVLIST_INSERTED	0x02
-#define EVLIST_SIGNAL	0x04
-#define EVLIST_ACTIVE	0x08
-#define EVLIST_INTERNAL	0x10
-#define EVLIST_INIT	0x80
-
-/* EVLIST_X_ Private space: 0x1000-0xf000 */
-#define EVLIST_ALL	(0xf000 | 0x9f)
-
-#define EV_TIMEOUT	0x01
-#define EV_READ		0x02
-#define EV_WRITE	0x04
-#define EV_SIGNAL	0x08
-#define EV_PERSIST	0x10	/* Persistant event */
-
-/* Fix so that ppl dont have to run with <sys/queue.h> */
-#ifndef TAILQ_ENTRY
-#define _EVENT_DEFINED_TQENTRY
-#define TAILQ_ENTRY(type)						\
-struct {								\
-	struct type *tqe_next;	/* next element */			\
-	struct type **tqe_prev;	/* address of previous next element */	\
-}
-#endif /* !TAILQ_ENTRY */
-
-struct event_base;
-#ifndef EVENT_NO_STRUCT
-struct event {
-	TAILQ_ENTRY (event) ev_next;
-	TAILQ_ENTRY (event) ev_active_next;
-	TAILQ_ENTRY (event) ev_signal_next;
-	unsigned int min_heap_idx;	/* for managing timeouts */
-
-	struct event_base *ev_base;
-
-	int ev_fd;
-	short ev_events;
-	short ev_ncalls;
-	short *ev_pncalls;	/* Allows deletes in callback */
-
-	struct timeval ev_timeout;
-
-	int ev_pri;		/* smaller numbers are higher priority */
-
-	void (*ev_callback)(int, short, void *arg);
-	void *ev_arg;
-
-	int ev_res;		/* result passed to event callback */
-	int ev_flags;
-};
-#else
-struct event;
-#endif
-
-#define EVENT_SIGNAL(ev)	(int)(ev)->ev_fd
-#define EVENT_FD(ev)		(int)(ev)->ev_fd
-
-/*
- * Key-Value pairs.  Can be used for HTTP headers but also for
- * query argument parsing.
- */
-struct evkeyval {
-	TAILQ_ENTRY(evkeyval) next;
-
-	char *key;
-	char *value;
-};
-
-#ifdef _EVENT_DEFINED_TQENTRY
-#undef TAILQ_ENTRY
-struct event_list;
-struct evkeyvalq;
-#undef _EVENT_DEFINED_TQENTRY
-#else
-TAILQ_HEAD (event_list, event);
-TAILQ_HEAD (evkeyvalq, evkeyval);
-#endif /* _EVENT_DEFINED_TQENTRY */
-
-/**
-  Initialize the event API.
-
-  Use event_base_new() to initialize a new event base, but does not set
-  the current_base global.   If using only event_base_new(), each event
-  added must have an event base set with event_base_set()
-
-  @see event_base_set(), event_base_free(), event_init()
- */
-struct event_base *event_base_new(void);
-
-/**
-  Initialize the event API.
-
-  The event API needs to be initialized with event_init() before it can be
-  used.  Sets the current_base global representing the default base for
-  events that have no base associated with them.
-
-  @see event_base_set(), event_base_new()
- */
-struct event_base *event_init(void);
-
-/**
-  Reinitialized the event base after a fork
-
-  Some event mechanisms do not survive across fork.   The event base needs
-  to be reinitialized with the event_reinit() function.
-
-  @param base the event base that needs to be re-initialized
-  @return 0 if successful, or -1 if some events could not be re-added.
-  @see event_base_new(), event_init()
-*/
-int event_reinit(struct event_base *base);
-
-/**
-  Loop to process events.
-
-  In order to process events, an application needs to call
-  event_dispatch().  This function only returns on error, and should
-  replace the event core of the application program.
-
-  @see event_base_dispatch()
- */
-int event_dispatch(void);
-
-
-/**
-  Threadsafe event dispatching loop.
-
-  @param eb the event_base structure returned by event_init()
-  @see event_init(), event_dispatch()
- */
-int event_base_dispatch(struct event_base *);
-
-
-/**
- Get the kernel event notification mechanism used by libevent.
- 
- @param eb the event_base structure returned by event_base_new()
- @return a string identifying the kernel event mechanism (kqueue, epoll, etc.)
- */
-const char *event_base_get_method(struct event_base *);
-        
-        
-/**
-  Deallocate all memory associated with an event_base, and free the base.
-
-  Note that this function will not close any fds or free any memory passed
-  to event_set as the argument to callback.
-
-  @param eb an event_base to be freed
- */
-void event_base_free(struct event_base *);
-
-
-#define _EVENT_LOG_DEBUG 0
-#define _EVENT_LOG_MSG   1
-#define _EVENT_LOG_WARN  2
-#define _EVENT_LOG_ERR   3
-typedef void (*event_log_cb)(int severity, const char *msg);
-/**
-  Redirect libevent's log messages.
-
-  @param cb a function taking two arguments: an integer severity between
-     _EVENT_LOG_DEBUG and _EVENT_LOG_ERR, and a string.  If cb is NULL,
-	 then the default log is used.
-  */
-void event_set_log_callback(event_log_cb cb);
-
-/**
-  Associate a different event base with an event.
-
-  @param eb the event base
-  @param ev the event
- */
-int event_base_set(struct event_base *, struct event *);
-
-/**
- event_loop() flags
- */
-/*@{*/
-#define EVLOOP_ONCE	0x01	/**< Block at most once. */
-#define EVLOOP_NONBLOCK	0x02	/**< Do not block. */
-/*@}*/
-
-/**
-  Handle events.
-
-  This is a more flexible version of event_dispatch().
-
-  @param flags any combination of EVLOOP_ONCE | EVLOOP_NONBLOCK
-  @return 0 if successful, -1 if an error occurred, or 1 if no events were
-    registered.
-  @see event_loopexit(), event_base_loop()
-*/
-int event_loop(int);
-
-/**
-  Handle events (threadsafe version).
-
-  This is a more flexible version of event_base_dispatch().
-
-  @param eb the event_base structure returned by event_init()
-  @param flags any combination of EVLOOP_ONCE | EVLOOP_NONBLOCK
-  @return 0 if successful, -1 if an error occurred, or 1 if no events were
-    registered.
-  @see event_loopexit(), event_base_loop()
-  */
-int event_base_loop(struct event_base *, int);
-
-/**
-  Exit the event loop after the specified time.
-
-  The next event_loop() iteration after the given timer expires will
-  complete normally (handling all queued events) then exit without
-  blocking for events again.
-
-  Subsequent invocations of event_loop() will proceed normally.
-
-  @param tv the amount of time after which the loop should terminate.
-  @return 0 if successful, or -1 if an error occurred
-  @see event_loop(), event_base_loop(), event_base_loopexit()
-  */
-int event_loopexit(const struct timeval *);
-
-
-/**
-  Exit the event loop after the specified time (threadsafe variant).
-
-  The next event_base_loop() iteration after the given timer expires will
-  complete normally (handling all queued events) then exit without
-  blocking for events again.
-
-  Subsequent invocations of event_base_loop() will proceed normally.
-
-  @param eb the event_base structure returned by event_init()
-  @param tv the amount of time after which the loop should terminate.
-  @return 0 if successful, or -1 if an error occurred
-  @see event_loopexit()
- */
-int event_base_loopexit(struct event_base *, const struct timeval *);
-
-/**
-  Abort the active event_loop() immediately.
-
-  event_loop() will abort the loop after the next event is completed;
-  event_loopbreak() is typically invoked from this event's callback.
-  This behavior is analogous to the "break;" statement.
-
-  Subsequent invocations of event_loop() will proceed normally.
-
-  @return 0 if successful, or -1 if an error occurred
-  @see event_base_loopbreak(), event_loopexit()
- */
-int event_loopbreak(void);
-
-/**
-  Abort the active event_base_loop() immediately.
-
-  event_base_loop() will abort the loop after the next event is completed;
-  event_base_loopbreak() is typically invoked from this event's callback.
-  This behavior is analogous to the "break;" statement.
-
-  Subsequent invocations of event_loop() will proceed normally.
-
-  @param eb the event_base structure returned by event_init()
-  @return 0 if successful, or -1 if an error occurred
-  @see event_base_loopexit
- */
-int event_base_loopbreak(struct event_base *);
-
-
-/**
-  Add a timer event.
-
-  @param ev the event struct
-  @param tv timeval struct
- */
-#define evtimer_add(ev, tv)		event_add(ev, tv)
-
-
-/**
-  Define a timer event.
-
-  @param ev event struct to be modified
-  @param cb callback function
-  @param arg argument that will be passed to the callback function
- */
-#define evtimer_set(ev, cb, arg)	event_set(ev, -1, 0, cb, arg)
-
-
-/**
- * Delete a timer event.
- *
- * @param ev the event struct to be disabled
- */
-#define evtimer_del(ev)			event_del(ev)
-#define evtimer_pending(ev, tv)		event_pending(ev, EV_TIMEOUT, tv)
-#define evtimer_initialized(ev)		((ev)->ev_flags & EVLIST_INIT)
-
-/**
- * Add a timeout event.
- *
- * @param ev the event struct to be disabled
- * @param tv the timeout value, in seconds
- */
-#define timeout_add(ev, tv)		event_add(ev, tv)
-
-
-/**
- * Define a timeout event.
- *
- * @param ev the event struct to be defined
- * @param cb the callback to be invoked when the timeout expires
- * @param arg the argument to be passed to the callback
- */
-#define timeout_set(ev, cb, arg)	event_set(ev, -1, 0, cb, arg)
-
-
-/**
- * Disable a timeout event.
- *
- * @param ev the timeout event to be disabled
- */
-#define timeout_del(ev)			event_del(ev)
-
-#define timeout_pending(ev, tv)		event_pending(ev, EV_TIMEOUT, tv)
-#define timeout_initialized(ev)		((ev)->ev_flags & EVLIST_INIT)
-
-#define signal_add(ev, tv)		event_add(ev, tv)
-#define signal_set(ev, x, cb, arg)	\
-	event_set(ev, x, EV_SIGNAL|EV_PERSIST, cb, arg)
-#define signal_del(ev)			event_del(ev)
-#define signal_pending(ev, tv)		event_pending(ev, EV_SIGNAL, tv)
-#define signal_initialized(ev)		((ev)->ev_flags & EVLIST_INIT)
-
-/**
-  Prepare an event structure to be added.
-
-  The function event_set() prepares the event structure ev to be used in
-  future calls to event_add() and event_del().  The event will be prepared to
-  call the function specified by the fn argument with an int argument
-  indicating the file descriptor, a short argument indicating the type of
-  event, and a void * argument given in the arg argument.  The fd indicates
-  the file descriptor that should be monitored for events.  The events can be
-  either EV_READ, EV_WRITE, or both.  Indicating that an application can read
-  or write from the file descriptor respectively without blocking.
-
-  The function fn will be called with the file descriptor that triggered the
-  event and the type of event which will be either EV_TIMEOUT, EV_SIGNAL,
-  EV_READ, or EV_WRITE.  The additional flag EV_PERSIST makes an event_add()
-  persistent until event_del() has been called.
-
-  @param ev an event struct to be modified
-  @param fd the file descriptor to be monitored
-  @param event desired events to monitor; can be EV_READ and/or EV_WRITE
-  @param fn callback function to be invoked when the event occurs
-  @param arg an argument to be passed to the callback function
-
-  @see event_add(), event_del(), event_once()
-
- */
-void event_set(struct event *, int, short, void (*)(int, short, void *), void *);
-
-/**
-  Schedule a one-time event to occur.
-
-  The function event_once() is similar to event_set().  However, it schedules
-  a callback to be called exactly once and does not require the caller to
-  prepare an event structure.
-
-  @param fd a file descriptor to monitor
-  @param events event(s) to monitor; can be any of EV_TIMEOUT | EV_READ |
-         EV_WRITE
-  @param callback callback function to be invoked when the event occurs
-  @param arg an argument to be passed to the callback function
-  @param timeout the maximum amount of time to wait for the event, or NULL
-         to wait forever
-  @return 0 if successful, or -1 if an error occurred
-  @see event_set()
-
- */
-int event_once(int, short, void (*)(int, short, void *), void *,
-    const struct timeval *);
-
-
-/**
-  Schedule a one-time event (threadsafe variant)
-
-  The function event_base_once() is similar to event_set().  However, it
-  schedules a callback to be called exactly once and does not require the
-  caller to prepare an event structure.
-
-  @param base an event_base returned by event_init()
-  @param fd a file descriptor to monitor
-  @param events event(s) to monitor; can be any of EV_TIMEOUT | EV_READ |
-         EV_WRITE
-  @param callback callback function to be invoked when the event occurs
-  @param arg an argument to be passed to the callback function
-  @param timeout the maximum amount of time to wait for the event, or NULL
-         to wait forever
-  @return 0 if successful, or -1 if an error occurred
-  @see event_once()
- */
-int event_base_once(struct event_base *base, int fd, short events,
-    void (*callback)(int, short, void *), void *arg,
-    const struct timeval *timeout);
-
-
-/**
-  Add an event to the set of monitored events.
-
-  The function event_add() schedules the execution of the ev event when the
-  event specified in event_set() occurs or in at least the time specified in
-  the tv.  If tv is NULL, no timeout occurs and the function will only be
-  called if a matching event occurs on the file descriptor.  The event in the
-  ev argument must be already initialized by event_set() and may not be used
-  in calls to event_set() until it has timed out or been removed with
-  event_del().  If the event in the ev argument already has a scheduled
-  timeout, the old timeout will be replaced by the new one.
-
-  @param ev an event struct initialized via event_set()
-  @param timeout the maximum amount of time to wait for the event, or NULL
-         to wait forever
-  @return 0 if successful, or -1 if an error occurred
-  @see event_del(), event_set()
-  */
-int event_add(struct event *ev, const struct timeval *timeout);
-
-
-/**
-  Remove an event from the set of monitored events.
-
-  The function event_del() will cancel the event in the argument ev.  If the
-  event has already executed or has never been added the call will have no
-  effect.
-
-  @param ev an event struct to be removed from the working set
-  @return 0 if successful, or -1 if an error occurred
-  @see event_add()
- */
-int event_del(struct event *);
-
-void event_active(struct event *, int, short);
-
-
-/**
-  Checks if a specific event is pending or scheduled.
-
-  @param ev an event struct previously passed to event_add()
-  @param event the requested event type; any of EV_TIMEOUT|EV_READ|
-         EV_WRITE|EV_SIGNAL
-  @param tv an alternate timeout (FIXME - is this true?)
-
-  @return 1 if the event is pending, or 0 if the event has not occurred
-
- */
-int event_pending(struct event *ev, short event, struct timeval *tv);
-
-
-/**
-  Test if an event structure has been initialized.
-
-  The event_initialized() macro can be used to check if an event has been
-  initialized.
-
-  @param ev an event structure to be tested
-  @return 1 if the structure has been initialized, or 0 if it has not been
-          initialized
- */
-#ifdef WIN32
-#define event_initialized(ev)		((ev)->ev_flags & EVLIST_INIT && (ev)->ev_fd != (int)INVALID_HANDLE_VALUE)
-#else
-#define event_initialized(ev)		((ev)->ev_flags & EVLIST_INIT)
-#endif
-
-
-/**
-  Get the libevent version number.
-
-  @return a string containing the version number of libevent
- */
-const char *event_get_version(void);
-
-
-/**
-  Get the kernel event notification mechanism used by libevent.
-
-  @return a string identifying the kernel event mechanism (kqueue, epoll, etc.)
- */
-const char *event_get_method(void);
-
-
-/**
-  Set the number of different event priorities.
-
-  By default libevent schedules all active events with the same priority.
-  However, some time it is desirable to process some events with a higher
-  priority than others.  For that reason, libevent supports strict priority
-  queues.  Active events with a lower priority are always processed before
-  events with a higher priority.
-
-  The number of different priorities can be set initially with the
-  event_priority_init() function.  This function should be called before the
-  first call to event_dispatch().  The event_priority_set() function can be
-  used to assign a priority to an event.  By default, libevent assigns the
-  middle priority to all events unless their priority is explicitly set.
-
-  @param npriorities the maximum number of priorities
-  @return 0 if successful, or -1 if an error occurred
-  @see event_base_priority_init(), event_priority_set()
-
- */
-int	event_priority_init(int);
-
-
-/**
-  Set the number of different event priorities (threadsafe variant).
-
-  See the description of event_priority_init() for more information.
-
-  @param eb the event_base structure returned by event_init()
-  @param npriorities the maximum number of priorities
-  @return 0 if successful, or -1 if an error occurred
-  @see event_priority_init(), event_priority_set()
- */
-int	event_base_priority_init(struct event_base *, int);
-
-
-/**
-  Assign a priority to an event.
-
-  @param ev an event struct
-  @param priority the new priority to be assigned
-  @return 0 if successful, or -1 if an error occurred
-  @see event_priority_init()
-  */
-int	event_priority_set(struct event *, int);
-
-
-/* These functions deal with buffering input and output */
-
-struct evbuffer {
-	u_char *buffer;
-	u_char *orig_buffer;
-
-	size_t misalign;
-	size_t totallen;
-	size_t off;
-
-	void (*cb)(struct evbuffer *, size_t, size_t, void *);
-	void *cbarg;
-};
-
-/* Just for error reporting - use other constants otherwise */
-#define EVBUFFER_READ		0x01
-#define EVBUFFER_WRITE		0x02
-#define EVBUFFER_EOF		0x10
-#define EVBUFFER_ERROR		0x20
-#define EVBUFFER_TIMEOUT	0x40
-
-struct bufferevent;
-typedef void (*evbuffercb)(struct bufferevent *, void *);
-typedef void (*everrorcb)(struct bufferevent *, short what, void *);
-
-struct event_watermark {
-	size_t low;
-	size_t high;
-};
-
-#ifndef EVENT_NO_STRUCT
-struct bufferevent {
-	struct event_base *ev_base;
-
-	struct event ev_read;
-	struct event ev_write;
-
-	struct evbuffer *input;
-	struct evbuffer *output;
-
-	struct event_watermark wm_read;
-	struct event_watermark wm_write;
-
-	evbuffercb readcb;
-	evbuffercb writecb;
-	everrorcb errorcb;
-	void *cbarg;
-
-	int timeout_read;	/* in seconds */
-	int timeout_write;	/* in seconds */
-
-	short enabled;	/* events that are currently enabled */
-};
-#endif
-
-/**
-  Create a new bufferevent.
-
-  libevent provides an abstraction on top of the regular event callbacks.
-  This abstraction is called a buffered event.  A buffered event provides
-  input and output buffers that get filled and drained automatically.  The
-  user of a buffered event no longer deals directly with the I/O, but
-  instead is reading from input and writing to output buffers.
-
-  Once initialized, the bufferevent structure can be used repeatedly with
-  bufferevent_enable() and bufferevent_disable().
-
-  When read enabled the bufferevent will try to read from the file descriptor
-  and call the read callback.  The write callback is executed whenever the
-  output buffer is drained below the write low watermark, which is 0 by
-  default.
-
-  If multiple bases are in use, bufferevent_base_set() must be called before
-  enabling the bufferevent for the first time.
-
-  @param fd the file descriptor from which data is read and written to.
-  		This file descriptor is not allowed to be a pipe(2).
-  @param readcb callback to invoke when there is data to be read, or NULL if
-         no callback is desired
-  @param writecb callback to invoke when the file descriptor is ready for
-         writing, or NULL if no callback is desired
-  @param errorcb callback to invoke when there is an error on the file
-         descriptor
-  @param cbarg an argument that will be supplied to each of the callbacks
-         (readcb, writecb, and errorcb)
-  @return a pointer to a newly allocated bufferevent struct, or NULL if an
-          error occurred
-  @see bufferevent_base_set(), bufferevent_free()
-  */
-struct bufferevent *bufferevent_new(int fd,
-    evbuffercb readcb, evbuffercb writecb, everrorcb errorcb, void *cbarg);
-
-
-/**
-  Assign a bufferevent to a specific event_base.
-
-  @param base an event_base returned by event_init()
-  @param bufev a bufferevent struct returned by bufferevent_new()
-  @return 0 if successful, or -1 if an error occurred
-  @see bufferevent_new()
- */
-int bufferevent_base_set(struct event_base *base, struct bufferevent *bufev);
-
-
-/**
-  Assign a priority to a bufferevent.
-
-  @param bufev a bufferevent struct
-  @param pri the priority to be assigned
-  @return 0 if successful, or -1 if an error occurred
-  */
-int bufferevent_priority_set(struct bufferevent *bufev, int pri);
-
-
-/**
-  Deallocate the storage associated with a bufferevent structure.
-
-  @param bufev the bufferevent structure to be freed.
-  */
-void bufferevent_free(struct bufferevent *bufev);
-
-
-/**
-  Changes the callbacks for a bufferevent.
-
-  @param bufev the bufferevent object for which to change callbacks
-  @param readcb callback to invoke when there is data to be read, or NULL if
-         no callback is desired
-  @param writecb callback to invoke when the file descriptor is ready for
-         writing, or NULL if no callback is desired
-  @param errorcb callback to invoke when there is an error on the file
-         descriptor
-  @param cbarg an argument that will be supplied to each of the callbacks
-         (readcb, writecb, and errorcb)
-  @see bufferevent_new()
-  */
-void bufferevent_setcb(struct bufferevent *bufev,
-    evbuffercb readcb, evbuffercb writecb, everrorcb errorcb, void *cbarg);
-
-/**
-  Changes the file descriptor on which the bufferevent operates.
-
-  @param bufev the bufferevent object for which to change the file descriptor
-  @param fd the file descriptor to operate on
-*/
-void bufferevent_setfd(struct bufferevent *bufev, int fd);
-
-/**
-  Write data to a bufferevent buffer.
-
-  The bufferevent_write() function can be used to write data to the file
-  descriptor.  The data is appended to the output buffer and written to the
-  descriptor automatically as it becomes available for writing.
-
-  @param bufev the bufferevent to be written to
-  @param data a pointer to the data to be written
-  @param size the length of the data, in bytes
-  @return 0 if successful, or -1 if an error occurred
-  @see bufferevent_write_buffer()
-  */
-int bufferevent_write(struct bufferevent *bufev,
-    const void *data, size_t size);
-
-
-/**
-  Write data from an evbuffer to a bufferevent buffer.  The evbuffer is
-  being drained as a result.
-
-  @param bufev the bufferevent to be written to
-  @param buf the evbuffer to be written
-  @return 0 if successful, or -1 if an error occurred
-  @see bufferevent_write()
- */
-int bufferevent_write_buffer(struct bufferevent *bufev, struct evbuffer *buf);
-
-
-/**
-  Read data from a bufferevent buffer.
-
-  The bufferevent_read() function is used to read data from the input buffer.
-
-  @param bufev the bufferevent to be read from
-  @param data pointer to a buffer that will store the data
-  @param size the size of the data buffer, in bytes
-  @return the amount of data read, in bytes.
- */
-size_t bufferevent_read(struct bufferevent *bufev, void *data, size_t size);
-
-/**
-  Enable a bufferevent.
-
-  @param bufev the bufferevent to be enabled
-  @param event any combination of EV_READ | EV_WRITE.
-  @return 0 if successful, or -1 if an error occurred
-  @see bufferevent_disable()
- */
-int bufferevent_enable(struct bufferevent *bufev, short event);
-
-
-/**
-  Disable a bufferevent.
-
-  @param bufev the bufferevent to be disabled
-  @param event any combination of EV_READ | EV_WRITE.
-  @return 0 if successful, or -1 if an error occurred
-  @see bufferevent_enable()
- */
-int bufferevent_disable(struct bufferevent *bufev, short event);
-
-
-/**
-  Set the read and write timeout for a buffered event.
-
-  @param bufev the bufferevent to be modified
-  @param timeout_read the read timeout
-  @param timeout_write the write timeout
- */
-void bufferevent_settimeout(struct bufferevent *bufev,
-    int timeout_read, int timeout_write);
-
-
-/**
-  Sets the watermarks for read and write events.
-
-  On input, a bufferevent does not invoke the user read callback unless
-  there is at least low watermark data in the buffer.   If the read buffer
-  is beyond the high watermark, the buffevent stops reading from the network.
-
-  On output, the user write callback is invoked whenever the buffered data
-  falls below the low watermark.
-
-  @param bufev the bufferevent to be modified
-  @param events EV_READ, EV_WRITE or both
-  @param lowmark the lower watermark to set
-  @param highmark the high watermark to set
-*/
-
-void bufferevent_setwatermark(struct bufferevent *bufev, short events,
-    size_t lowmark, size_t highmark);
-
-#define EVBUFFER_LENGTH(x)	(x)->off
-#define EVBUFFER_DATA(x)	(x)->buffer
-#define EVBUFFER_INPUT(x)	(x)->input
-#define EVBUFFER_OUTPUT(x)	(x)->output
-
-
-/**
-  Allocate storage for a new evbuffer.
-
-  @return a pointer to a newly allocated evbuffer struct, or NULL if an error
-          occurred
- */
-struct evbuffer *evbuffer_new(void);
-
-
-/**
-  Deallocate storage for an evbuffer.
-
-  @param pointer to the evbuffer to be freed
- */
-void evbuffer_free(struct evbuffer *);
-
-
-/**
-  Expands the available space in an event buffer.
-
-  Expands the available space in the event buffer to at least datlen
-
-  @param buf the event buffer to be expanded
-  @param datlen the new minimum length requirement
-  @return 0 if successful, or -1 if an error occurred
-*/
-int evbuffer_expand(struct evbuffer *, size_t);
-
-
-/**
-  Append data to the end of an evbuffer.
-
-  @param buf the event buffer to be appended to
-  @param data pointer to the beginning of the data buffer
-  @param datlen the number of bytes to be copied from the data buffer
- */
-int evbuffer_add(struct evbuffer *, const void *, size_t);
-
-
-
-/**
-  Read data from an event buffer and drain the bytes read.
-
-  @param buf the event buffer to be read from
-  @param data the destination buffer to store the result
-  @param datlen the maximum size of the destination buffer
-  @return the number of bytes read
- */
-int evbuffer_remove(struct evbuffer *, void *, size_t);
-
-
-/**
- * Read a single line from an event buffer.
- *
- * Reads a line terminated by either '\r\n', '\n\r' or '\r' or '\n'.
- * The returned buffer needs to be freed by the caller.
- *
- * @param buffer the evbuffer to read from
- * @return pointer to a single line, or NULL if an error occurred
- */
-char *evbuffer_readline(struct evbuffer *);
-
-
-/** Used to tell evbuffer_readln what kind of line-ending to look for.
- */
-enum evbuffer_eol_style {
-	/** Any sequence of CR and LF characters is acceptable as an EOL. */
-	EVBUFFER_EOL_ANY,
-	/** An EOL is an LF, optionally preceded by a CR.  This style is
-	 * most useful for implementing text-based internet protocols. */
-	EVBUFFER_EOL_CRLF,
-	/** An EOL is a CR followed by an LF. */
-	EVBUFFER_EOL_CRLF_STRICT,
-	/** An EOL is a LF. */
-        EVBUFFER_EOL_LF
-};
-
-/**
- * Read a single line from an event buffer.
- *
- * Reads a line terminated by an EOL as determined by the evbuffer_eol_style
- * argument.  Returns a newly allocated nul-terminated string; the caller must
- * free the returned value.  The EOL is not included in the returned string.
- *
- * @param buffer the evbuffer to read from
- * @param n_read_out if non-NULL, points to a size_t that is set to the
- *       number of characters in the returned string.  This is useful for
- *       strings that can contain NUL characters.
- * @param eol_style the style of line-ending to use.
- * @return pointer to a single line, or NULL if an error occurred
- */
-char *evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
-    enum evbuffer_eol_style eol_style);
-
-
-/**
-  Move data from one evbuffer into another evbuffer.
-
-  This is a destructive add.  The data from one buffer moves into
-  the other buffer. The destination buffer is expanded as needed.
-
-  @param outbuf the output buffer
-  @param inbuf the input buffer
-  @return 0 if successful, or -1 if an error occurred
- */
-int evbuffer_add_buffer(struct evbuffer *, struct evbuffer *);
-
-
-/**
-  Append a formatted string to the end of an evbuffer.
-
-  @param buf the evbuffer that will be appended to
-  @param fmt a format string
-  @param ... arguments that will be passed to printf(3)
-  @return The number of bytes added if successful, or -1 if an error occurred.
- */
-int evbuffer_add_printf(struct evbuffer *, const char *fmt, ...)
-#ifdef __GNUC__
-  __attribute__((format(printf, 2, 3)))
-#endif
-;
-
-
-/**
-  Append a va_list formatted string to the end of an evbuffer.
-
-  @param buf the evbuffer that will be appended to
-  @param fmt a format string
-  @param ap a varargs va_list argument array that will be passed to vprintf(3)
-  @return The number of bytes added if successful, or -1 if an error occurred.
- */
-int evbuffer_add_vprintf(struct evbuffer *, const char *fmt, va_list ap);
-
-
-/**
-  Remove a specified number of bytes data from the beginning of an evbuffer.
-
-  @param buf the evbuffer to be drained
-  @param len the number of bytes to drain from the beginning of the buffer
- */
-void evbuffer_drain(struct evbuffer *, size_t);
-
-
-/**
-  Write the contents of an evbuffer to a file descriptor.
-
-  The evbuffer will be drained after the bytes have been successfully written.
-
-  @param buffer the evbuffer to be written and drained
-  @param fd the file descriptor to be written to
-  @return the number of bytes written, or -1 if an error occurred
-  @see evbuffer_read()
- */
-int evbuffer_write(struct evbuffer *, int);
-
-
-/**
-  Read from a file descriptor and store the result in an evbuffer.
-
-  @param buf the evbuffer to store the result
-  @param fd the file descriptor to read from
-  @param howmuch the number of bytes to be read
-  @return the number of bytes read, or -1 if an error occurred
-  @see evbuffer_write()
- */
-int evbuffer_read(struct evbuffer *, int, int);
-
-
-/**
-  Find a string within an evbuffer.
-
-  @param buffer the evbuffer to be searched
-  @param what the string to be searched for
-  @param len the length of the search string
-  @return a pointer to the beginning of the search string, or NULL if the search failed.
- */
-u_char *evbuffer_find(struct evbuffer *, const u_char *, size_t);
-
-/**
-  Set a callback to invoke when the evbuffer is modified.
-
-  @param buffer the evbuffer to be monitored
-  @param cb the callback function to invoke when the evbuffer is modified
-  @param cbarg an argument to be provided to the callback function
- */
-void evbuffer_setcb(struct evbuffer *, void (*)(struct evbuffer *, size_t, size_t, void *), void *);
-
-/*
- * Marshaling tagged data - We assume that all tags are inserted in their
- * numeric order - so that unknown tags will always be higher than the
- * known ones - and we can just ignore the end of an event buffer.
- */
-
-void evtag_init(void);
-
-void evtag_marshal(struct evbuffer *evbuf, ev_uint32_t tag, const void *data,
-    ev_uint32_t len);
-
-/**
-  Encode an integer and store it in an evbuffer.
-
-  We encode integer's by nibbles; the first nibble contains the number
-  of significant nibbles - 1;  this allows us to encode up to 64-bit
-  integers.  This function is byte-order independent.
-
-  @param evbuf evbuffer to store the encoded number
-  @param number a 32-bit integer
- */
-void encode_int(struct evbuffer *evbuf, ev_uint32_t number);
-
-void evtag_marshal_int(struct evbuffer *evbuf, ev_uint32_t tag,
-    ev_uint32_t integer);
-
-void evtag_marshal_string(struct evbuffer *buf, ev_uint32_t tag,
-    const char *string);
-
-void evtag_marshal_timeval(struct evbuffer *evbuf, ev_uint32_t tag,
-    struct timeval *tv);
-
-int evtag_unmarshal(struct evbuffer *src, ev_uint32_t *ptag,
-    struct evbuffer *dst);
-int evtag_peek(struct evbuffer *evbuf, ev_uint32_t *ptag);
-int evtag_peek_length(struct evbuffer *evbuf, ev_uint32_t *plength);
-int evtag_payload_length(struct evbuffer *evbuf, ev_uint32_t *plength);
-int evtag_consume(struct evbuffer *evbuf);
-
-int evtag_unmarshal_int(struct evbuffer *evbuf, ev_uint32_t need_tag,
-    ev_uint32_t *pinteger);
-
-int evtag_unmarshal_fixed(struct evbuffer *src, ev_uint32_t need_tag,
-    void *data, size_t len);
-
-int evtag_unmarshal_string(struct evbuffer *evbuf, ev_uint32_t need_tag,
-    char **pstring);
-
-int evtag_unmarshal_timeval(struct evbuffer *evbuf, ev_uint32_t need_tag,
-    struct timeval *ptv);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _EVENT_H_ */
diff --git a/base/third_party/libevent/event_rpcgen.py b/base/third_party/libevent/event_rpcgen.py
deleted file mode 100755
index 4ec77a6..0000000
--- a/base/third_party/libevent/event_rpcgen.py
+++ /dev/null
@@ -1,1423 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright (c) 2005 Niels Provos <provos@citi.umich.edu>
-# All rights reserved.
-#
-# Generates marshaling code based on libevent.
-
-import sys
-import re
-
-#
-_NAME = "event_rpcgen.py"
-_VERSION = "0.1"
-_STRUCT_RE = '[a-z][a-z_0-9]*'
-
-# Globals
-line_count = 0
-
-white = re.compile(r'^\s+')
-cppcomment = re.compile(r'\/\/.*$')
-headerdirect = []
-cppdirect = []
-
-# Holds everything that makes a struct
-class Struct:
-    def __init__(self, name):
-        self._name = name
-        self._entries = []
-        self._tags = {}
-        print >>sys.stderr, '  Created struct: %s' % name
-
-    def AddEntry(self, entry):
-        if self._tags.has_key(entry.Tag()):
-            print >>sys.stderr, ( 'Entry "%s" duplicates tag number '
-                                  '%d from "%s" around line %d' ) % (
-                entry.Name(), entry.Tag(),
-                self._tags[entry.Tag()], line_count)
-            sys.exit(1)
-        self._entries.append(entry)
-        self._tags[entry.Tag()] = entry.Name()
-        print >>sys.stderr, '    Added entry: %s' % entry.Name()
-
-    def Name(self):
-        return self._name
-
-    def EntryTagName(self, entry):
-        """Creates the name inside an enumeration for distinguishing data
-        types."""
-        name = "%s_%s" % (self._name, entry.Name())
-        return name.upper()
-
-    def PrintIdented(self, file, ident, code):
-        """Takes an array, add indentation to each entry and prints it."""
-        for entry in code:
-            print >>file, '%s%s' % (ident, entry)
-
-    def PrintTags(self, file):
-        """Prints the tag definitions for a structure."""
-        print >>file, '/* Tag definition for %s */' % self._name
-        print >>file, 'enum %s_ {' % self._name.lower()
-        for entry in self._entries:
-            print >>file, '  %s=%d,' % (self.EntryTagName(entry),
-                                        entry.Tag())
-        print >>file, '  %s_MAX_TAGS' % (self._name.upper())
-        print >>file, '};\n'
-
-    def PrintForwardDeclaration(self, file):
-        print >>file, 'struct %s;' % self._name
-
-    def PrintDeclaration(self, file):
-        print >>file, '/* Structure declaration for %s */' % self._name
-        print >>file, 'struct %s_access_ {' % self._name
-        for entry in self._entries:
-            dcl = entry.AssignDeclaration('(*%s_assign)' % entry.Name())
-            dcl.extend(
-                entry.GetDeclaration('(*%s_get)' % entry.Name()))
-            if entry.Array():
-                dcl.extend(
-                    entry.AddDeclaration('(*%s_add)' % entry.Name()))
-            self.PrintIdented(file, '  ', dcl)
-        print >>file, '};\n'
-
-        print >>file, 'struct %s {' % self._name
-        print >>file, '  struct %s_access_ *base;\n' % self._name
-        for entry in self._entries:
-            dcl = entry.Declaration()
-            self.PrintIdented(file, '  ', dcl)
-        print >>file, ''
-        for entry in self._entries:
-            print >>file, '  ev_uint8_t %s_set;' % entry.Name()
-        print >>file, '};\n'
-
-        print >>file, \
-"""struct %(name)s *%(name)s_new(void);
-void %(name)s_free(struct %(name)s *);
-void %(name)s_clear(struct %(name)s *);
-void %(name)s_marshal(struct evbuffer *, const struct %(name)s *);
-int %(name)s_unmarshal(struct %(name)s *, struct evbuffer *);
-int %(name)s_complete(struct %(name)s *);
-void evtag_marshal_%(name)s(struct evbuffer *, ev_uint32_t, 
-    const struct %(name)s *);
-int evtag_unmarshal_%(name)s(struct evbuffer *, ev_uint32_t,
-    struct %(name)s *);""" % { 'name' : self._name }
-
-
-        # Write a setting function of every variable
-        for entry in self._entries:
-            self.PrintIdented(file, '', entry.AssignDeclaration(
-                entry.AssignFuncName()))
-            self.PrintIdented(file, '', entry.GetDeclaration(
-                entry.GetFuncName()))
-            if entry.Array():
-                self.PrintIdented(file, '', entry.AddDeclaration(
-                    entry.AddFuncName()))
-
-        print >>file, '/* --- %s done --- */\n' % self._name
-
-    def PrintCode(self, file):
-        print >>file, ('/*\n'
-                       ' * Implementation of %s\n'
-                       ' */\n') % self._name
-
-        print >>file, \
-              'static struct %(name)s_access_ __%(name)s_base = {' % \
-              { 'name' : self._name }
-        for entry in self._entries:
-            self.PrintIdented(file, '  ', entry.CodeBase())
-        print >>file, '};\n'
-
-        # Creation
-        print >>file, (
-            'struct %(name)s *\n'
-            '%(name)s_new(void)\n'
-            '{\n'
-            '  struct %(name)s *tmp;\n'
-            '  if ((tmp = malloc(sizeof(struct %(name)s))) == NULL) {\n'
-            '    event_warn("%%s: malloc", __func__);\n'
-            '    return (NULL);\n'
-            '  }\n'
-            '  tmp->base = &__%(name)s_base;\n') % { 'name' : self._name }
-
-        for entry in self._entries:
-            self.PrintIdented(file, '  ', entry.CodeNew('tmp'))
-            print >>file, '  tmp->%s_set = 0;\n' % entry.Name()
-
-        print >>file, (
-            '  return (tmp);\n'
-            '}\n')
-
-        # Adding
-        for entry in self._entries:
-            if entry.Array():
-                self.PrintIdented(file, '', entry.CodeAdd())
-            print >>file, ''
-            
-        # Assigning
-        for entry in self._entries:
-            self.PrintIdented(file, '', entry.CodeAssign())
-            print >>file, ''
-
-        # Getting
-        for entry in self._entries:
-            self.PrintIdented(file, '', entry.CodeGet())
-            print >>file, ''
-            
-        # Clearing
-        print >>file, ( 'void\n'
-                        '%(name)s_clear(struct %(name)s *tmp)\n'
-                        '{'
-                        ) % { 'name' : self._name }
-        for entry in self._entries:
-            self.PrintIdented(file, '  ', entry.CodeClear('tmp'))
-
-        print >>file, '}\n'
-
-        # Freeing
-        print >>file, ( 'void\n'
-                        '%(name)s_free(struct %(name)s *tmp)\n'
-                        '{'
-                        ) % { 'name' : self._name }
-        
-        for entry in self._entries:
-            self.PrintIdented(file, '  ', entry.CodeFree('tmp'))
-
-        print >>file, ('  free(tmp);\n'
-                       '}\n')
-
-        # Marshaling
-        print >>file, ('void\n'
-                       '%(name)s_marshal(struct evbuffer *evbuf, '
-                       'const struct %(name)s *tmp)'
-                       '{') % { 'name' : self._name }
-        for entry in self._entries:
-            indent = '  '
-            # Optional entries do not have to be set
-            if entry.Optional():
-                indent += '  '
-                print >>file, '  if (tmp->%s_set) {' % entry.Name()
-            self.PrintIdented(
-                file, indent,
-                entry.CodeMarshal('evbuf', self.EntryTagName(entry), 'tmp'))
-            if entry.Optional():
-                print >>file, '  }'
-
-        print >>file, '}\n'
-                       
-        # Unmarshaling
-        print >>file, ('int\n'
-                       '%(name)s_unmarshal(struct %(name)s *tmp, '
-                       ' struct evbuffer *evbuf)\n'
-                       '{\n'
-                       '  ev_uint32_t tag;\n'
-                       '  while (EVBUFFER_LENGTH(evbuf) > 0) {\n'
-                       '    if (evtag_peek(evbuf, &tag) == -1)\n'
-                       '      return (-1);\n'
-                       '    switch (tag) {\n'
-                       ) % { 'name' : self._name }
-        for entry in self._entries:
-            print >>file, '      case %s:\n' % self.EntryTagName(entry)
-            if not entry.Array():
-                print >>file, (
-                    '        if (tmp->%s_set)\n'
-                    '          return (-1);'
-                    ) % (entry.Name())
-
-            self.PrintIdented(
-                file, '        ',
-                entry.CodeUnmarshal('evbuf',
-                                    self.EntryTagName(entry), 'tmp'))
-
-            print >>file, ( '        tmp->%s_set = 1;\n' % entry.Name() +
-                            '        break;\n' )
-        print >>file, ( '      default:\n'
-                        '        return -1;\n'
-                        '    }\n'
-                        '  }\n' )
-        # Check if it was decoded completely
-        print >>file, ( '  if (%(name)s_complete(tmp) == -1)\n'
-                        '    return (-1);'
-                        ) % { 'name' : self._name }
-
-        # Successfully decoded
-        print >>file, ( '  return (0);\n'
-                        '}\n')
-
-        # Checking if a structure has all the required data
-        print >>file, (
-            'int\n'
-            '%(name)s_complete(struct %(name)s *msg)\n'
-            '{' ) % { 'name' : self._name }
-        for entry in self._entries:
-            self.PrintIdented(
-                file, '  ',
-                entry.CodeComplete('msg'))
-        print >>file, (
-            '  return (0);\n'
-            '}\n' )
-
-        # Complete message unmarshaling
-        print >>file, (
-            'int\n'
-            'evtag_unmarshal_%(name)s(struct evbuffer *evbuf, '
-            'ev_uint32_t need_tag, struct %(name)s *msg)\n'
-            '{\n'
-            '  ev_uint32_t tag;\n'
-            '  int res = -1;\n'
-            '\n'
-            '  struct evbuffer *tmp = evbuffer_new();\n'
-            '\n'
-            '  if (evtag_unmarshal(evbuf, &tag, tmp) == -1'
-            ' || tag != need_tag)\n'
-            '    goto error;\n'
-            '\n'
-            '  if (%(name)s_unmarshal(msg, tmp) == -1)\n'
-            '    goto error;\n'
-            '\n'
-            '  res = 0;\n'
-            '\n'
-            ' error:\n'
-            '  evbuffer_free(tmp);\n'
-            '  return (res);\n'
-            '}\n' ) % { 'name' : self._name }
-
-        # Complete message marshaling
-        print >>file, (
-            'void\n'
-            'evtag_marshal_%(name)s(struct evbuffer *evbuf, ev_uint32_t tag, '
-            'const struct %(name)s *msg)\n'
-            '{\n'
-            '  struct evbuffer *_buf = evbuffer_new();\n'
-            '  assert(_buf != NULL);\n'
-            '  evbuffer_drain(_buf, -1);\n'
-            '  %(name)s_marshal(_buf, msg);\n'
-            '  evtag_marshal(evbuf, tag, EVBUFFER_DATA(_buf), '
-            'EVBUFFER_LENGTH(_buf));\n'
-            '  evbuffer_free(_buf);\n'
-            '}\n' ) % { 'name' : self._name }
-
-class Entry:
-    def __init__(self, type, name, tag):
-        self._type = type
-        self._name = name
-        self._tag = int(tag)
-        self._ctype = type
-        self._optional = 0
-        self._can_be_array = 0
-        self._array = 0
-        self._line_count = -1
-        self._struct = None
-        self._refname = None
-
-    def GetTranslation(self):
-        return { "parent_name" : self._struct.Name(),
-                 "name" : self._name,
-                 "ctype" : self._ctype,
-                 "refname" : self._refname
-                 }
-    
-    def SetStruct(self, struct):
-        self._struct = struct
-
-    def LineCount(self):
-        assert self._line_count != -1
-        return self._line_count
-
-    def SetLineCount(self, number):
-        self._line_count = number
-
-    def Array(self):
-        return self._array
-
-    def Optional(self):
-        return self._optional
-
-    def Tag(self):
-        return self._tag
-
-    def Name(self):
-        return self._name
-
-    def Type(self):
-        return self._type
-
-    def MakeArray(self, yes=1):
-        self._array = yes
-        
-    def MakeOptional(self):
-        self._optional = 1
-
-    def GetFuncName(self):
-        return '%s_%s_get' % (self._struct.Name(), self._name)
-    
-    def GetDeclaration(self, funcname):
-        code = [ 'int %s(struct %s *, %s *);' % (
-            funcname, self._struct.Name(), self._ctype ) ]
-        return code
-
-    def CodeGet(self):
-        code = (
-            'int',
-            '%(parent_name)s_%(name)s_get(struct %(parent_name)s *msg, '
-            '%(ctype)s *value)',
-            '{',
-            '  if (msg->%(name)s_set != 1)',
-            '    return (-1);',
-            '  *value = msg->%(name)s_data;',
-            '  return (0);',
-            '}' )
-        code = '\n'.join(code)
-        code = code % self.GetTranslation()
-        return code.split('\n')
-        
-    def AssignFuncName(self):
-        return '%s_%s_assign' % (self._struct.Name(), self._name)
-    
-    def AddFuncName(self):
-        return '%s_%s_add' % (self._struct.Name(), self._name)
-    
-    def AssignDeclaration(self, funcname):
-        code = [ 'int %s(struct %s *, const %s);' % (
-            funcname, self._struct.Name(), self._ctype ) ]
-        return code
-
-    def CodeAssign(self):
-        code = [ 'int',
-                 '%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,'
-                 ' const %(ctype)s value)',
-                 '{',
-                 '  msg->%(name)s_set = 1;',
-                 '  msg->%(name)s_data = value;',
-                 '  return (0);',
-                 '}' ]
-        code = '\n'.join(code)
-        code = code % self.GetTranslation()
-        return code.split('\n')
-
-    def CodeClear(self, structname):
-        code = [ '%s->%s_set = 0;' % (structname, self.Name()) ]
-
-        return code
-        
-    def CodeComplete(self, structname):
-        if self.Optional():
-            return []
-        
-        code = [ 'if (!%s->%s_set)' % (structname, self.Name()),
-                 '  return (-1);' ]
-
-        return code
-
-    def CodeFree(self, name):
-        return []
-
-    def CodeBase(self):
-        code = [
-            '%(parent_name)s_%(name)s_assign,',
-            '%(parent_name)s_%(name)s_get,'
-            ]
-        if self.Array():
-            code.append('%(parent_name)s_%(name)s_add,')
-
-        code = '\n'.join(code)
-        code = code % self.GetTranslation()
-        return code.split('\n')
-
-    def Verify(self):
-        if self.Array() and not self._can_be_array:
-            print >>sys.stderr, (
-                'Entry "%s" cannot be created as an array '
-                'around line %d' ) % (self._name, self.LineCount())
-            sys.exit(1)
-        if not self._struct:
-            print >>sys.stderr, (
-                'Entry "%s" does not know which struct it belongs to '
-                'around line %d' ) % (self._name, self.LineCount())
-            sys.exit(1)
-        if self._optional and self._array:
-            print >>sys.stderr,  ( 'Entry "%s" has illegal combination of '
-                                   'optional and array around line %d' ) % (
-                self._name, self.LineCount() )
-            sys.exit(1)
-
-class EntryBytes(Entry):
-    def __init__(self, type, name, tag, length):
-        # Init base class
-        Entry.__init__(self, type, name, tag)
-
-        self._length = length
-        self._ctype = 'ev_uint8_t'
-
-    def GetDeclaration(self, funcname):
-        code = [ 'int %s(struct %s *, %s **);' % (
-            funcname, self._struct.Name(), self._ctype ) ]
-        return code
-        
-    def AssignDeclaration(self, funcname):
-        code = [ 'int %s(struct %s *, const %s *);' % (
-            funcname, self._struct.Name(), self._ctype ) ]
-        return code
-        
-    def Declaration(self):
-        dcl  = ['ev_uint8_t %s_data[%s];' % (self._name, self._length)]
-        
-        return dcl
-
-    def CodeGet(self):
-        name = self._name
-        code = [ 'int',
-                 '%s_%s_get(struct %s *msg, %s **value)' % (
-            self._struct.Name(), name,
-            self._struct.Name(), self._ctype),
-                 '{',
-                 '  if (msg->%s_set != 1)' % name,
-                 '    return (-1);',
-                 '  *value = msg->%s_data;' % name,
-                 '  return (0);',
-                 '}' ]
-        return code
-        
-    def CodeAssign(self):
-        name = self._name
-        code = [ 'int',
-                 '%s_%s_assign(struct %s *msg, const %s *value)' % (
-            self._struct.Name(), name,
-            self._struct.Name(), self._ctype),
-                 '{',
-                 '  msg->%s_set = 1;' % name,
-                 '  memcpy(msg->%s_data, value, %s);' % (
-            name, self._length),
-                 '  return (0);',
-                 '}' ]
-        return code
-        
-    def CodeUnmarshal(self, buf, tag_name, var_name):
-        code = [  'if (evtag_unmarshal_fixed(%s, %s, ' % (buf, tag_name) +
-                  '%s->%s_data, ' % (var_name, self._name) +
-                  'sizeof(%s->%s_data)) == -1) {' % (
-            var_name, self._name),
-                  '  event_warnx("%%s: failed to unmarshal %s", __func__);' % (
-            self._name ),
-                  '  return (-1);',
-                  '}'
-                  ]
-        return code
-
-    def CodeMarshal(self, buf, tag_name, var_name):
-        code = ['evtag_marshal(%s, %s, %s->%s_data, sizeof(%s->%s_data));' % (
-            buf, tag_name, var_name, self._name, var_name, self._name )]
-        return code
-
-    def CodeClear(self, structname):
-        code = [ '%s->%s_set = 0;' % (structname, self.Name()),
-                 'memset(%s->%s_data, 0, sizeof(%s->%s_data));' % (
-            structname, self._name, structname, self._name)]
-
-        return code
-        
-    def CodeNew(self, name):
-        code  = ['memset(%s->%s_data, 0, sizeof(%s->%s_data));' % (
-            name, self._name, name, self._name)]
-        return code
-
-    def Verify(self):
-        if not self._length:
-            print >>sys.stderr, 'Entry "%s" needs a length around line %d' % (
-                self._name, self.LineCount() )
-            sys.exit(1)
-
-        Entry.Verify(self)
-
-class EntryInt(Entry):
-    def __init__(self, type, name, tag):
-        # Init base class
-        Entry.__init__(self, type, name, tag)
-
-        self._ctype = 'ev_uint32_t'
-
-    def CodeUnmarshal(self, buf, tag_name, var_name):
-        code = ['if (evtag_unmarshal_int(%s, %s, &%s->%s_data) == -1) {' % (
-            buf, tag_name, var_name, self._name),
-                  '  event_warnx("%%s: failed to unmarshal %s", __func__);' % (
-            self._name ),
-                '  return (-1);',
-                '}' ] 
-        return code
-
-    def CodeMarshal(self, buf, tag_name, var_name):
-        code = ['evtag_marshal_int(%s, %s, %s->%s_data);' % (
-            buf, tag_name, var_name, self._name)]
-        return code
-
-    def Declaration(self):
-        dcl  = ['ev_uint32_t %s_data;' % self._name]
-
-        return dcl
-
-    def CodeNew(self, name):
-        code = ['%s->%s_data = 0;' % (name, self._name)]
-        return code
-
-class EntryString(Entry):
-    def __init__(self, type, name, tag):
-        # Init base class
-        Entry.__init__(self, type, name, tag)
-
-        self._ctype = 'char *'
-
-    def CodeAssign(self):
-        name = self._name
-        code = """int
-%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,
-    const %(ctype)s value)
-{
-  if (msg->%(name)s_data != NULL)
-    free(msg->%(name)s_data);
-  if ((msg->%(name)s_data = strdup(value)) == NULL)
-    return (-1);
-  msg->%(name)s_set = 1;
-  return (0);
-}""" % self.GetTranslation()
-
-        return code.split('\n')
-        
-    def CodeUnmarshal(self, buf, tag_name, var_name):
-        code = ['if (evtag_unmarshal_string(%s, %s, &%s->%s_data) == -1) {' % (
-            buf, tag_name, var_name, self._name),
-                '  event_warnx("%%s: failed to unmarshal %s", __func__);' % (
-            self._name ),
-                '  return (-1);',
-                '}'
-                ]
-        return code
-
-    def CodeMarshal(self, buf, tag_name, var_name):
-        code = ['evtag_marshal_string(%s, %s, %s->%s_data);' % (
-            buf, tag_name, var_name, self._name)]
-        return code
-
-    def CodeClear(self, structname):
-        code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
-                 '  free (%s->%s_data);' % (structname, self.Name()),
-                 '  %s->%s_data = NULL;' % (structname, self.Name()),
-                 '  %s->%s_set = 0;' % (structname, self.Name()),
-                 '}'
-                 ]
-
-        return code
-        
-    def CodeNew(self, name):
-        code  = ['%s->%s_data = NULL;' % (name, self._name)]
-        return code
-
-    def CodeFree(self, name):
-        code  = ['if (%s->%s_data != NULL)' % (name, self._name),
-                 '    free (%s->%s_data); ' % (name, self._name)]
-
-        return code
-
-    def Declaration(self):
-        dcl  = ['char *%s_data;' % self._name]
-
-        return dcl
-
-class EntryStruct(Entry):
-    def __init__(self, type, name, tag, refname):
-        # Init base class
-        Entry.__init__(self, type, name, tag)
-
-        self._can_be_array = 1
-        self._refname = refname
-        self._ctype = 'struct %s*' % refname
-
-    def CodeGet(self):
-        name = self._name
-        code = [ 'int',
-                 '%s_%s_get(struct %s *msg, %s *value)' % (
-            self._struct.Name(), name,
-            self._struct.Name(), self._ctype),
-                 '{',
-                 '  if (msg->%s_set != 1) {' % name,
-                 '    msg->%s_data = %s_new();' % (name, self._refname),
-                 '    if (msg->%s_data == NULL)' % name,
-                 '      return (-1);',
-                 '    msg->%s_set = 1;' % name,
-                 '  }',
-                 '  *value = msg->%s_data;' % name,
-                 '  return (0);',
-                 '}' ]
-        return code
-        
-    def CodeAssign(self):
-        name = self._name
-        code = """int
-%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,
-    const %(ctype)s value)
-{
-   struct evbuffer *tmp = NULL;
-   if (msg->%(name)s_set) {
-     %(refname)s_clear(msg->%(name)s_data);
-     msg->%(name)s_set = 0;
-   } else {
-     msg->%(name)s_data = %(refname)s_new();
-     if (msg->%(name)s_data == NULL) {
-       event_warn("%%s: %(refname)s_new()", __func__);
-       goto error;
-     }
-   }
-   if ((tmp = evbuffer_new()) == NULL) {
-     event_warn("%%s: evbuffer_new()", __func__);
-     goto error;
-   }
-   %(refname)s_marshal(tmp, value);
-   if (%(refname)s_unmarshal(msg->%(name)s_data, tmp) == -1) {
-     event_warnx("%%s: %(refname)s_unmarshal", __func__);
-     goto error;
-   }
-   msg->%(name)s_set = 1;
-   evbuffer_free(tmp);
-   return (0);
- error:
-   if (tmp != NULL)
-     evbuffer_free(tmp);
-   if (msg->%(name)s_data != NULL) {
-     %(refname)s_free(msg->%(name)s_data);
-     msg->%(name)s_data = NULL;
-   }
-   return (-1);
-}""" % self.GetTranslation()
-        return code.split('\n')
-        
-    def CodeComplete(self, structname):
-        if self.Optional():
-            code = [ 'if (%s->%s_set && %s_complete(%s->%s_data) == -1)' % (
-                structname, self.Name(),
-                self._refname, structname, self.Name()),
-                     '  return (-1);' ]
-        else:
-            code = [ 'if (%s_complete(%s->%s_data) == -1)' % (
-                self._refname, structname, self.Name()),
-                     '  return (-1);' ]
-
-        return code
-    
-    def CodeUnmarshal(self, buf, tag_name, var_name):
-        code = ['%s->%s_data = %s_new();' % (
-            var_name, self._name, self._refname),
-                'if (%s->%s_data == NULL)' % (var_name, self._name),
-                '  return (-1);',
-                'if (evtag_unmarshal_%s(%s, %s, %s->%s_data) == -1) {' % (
-            self._refname, buf, tag_name, var_name, self._name),
-                  '  event_warnx("%%s: failed to unmarshal %s", __func__);' % (
-            self._name ),
-                '  return (-1);',
-                '}'
-                ]
-        return code
-
-    def CodeMarshal(self, buf, tag_name, var_name):
-        code = ['evtag_marshal_%s(%s, %s, %s->%s_data);' % (
-            self._refname, buf, tag_name, var_name, self._name)]
-        return code
-
-    def CodeClear(self, structname):
-        code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
-                 '  %s_free(%s->%s_data);' % (
-            self._refname, structname, self.Name()),
-                 '  %s->%s_data = NULL;' % (structname, self.Name()),
-                 '  %s->%s_set = 0;' % (structname, self.Name()),
-                 '}'
-                 ]
-
-        return code
-        
-    def CodeNew(self, name):
-        code  = ['%s->%s_data = NULL;' % (name, self._name)]
-        return code
-
-    def CodeFree(self, name):
-        code  = ['if (%s->%s_data != NULL)' % (name, self._name),
-                 '    %s_free(%s->%s_data); ' % (
-            self._refname, name, self._name)]
-
-        return code
-
-    def Declaration(self):
-        dcl  = ['%s %s_data;' % (self._ctype, self._name)]
-
-        return dcl
-
-class EntryVarBytes(Entry):
-    def __init__(self, type, name, tag):
-        # Init base class
-        Entry.__init__(self, type, name, tag)
-
-        self._ctype = 'ev_uint8_t *'
-
-    def GetDeclaration(self, funcname):
-        code = [ 'int %s(struct %s *, %s *, ev_uint32_t *);' % (
-            funcname, self._struct.Name(), self._ctype ) ]
-        return code
-        
-    def AssignDeclaration(self, funcname):
-        code = [ 'int %s(struct %s *, const %s, ev_uint32_t);' % (
-            funcname, self._struct.Name(), self._ctype ) ]
-        return code
-        
-    def CodeAssign(self):
-        name = self._name
-        code = [ 'int',
-                 '%s_%s_assign(struct %s *msg, '
-                 'const %s value, ev_uint32_t len)' % (
-            self._struct.Name(), name,
-            self._struct.Name(), self._ctype),
-                 '{',
-                 '  if (msg->%s_data != NULL)' % name,
-                 '    free (msg->%s_data);' % name,
-                 '  msg->%s_data = malloc(len);' % name,
-                 '  if (msg->%s_data == NULL)' % name,
-                 '    return (-1);',
-                 '  msg->%s_set = 1;' % name,
-                 '  msg->%s_length = len;' % name,
-                 '  memcpy(msg->%s_data, value, len);' % name,
-                 '  return (0);',
-                 '}' ]
-        return code
-        
-    def CodeGet(self):
-        name = self._name
-        code = [ 'int',
-                 '%s_%s_get(struct %s *msg, %s *value, ev_uint32_t *plen)' % (
-            self._struct.Name(), name,
-            self._struct.Name(), self._ctype),
-                 '{',
-                 '  if (msg->%s_set != 1)' % name,
-                 '    return (-1);',
-                 '  *value = msg->%s_data;' % name,
-                 '  *plen = msg->%s_length;' % name,
-                 '  return (0);',
-                 '}' ]
-        return code
-
-    def CodeUnmarshal(self, buf, tag_name, var_name):
-        code = ['if (evtag_payload_length(%s, &%s->%s_length) == -1)' % (
-            buf, var_name, self._name),
-                '  return (-1);',
-                # We do not want DoS opportunities
-                'if (%s->%s_length > EVBUFFER_LENGTH(%s))' % (
-            var_name, self._name, buf),
-                '  return (-1);',
-                'if ((%s->%s_data = malloc(%s->%s_length)) == NULL)' % (
-            var_name, self._name, var_name, self._name),
-                '  return (-1);',
-                'if (evtag_unmarshal_fixed(%s, %s, %s->%s_data, '
-                '%s->%s_length) == -1) {' % (
-            buf, tag_name, var_name, self._name, var_name, self._name),
-                '  event_warnx("%%s: failed to unmarshal %s", __func__);' % (
-            self._name ),
-                '  return (-1);',
-                '}'
-                ]
-        return code
-
-    def CodeMarshal(self, buf, tag_name, var_name):
-        code = ['evtag_marshal(%s, %s, %s->%s_data, %s->%s_length);' % (
-            buf, tag_name, var_name, self._name, var_name, self._name)]
-        return code
-
-    def CodeClear(self, structname):
-        code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
-                 '  free (%s->%s_data);' % (structname, self.Name()),
-                 '  %s->%s_data = NULL;' % (structname, self.Name()),
-                 '  %s->%s_length = 0;' % (structname, self.Name()),
-                 '  %s->%s_set = 0;' % (structname, self.Name()),
-                 '}'
-                 ]
-
-        return code
-        
-    def CodeNew(self, name):
-        code  = ['%s->%s_data = NULL;' % (name, self._name),
-                 '%s->%s_length = 0;' % (name, self._name) ]
-        return code
-
-    def CodeFree(self, name):
-        code  = ['if (%s->%s_data != NULL)' % (name, self._name),
-                 '    free (%s->%s_data); ' % (name, self._name)]
-
-        return code
-
-    def Declaration(self):
-        dcl  = ['ev_uint8_t *%s_data;' % self._name,
-                'ev_uint32_t %s_length;' % self._name]
-
-        return dcl
-
-class EntryArray(Entry):
-    def __init__(self, entry):
-        # Init base class
-        Entry.__init__(self, entry._type, entry._name, entry._tag)
-
-        self._entry = entry
-        self._refname = entry._refname
-        self._ctype = 'struct %s *' % self._refname
-
-    def GetDeclaration(self, funcname):
-        """Allows direct access to elements of the array."""
-        translate = self.GetTranslation()
-        translate["funcname"] = funcname
-        code = [
-            'int %(funcname)s(struct %(parent_name)s *, int, %(ctype)s *);' %
-            translate ]
-        return code
-        
-    def AssignDeclaration(self, funcname):
-        code = [ 'int %s(struct %s *, int, const %s);' % (
-            funcname, self._struct.Name(), self._ctype ) ]
-        return code
-        
-    def AddDeclaration(self, funcname):
-        code = [ '%s %s(struct %s *);' % (
-            self._ctype, funcname, self._struct.Name() ) ]
-        return code
-        
-    def CodeGet(self):
-        code = """int
-%(parent_name)s_%(name)s_get(struct %(parent_name)s *msg, int offset,
-    %(ctype)s *value)
-{
-  if (!msg->%(name)s_set || offset < 0 || offset >= msg->%(name)s_length)
-    return (-1);
-  *value = msg->%(name)s_data[offset];
-  return (0);
-}""" % self.GetTranslation()
-
-        return code.split('\n')
-        
-    def CodeAssign(self):
-        code = """int
-%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg, int off,
-    const %(ctype)s value)
-{
-  struct evbuffer *tmp = NULL;
-  if (!msg->%(name)s_set || off < 0 || off >= msg->%(name)s_length)
-    return (-1);
-  %(refname)s_clear(msg->%(name)s_data[off]);
-  if ((tmp = evbuffer_new()) == NULL) {
-    event_warn("%%s: evbuffer_new()", __func__);
-    goto error;
-  }
-  %(refname)s_marshal(tmp, value);
-  if (%(refname)s_unmarshal(msg->%(name)s_data[off], tmp) == -1) {
-    event_warnx("%%s: %(refname)s_unmarshal", __func__);
-    goto error;
-  }
-  evbuffer_free(tmp);
-  return (0);
-error:
-  if (tmp != NULL)
-    evbuffer_free(tmp);
-  %(refname)s_clear(msg->%(name)s_data[off]);
-  return (-1);
-}""" % self.GetTranslation()
-
-        return code.split('\n')
-        
-    def CodeAdd(self):
-        code = \
-"""%(ctype)s
-%(parent_name)s_%(name)s_add(struct %(parent_name)s *msg)
-{
-  if (++msg->%(name)s_length >= msg->%(name)s_num_allocated) {
-    int tobe_allocated = msg->%(name)s_num_allocated;
-    %(ctype)s* new_data = NULL;
-    tobe_allocated = !tobe_allocated ? 1 : tobe_allocated << 1;
-    new_data = (%(ctype)s*) realloc(msg->%(name)s_data,
-        tobe_allocated * sizeof(%(ctype)s));
-    if (new_data == NULL)
-      goto error;
-    msg->%(name)s_data = new_data;
-    msg->%(name)s_num_allocated = tobe_allocated;
-  }
-  msg->%(name)s_data[msg->%(name)s_length - 1] = %(refname)s_new();
-  if (msg->%(name)s_data[msg->%(name)s_length - 1] == NULL)
-    goto error;
-  msg->%(name)s_set = 1;
-  return (msg->%(name)s_data[msg->%(name)s_length - 1]);
-error:
-  --msg->%(name)s_length;
-  return (NULL);
-}
-        """ % self.GetTranslation()
-
-        return code.split('\n')
-
-    def CodeComplete(self, structname):
-        code = []
-        translate = self.GetTranslation()
-
-        if self.Optional():
-            code.append( 'if (%(structname)s->%(name)s_set)'  % translate)
-
-        translate["structname"] = structname
-        tmp = """{
-  int i;
-  for (i = 0; i < %(structname)s->%(name)s_length; ++i) {
-    if (%(refname)s_complete(%(structname)s->%(name)s_data[i]) == -1)
-      return (-1);
-  }
-}""" % translate
-        code.extend(tmp.split('\n'))
-
-        return code
-    
-    def CodeUnmarshal(self, buf, tag_name, var_name):
-        translate = self.GetTranslation()
-        translate["var_name"] = var_name
-        translate["buf"] = buf
-        translate["tag_name"] = tag_name
-        code = """if (%(parent_name)s_%(name)s_add(%(var_name)s) == NULL)
-  return (-1);
-if (evtag_unmarshal_%(refname)s(%(buf)s, %(tag_name)s,
-  %(var_name)s->%(name)s_data[%(var_name)s->%(name)s_length - 1]) == -1) {
-  --%(var_name)s->%(name)s_length;
-  event_warnx("%%s: failed to unmarshal %(name)s", __func__);
-  return (-1);
-}""" % translate
-
-        return code.split('\n')
-
-    def CodeMarshal(self, buf, tag_name, var_name):
-        code = ['{',
-                '  int i;',
-                '  for (i = 0; i < %s->%s_length; ++i) {' % (
-            var_name, self._name),
-                '    evtag_marshal_%s(%s, %s, %s->%s_data[i]);' % (
-            self._refname, buf, tag_name, var_name, self._name),
-                '  }',
-                '}'
-                ]
-        return code
-
-    def CodeClear(self, structname):
-        code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
-                 '  int i;',
-                 '  for (i = 0; i < %s->%s_length; ++i) {' % (
-            structname, self.Name()),
-                 '    %s_free(%s->%s_data[i]);' % (
-            self._refname, structname, self.Name()),
-                 '  }',
-                 '  free(%s->%s_data);' % (structname, self.Name()),
-                 '  %s->%s_data = NULL;' % (structname, self.Name()),
-                 '  %s->%s_set = 0;' % (structname, self.Name()),
-                 '  %s->%s_length = 0;' % (structname, self.Name()),
-                 '  %s->%s_num_allocated = 0;' % (structname, self.Name()),
-                 '}'
-                 ]
-
-        return code
-        
-    def CodeNew(self, name):
-        code  = ['%s->%s_data = NULL;' % (name, self._name),
-                 '%s->%s_length = 0;' % (name, self._name),
-                 '%s->%s_num_allocated = 0;' % (name, self._name)]
-        return code
-
-    def CodeFree(self, name):
-        code  = ['if (%s->%s_data != NULL) {' % (name, self._name),
-                 '  int i;',
-                 '  for (i = 0; i < %s->%s_length; ++i) {' % (
-            name, self._name),
-                 '    %s_free(%s->%s_data[i]); ' % (
-            self._refname, name, self._name),
-                 '    %s->%s_data[i] = NULL;' % (name, self._name),
-                 '  }',
-                 '  free(%s->%s_data);' % (name, self._name),
-                 '  %s->%s_data = NULL;' % (name, self._name),
-                 '  %s->%s_length = 0;' % (name, self._name),
-                 '  %s->%s_num_allocated = 0;' % (name, self._name),
-                 '}'
-                 ]
-
-        return code
-
-    def Declaration(self):
-        dcl  = ['struct %s **%s_data;' % (self._refname, self._name),
-                'int %s_length;' % self._name,
-                'int %s_num_allocated;' % self._name ]
-
-        return dcl
-
-def NormalizeLine(line):
-    global white
-    global cppcomment
-    
-    line = cppcomment.sub('', line)
-    line = line.strip()
-    line = white.sub(' ', line)
-
-    return line
-
-def ProcessOneEntry(newstruct, entry):
-    optional = 0
-    array = 0
-    entry_type = ''
-    name = ''
-    tag = ''
-    tag_set = None
-    separator = ''
-    fixed_length = ''
-
-    tokens = entry.split(' ')
-    while tokens:
-        token = tokens[0]
-        tokens = tokens[1:]
-
-        if not entry_type:
-            if not optional and token == 'optional':
-                optional = 1
-                continue
-
-            if not array and token == 'array':
-                array = 1
-                continue
-
-        if not entry_type:
-            entry_type = token
-            continue
-
-        if not name:
-            res = re.match(r'^([^\[\]]+)(\[.*\])?$', token)
-            if not res:
-                print >>sys.stderr, 'Cannot parse name: \"%s\" around %d' % (
-                    entry, line_count)
-                sys.exit(1)
-            name = res.group(1)
-            fixed_length = res.group(2)
-            if fixed_length:
-                fixed_length = fixed_length[1:-1]
-            continue
-
-        if not separator:
-            separator = token
-            if separator != '=':
-                print >>sys.stderr, 'Expected "=" after name \"%s\" got %s' % (
-                    name, token)
-                sys.exit(1)
-            continue
-
-        if not tag_set:
-            tag_set = 1
-            if not re.match(r'^(0x)?[0-9]+$', token):
-                print >>sys.stderr, 'Expected tag number: \"%s\"' % entry
-                sys.exit(1)
-            tag = int(token, 0)
-            continue
-
-        print >>sys.stderr, 'Cannot parse \"%s\"' % entry
-        sys.exit(1)
-
-    if not tag_set:
-        print >>sys.stderr, 'Need tag number: \"%s\"' % entry
-        sys.exit(1)
-
-    # Create the right entry
-    if entry_type == 'bytes':
-        if fixed_length:
-            newentry = EntryBytes(entry_type, name, tag, fixed_length)
-        else:
-            newentry = EntryVarBytes(entry_type, name, tag)
-    elif entry_type == 'int' and not fixed_length:
-        newentry = EntryInt(entry_type, name, tag)
-    elif entry_type == 'string' and not fixed_length:
-        newentry = EntryString(entry_type, name, tag)
-    else:
-        res = re.match(r'^struct\[(%s)\]$' % _STRUCT_RE,
-                       entry_type, re.IGNORECASE)
-        if res:
-            # References another struct defined in our file
-            newentry = EntryStruct(entry_type, name, tag, res.group(1))
-        else:
-            print >>sys.stderr, 'Bad type: "%s" in "%s"' % (entry_type, entry)
-            sys.exit(1)
-
-    structs = []
-        
-    if optional:
-        newentry.MakeOptional()
-    if array:
-        newentry.MakeArray()
-
-    newentry.SetStruct(newstruct)
-    newentry.SetLineCount(line_count)
-    newentry.Verify()
-
-    if array:
-        # We need to encapsulate this entry into a struct
-        newname = newentry.Name()+ '_array'
-
-        # Now borgify the new entry.
-        newentry = EntryArray(newentry)
-        newentry.SetStruct(newstruct)
-        newentry.SetLineCount(line_count)
-        newentry.MakeArray()
-
-    newstruct.AddEntry(newentry)
-
-    return structs
-
-def ProcessStruct(data):
-    tokens = data.split(' ')
-
-    # First three tokens are: 'struct' 'name' '{'
-    newstruct = Struct(tokens[1])
-
-    inside = ' '.join(tokens[3:-1])
-
-    tokens = inside.split(';')
-
-    structs = []
-
-    for entry in tokens:
-        entry = NormalizeLine(entry)
-        if not entry:
-            continue
-
-        # It's possible that new structs get defined in here
-        structs.extend(ProcessOneEntry(newstruct, entry))
-
-    structs.append(newstruct)
-    return structs
-
-def GetNextStruct(file):
-    global line_count
-    global cppdirect
-
-    got_struct = 0
-
-    processed_lines = []
-
-    have_c_comment = 0
-    data = ''
-    while 1:
-        line = file.readline()
-        if not line:
-            break
-        
-        line_count += 1
-        line = line[:-1]
-
-        if not have_c_comment and re.search(r'/\*', line):
-            if re.search(r'/\*.*\*/', line):
-                line = re.sub(r'/\*.*\*/', '', line)
-            else:
-                line = re.sub(r'/\*.*$', '', line)
-                have_c_comment = 1
-
-        if have_c_comment:
-            if not re.search(r'\*/', line):
-                continue
-            have_c_comment = 0
-            line = re.sub(r'^.*\*/', '', line)
-
-        line = NormalizeLine(line)
-
-        if not line:
-            continue
-
-        if not got_struct:
-            if re.match(r'#include ["<].*[>"]', line):
-                cppdirect.append(line)
-                continue
-            
-            if re.match(r'^#(if( |def)|endif)', line):
-                cppdirect.append(line)
-                continue
-
-            if re.match(r'^#define', line):
-                headerdirect.append(line)
-                continue
-
-            if not re.match(r'^struct %s {$' % _STRUCT_RE,
-                            line, re.IGNORECASE):
-                print >>sys.stderr, 'Missing struct on line %d: %s' % (
-                    line_count, line)
-                sys.exit(1)
-            else:
-                got_struct = 1
-                data += line
-            continue
-
-        # We are inside the struct
-        tokens = line.split('}')
-        if len(tokens) == 1:
-            data += ' ' + line
-            continue
-
-        if len(tokens[1]):
-            print >>sys.stderr, 'Trailing garbage after struct on line %d' % (
-                line_count )
-            sys.exit(1)
-
-        # We found the end of the struct
-        data += ' %s}' % tokens[0]
-        break
-
-    # Remove any comments, that might be in there
-    data = re.sub(r'/\*.*\*/', '', data)
-    
-    return data
-        
-
-def Parse(file):
-    """
-    Parses the input file and returns C code and corresponding header file.
-    """
-
-    entities = []
-
-    while 1:
-        # Just gets the whole struct nicely formatted
-        data = GetNextStruct(file)
-
-        if not data:
-            break
-
-        entities.extend(ProcessStruct(data))
-
-    return entities
-
-def GuardName(name):
-    name = '_'.join(name.split('.'))
-    name = '_'.join(name.split('/'))
-    guard = '_'+name.upper()+'_'
-
-    return guard
-
-def HeaderPreamble(name):
-    guard = GuardName(name)
-    pre = (
-        '/*\n'
-        ' * Automatically generated from %s\n'
-        ' */\n\n'
-        '#ifndef %s\n'
-        '#define %s\n\n' ) % (
-        name, guard, guard)
-
-    # insert stdint.h - let's hope everyone has it
-    pre += (
-        '#include <event-config.h>\n'
-        '#ifdef _EVENT_HAVE_STDINT_H\n'
-        '#include <stdint.h>\n'
-        '#endif\n' )
-
-    for statement in headerdirect:
-        pre += '%s\n' % statement
-    if headerdirect:
-        pre += '\n'
-
-    pre += (
-        '#define EVTAG_HAS(msg, member) ((msg)->member##_set == 1)\n'
-        '#ifdef __GNUC__\n'
-        '#define EVTAG_ASSIGN(msg, member, args...) '
-        '(*(msg)->base->member##_assign)(msg, ## args)\n'
-        '#define EVTAG_GET(msg, member, args...) '
-        '(*(msg)->base->member##_get)(msg, ## args)\n'
-        '#else\n'
-        '#define EVTAG_ASSIGN(msg, member, ...) '
-        '(*(msg)->base->member##_assign)(msg, ## __VA_ARGS__)\n'
-        '#define EVTAG_GET(msg, member, ...) '
-        '(*(msg)->base->member##_get)(msg, ## __VA_ARGS__)\n'
-        '#endif\n'
-        '#define EVTAG_ADD(msg, member) (*(msg)->base->member##_add)(msg)\n'
-        '#define EVTAG_LEN(msg, member) ((msg)->member##_length)\n'
-        )
-
-    return pre
-     
-
-def HeaderPostamble(name):
-    guard = GuardName(name)
-    return '#endif  /* %s */' % guard
-
-def BodyPreamble(name):
-    global _NAME
-    global _VERSION
-    
-    header_file = '.'.join(name.split('.')[:-1]) + '.gen.h'
-
-    pre = ( '/*\n'
-            ' * Automatically generated from %s\n'
-            ' * by %s/%s.  DO NOT EDIT THIS FILE.\n'
-            ' */\n\n' ) % (name, _NAME, _VERSION)
-    pre += ( '#include <sys/types.h>\n'
-             '#ifdef _EVENT_HAVE_SYS_TIME_H\n'
-             '#include <sys/time.h>\n'
-             '#endif\n'
-             '#include <stdlib.h>\n'
-             '#include <string.h>\n'
-             '#include <assert.h>\n'
-             '#define EVENT_NO_STRUCT\n'
-             '#include <event.h>\n\n'
-             '#ifdef _EVENT___func__\n'
-             '#define __func__ _EVENT___func__\n'
-             '#endif\n' )
-
-    for statement in cppdirect:
-        pre += '%s\n' % statement
-    
-    pre += '\n#include "%s"\n\n' % header_file
-
-    pre += 'void event_err(int eval, const char *fmt, ...);\n'
-    pre += 'void event_warn(const char *fmt, ...);\n'
-    pre += 'void event_errx(int eval, const char *fmt, ...);\n'
-    pre += 'void event_warnx(const char *fmt, ...);\n\n'
-
-    return pre
-
-def main(argv):
-    if len(argv) < 2 or not argv[1]:
-        print >>sys.stderr, 'Need RPC description file as first argument.'
-        sys.exit(1)
-
-    filename = argv[1]
-
-    ext = filename.split('.')[-1]
-    if ext != 'rpc':
-        print >>sys.stderr, 'Unrecognized file extension: %s' % ext
-        sys.exit(1)
-
-    print >>sys.stderr, 'Reading \"%s\"' % filename
-
-    fp = open(filename, 'r')
-    entities = Parse(fp)
-    fp.close()
-
-    header_file = '.'.join(filename.split('.')[:-1]) + '.gen.h'
-    impl_file = '.'.join(filename.split('.')[:-1]) + '.gen.c'
-
-    print >>sys.stderr, '... creating "%s"' % header_file
-    header_fp = open(header_file, 'w')
-    print >>header_fp, HeaderPreamble(filename)
-
-    # Create forward declarations: allows other structs to reference
-    # each other
-    for entry in entities:
-        entry.PrintForwardDeclaration(header_fp)
-    print >>header_fp, ''
-
-    for entry in entities:
-        entry.PrintTags(header_fp)
-        entry.PrintDeclaration(header_fp)
-    print >>header_fp, HeaderPostamble(filename)
-    header_fp.close()
-
-    print >>sys.stderr, '... creating "%s"' % impl_file
-    impl_fp = open(impl_file, 'w')
-    print >>impl_fp, BodyPreamble(filename)
-    for entry in entities:
-        entry.PrintCode(impl_fp)
-    impl_fp.close()
-
-if __name__ == '__main__':
-    main(sys.argv)
diff --git a/base/third_party/libevent/event_tagging.c b/base/third_party/libevent/event_tagging.c
deleted file mode 100644
index d436e3f..0000000
--- a/base/third_party/libevent/event_tagging.c
+++ /dev/null
@@ -1,443 +0,0 @@
-/*
- * Copyright (c) 2003, 2004 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif
-
-#ifdef WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <winsock2.h>
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-#else
-#include <sys/ioctl.h>
-#endif
-
-#include <sys/queue.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#ifndef WIN32
-#include <syslog.h>
-#endif
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-
-#include "event.h"
-#include "evutil.h"
-#include "log.h"
-
-int evtag_decode_int(ev_uint32_t *pnumber, struct evbuffer *evbuf);
-int evtag_encode_tag(struct evbuffer *evbuf, ev_uint32_t tag);
-int evtag_decode_tag(ev_uint32_t *ptag, struct evbuffer *evbuf);
-
-static struct evbuffer *_buf;	/* not thread safe */
-
-void
-evtag_init(void)
-{
-	if (_buf != NULL)
-		return;
-
-	if ((_buf = evbuffer_new()) == NULL)
-		event_err(1, "%s: malloc", __func__);
-}
-
-/* 
- * We encode integer's by nibbles; the first nibble contains the number
- * of significant nibbles - 1;  this allows us to encode up to 64-bit
- * integers.  This function is byte-order independent.
- */
-
-void
-encode_int(struct evbuffer *evbuf, ev_uint32_t number)
-{
-	int off = 1, nibbles = 0;
-	ev_uint8_t data[5];
-
-	memset(data, 0, sizeof(ev_uint32_t)+1);
-	while (number) {
-		if (off & 0x1)
-			data[off/2] = (data[off/2] & 0xf0) | (number & 0x0f);
-		else
-			data[off/2] = (data[off/2] & 0x0f) |
-			    ((number & 0x0f) << 4);
-		number >>= 4;
-		off++;
-	}
-
-	if (off > 2)
-		nibbles = off - 2;
-
-	/* Off - 1 is the number of encoded nibbles */
-	data[0] = (data[0] & 0x0f) | ((nibbles & 0x0f) << 4);
-
-	evbuffer_add(evbuf, data, (off + 1) / 2);
-}
-
-/*
- * Support variable length encoding of tags; we use the high bit in each
- * octet as a continuation signal.
- */
-
-int
-evtag_encode_tag(struct evbuffer *evbuf, ev_uint32_t tag)
-{
-	int bytes = 0;
-	ev_uint8_t data[5];
-
-	memset(data, 0, sizeof(data));
-	do {
-		ev_uint8_t lower = tag & 0x7f;
-		tag >>= 7;
-
-		if (tag)
-			lower |= 0x80;
-
-		data[bytes++] = lower;
-	} while (tag);
-
-	if (evbuf != NULL)
-		evbuffer_add(evbuf, data, bytes);
-
-	return (bytes);
-}
-
-static int
-decode_tag_internal(ev_uint32_t *ptag, struct evbuffer *evbuf, int dodrain)
-{
-	ev_uint32_t number = 0;
-	ev_uint8_t *data = EVBUFFER_DATA(evbuf);
-	int len = EVBUFFER_LENGTH(evbuf);
-	int count = 0, shift = 0, done = 0;
-
-	while (count++ < len) {
-		ev_uint8_t lower = *data++;
-		number |= (lower & 0x7f) << shift;
-		shift += 7;
-
-		if (!(lower & 0x80)) {
-			done = 1;
-			break;
-		}
-	}
-
-	if (!done)
-		return (-1);
-
-	if (dodrain)
-		evbuffer_drain(evbuf, count);
-
-	if (ptag != NULL)
-		*ptag = number;
-
-	return (count);
-}
-
-int
-evtag_decode_tag(ev_uint32_t *ptag, struct evbuffer *evbuf)
-{
-	return (decode_tag_internal(ptag, evbuf, 1 /* dodrain */));
-}
-
-/*
- * Marshal a data type, the general format is as follows:
- *
- * tag number: one byte; length: var bytes; payload: var bytes
- */
-
-void
-evtag_marshal(struct evbuffer *evbuf, ev_uint32_t tag,
-    const void *data, ev_uint32_t len)
-{
-	evtag_encode_tag(evbuf, tag);
-	encode_int(evbuf, len);
-	evbuffer_add(evbuf, (void *)data, len);
-}
-
-/* Marshaling for integers */
-void
-evtag_marshal_int(struct evbuffer *evbuf, ev_uint32_t tag, ev_uint32_t integer)
-{
-	evbuffer_drain(_buf, EVBUFFER_LENGTH(_buf));
-	encode_int(_buf, integer);
-
-	evtag_encode_tag(evbuf, tag);
-	encode_int(evbuf, EVBUFFER_LENGTH(_buf));
-	evbuffer_add_buffer(evbuf, _buf);
-}
-
-void
-evtag_marshal_string(struct evbuffer *buf, ev_uint32_t tag, const char *string)
-{
-	evtag_marshal(buf, tag, string, strlen(string));
-}
-
-void
-evtag_marshal_timeval(struct evbuffer *evbuf, ev_uint32_t tag, struct timeval *tv)
-{
-	evbuffer_drain(_buf, EVBUFFER_LENGTH(_buf));
-
-	encode_int(_buf, tv->tv_sec);
-	encode_int(_buf, tv->tv_usec);
-
-	evtag_marshal(evbuf, tag, EVBUFFER_DATA(_buf),
-	    EVBUFFER_LENGTH(_buf));
-}
-
-static int
-decode_int_internal(ev_uint32_t *pnumber, struct evbuffer *evbuf, int dodrain)
-{
-	ev_uint32_t number = 0;
-	ev_uint8_t *data = EVBUFFER_DATA(evbuf);
-	int len = EVBUFFER_LENGTH(evbuf);
-	int nibbles = 0;
-
-	if (!len)
-		return (-1);
-
-	nibbles = ((data[0] & 0xf0) >> 4) + 1;
-	if (nibbles > 8 || (nibbles >> 1) + 1 > len)
-		return (-1);
-	len = (nibbles >> 1) + 1;
-
-	while (nibbles > 0) {
-		number <<= 4;
-		if (nibbles & 0x1)
-			number |= data[nibbles >> 1] & 0x0f;
-		else
-			number |= (data[nibbles >> 1] & 0xf0) >> 4;
-		nibbles--;
-	}
-
-	if (dodrain)
-		evbuffer_drain(evbuf, len);
-
-	*pnumber = number;
-
-	return (len);
-}
-
-int
-evtag_decode_int(ev_uint32_t *pnumber, struct evbuffer *evbuf)
-{
-	return (decode_int_internal(pnumber, evbuf, 1) == -1 ? -1 : 0);
-}
-
-int
-evtag_peek(struct evbuffer *evbuf, ev_uint32_t *ptag)
-{
-	return (decode_tag_internal(ptag, evbuf, 0 /* dodrain */));
-}
-
-int
-evtag_peek_length(struct evbuffer *evbuf, ev_uint32_t *plength)
-{
-	struct evbuffer tmp;
-	int res, len;
-
-	len = decode_tag_internal(NULL, evbuf, 0 /* dodrain */);
-	if (len == -1)
-		return (-1);
-
-	tmp = *evbuf;
-	tmp.buffer += len;
-	tmp.off -= len;
-
-	res = decode_int_internal(plength, &tmp, 0);
-	if (res == -1)
-		return (-1);
-
-	*plength += res + len;
-
-	return (0);
-}
-
-int
-evtag_payload_length(struct evbuffer *evbuf, ev_uint32_t *plength)
-{
-	struct evbuffer tmp;
-	int res, len;
-
-	len = decode_tag_internal(NULL, evbuf, 0 /* dodrain */);
-	if (len == -1)
-		return (-1);
-
-	tmp = *evbuf;
-	tmp.buffer += len;
-	tmp.off -= len;
-
-	res = decode_int_internal(plength, &tmp, 0);
-	if (res == -1)
-		return (-1);
-
-	return (0);
-}
-
-int
-evtag_consume(struct evbuffer *evbuf)
-{
-	ev_uint32_t len;
-	if (decode_tag_internal(NULL, evbuf, 1 /* dodrain */) == -1)
-		return (-1);
-	if (evtag_decode_int(&len, evbuf) == -1)
-		return (-1);
-	evbuffer_drain(evbuf, len);
-
-	return (0);
-}
-
-/* Reads the data type from an event buffer */
-
-int
-evtag_unmarshal(struct evbuffer *src, ev_uint32_t *ptag, struct evbuffer *dst)
-{
-	ev_uint32_t len;
-	ev_uint32_t integer;
-
-	if (decode_tag_internal(ptag, src, 1 /* dodrain */) == -1)
-		return (-1);
-	if (evtag_decode_int(&integer, src) == -1)
-		return (-1);
-	len = integer;
-
-	if (EVBUFFER_LENGTH(src) < len)
-		return (-1);
-
-	if (evbuffer_add(dst, EVBUFFER_DATA(src), len) == -1)
-		return (-1);
-
-	evbuffer_drain(src, len);
-
-	return (len);
-}
-
-/* Marshaling for integers */
-
-int
-evtag_unmarshal_int(struct evbuffer *evbuf, ev_uint32_t need_tag,
-    ev_uint32_t *pinteger)
-{
-	ev_uint32_t tag;
-	ev_uint32_t len;
-	ev_uint32_t integer;
-
-	if (decode_tag_internal(&tag, evbuf, 1 /* dodrain */) == -1)
-		return (-1);
-	if (need_tag != tag)
-		return (-1);
-	if (evtag_decode_int(&integer, evbuf) == -1)
-		return (-1);
-	len = integer;
-
-	if (EVBUFFER_LENGTH(evbuf) < len)
-		return (-1);
-	
-	evbuffer_drain(_buf, EVBUFFER_LENGTH(_buf));
-	if (evbuffer_add(_buf, EVBUFFER_DATA(evbuf), len) == -1)
-		return (-1);
-
-	evbuffer_drain(evbuf, len);
-
-	return (evtag_decode_int(pinteger, _buf));
-}
-
-/* Unmarshal a fixed length tag */
-
-int
-evtag_unmarshal_fixed(struct evbuffer *src, ev_uint32_t need_tag, void *data,
-    size_t len)
-{
-	ev_uint32_t tag;
-
-	/* Initialize this event buffer so that we can read into it */
-	evbuffer_drain(_buf, EVBUFFER_LENGTH(_buf));
-
-	/* Now unmarshal a tag and check that it matches the tag we want */
-	if (evtag_unmarshal(src, &tag, _buf) == -1 || tag != need_tag)
-		return (-1);
-
-	if (EVBUFFER_LENGTH(_buf) != len)
-		return (-1);
-
-	memcpy(data, EVBUFFER_DATA(_buf), len);
-	return (0);
-}
-
-int
-evtag_unmarshal_string(struct evbuffer *evbuf, ev_uint32_t need_tag,
-    char **pstring)
-{
-	ev_uint32_t tag;
-
-	evbuffer_drain(_buf, EVBUFFER_LENGTH(_buf));
-
-	if (evtag_unmarshal(evbuf, &tag, _buf) == -1 || tag != need_tag)
-		return (-1);
-
-	*pstring = calloc(EVBUFFER_LENGTH(_buf) + 1, 1);
-	if (*pstring == NULL)
-		event_err(1, "%s: calloc", __func__);
-	evbuffer_remove(_buf, *pstring, EVBUFFER_LENGTH(_buf));
-
-	return (0);
-}
-
-int
-evtag_unmarshal_timeval(struct evbuffer *evbuf, ev_uint32_t need_tag,
-    struct timeval *ptv)
-{
-	ev_uint32_t tag;
-	ev_uint32_t integer;
-
-	evbuffer_drain(_buf, EVBUFFER_LENGTH(_buf));
-	if (evtag_unmarshal(evbuf, &tag, _buf) == -1 || tag != need_tag)
-		return (-1);
-
-	if (evtag_decode_int(&integer, _buf) == -1)
-		return (-1);
-	ptv->tv_sec = integer;
-	if (evtag_decode_int(&integer, _buf) == -1)
-		return (-1);
-	ptv->tv_usec = integer;
-
-	return (0);
-}
diff --git a/base/third_party/libevent/evhttp.h b/base/third_party/libevent/evhttp.h
deleted file mode 100644
index 48c1d91..0000000
--- a/base/third_party/libevent/evhttp.h
+++ /dev/null
@@ -1,375 +0,0 @@
-/*
- * Copyright (c) 2000-2004 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef _EVHTTP_H_
-#define _EVHTTP_H_
-
-#include "event.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <winsock2.h>
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-#endif
-
-/** @file evhttp.h
- *
- * Basic support for HTTP serving.
- *
- * As libevent is a library for dealing with event notification and most
- * interesting applications are networked today, I have often found the
- * need to write HTTP code.  The following prototypes and definitions provide
- * an application with a minimal interface for making HTTP requests and for
- * creating a very simple HTTP server.
- */
-
-/* Response codes */
-#define HTTP_OK			200
-#define HTTP_NOCONTENT		204
-#define HTTP_MOVEPERM		301
-#define HTTP_MOVETEMP		302
-#define HTTP_NOTMODIFIED	304
-#define HTTP_BADREQUEST		400
-#define HTTP_NOTFOUND		404
-#define HTTP_SERVUNAVAIL	503
-
-struct evhttp;
-struct evhttp_request;
-struct evkeyvalq;
-
-/** Create a new HTTP server
- *
- * @param base (optional) the event base to receive the HTTP events
- * @return a pointer to a newly initialized evhttp server structure
- */
-struct evhttp *evhttp_new(struct event_base *base);
-
-/**
- * Binds an HTTP server on the specified address and port.
- *
- * Can be called multiple times to bind the same http server
- * to multiple different ports.
- *
- * @param http a pointer to an evhttp object
- * @param address a string containing the IP address to listen(2) on
- * @param port the port number to listen on
- * @return 0 on success, -1 on failure
- * @see evhttp_free()
- */
-int evhttp_bind_socket(struct evhttp *http, const char *address, u_short port);
-
-/**
- * Makes an HTTP server accept connections on the specified socket
- *
- * This may be useful to create a socket and then fork multiple instances
- * of an http server, or when a socket has been communicated via file
- * descriptor passing in situations where an http servers does not have
- * permissions to bind to a low-numbered port.
- *
- * Can be called multiple times to have the http server listen to
- * multiple different sockets.
- *
- * @param http a pointer to an evhttp object
- * @param fd a socket fd that is ready for accepting connections
- * @return 0 on success, -1 on failure.
- * @see evhttp_free(), evhttp_bind_socket()
- */
-int evhttp_accept_socket(struct evhttp *http, int fd);
-
-/**
- * Free the previously created HTTP server.
- *
- * Works only if no requests are currently being served.
- *
- * @param http the evhttp server object to be freed
- * @see evhttp_start()
- */
-void evhttp_free(struct evhttp* http);
-
-/** Set a callback for a specified URI */
-void evhttp_set_cb(struct evhttp *, const char *,
-    void (*)(struct evhttp_request *, void *), void *);
-
-/** Removes the callback for a specified URI */
-int evhttp_del_cb(struct evhttp *, const char *);
-
-/** Set a callback for all requests that are not caught by specific callbacks
- */
-void evhttp_set_gencb(struct evhttp *,
-    void (*)(struct evhttp_request *, void *), void *);
-
-/**
- * Set the timeout for an HTTP request.
- *
- * @param http an evhttp object
- * @param timeout_in_secs the timeout, in seconds
- */
-void evhttp_set_timeout(struct evhttp *, int timeout_in_secs);
-
-/* Request/Response functionality */
-
-/**
- * Send an HTML error message to the client.
- *
- * @param req a request object
- * @param error the HTTP error code
- * @param reason a brief explanation of the error
- */
-void evhttp_send_error(struct evhttp_request *req, int error,
-    const char *reason);
-
-/**
- * Send an HTML reply to the client.
- *
- * @param req a request object
- * @param code the HTTP response code to send
- * @param reason a brief message to send with the response code
- * @param databuf the body of the response
- */
-void evhttp_send_reply(struct evhttp_request *req, int code,
-    const char *reason, struct evbuffer *databuf);
-
-/* Low-level response interface, for streaming/chunked replies */
-void evhttp_send_reply_start(struct evhttp_request *, int, const char *);
-void evhttp_send_reply_chunk(struct evhttp_request *, struct evbuffer *);
-void evhttp_send_reply_end(struct evhttp_request *);
-
-/**
- * Start an HTTP server on the specified address and port
- *
- * DEPRECATED: it does not allow an event base to be specified
- *
- * @param address the address to which the HTTP server should be bound
- * @param port the port number on which the HTTP server should listen
- * @return an struct evhttp object
- */
-struct evhttp *evhttp_start(const char *address, u_short port);
-
-/*
- * Interfaces for making requests
- */
-enum evhttp_cmd_type { EVHTTP_REQ_GET, EVHTTP_REQ_POST, EVHTTP_REQ_HEAD };
-
-enum evhttp_request_kind { EVHTTP_REQUEST, EVHTTP_RESPONSE };
-
-/**
- * the request structure that a server receives.
- * WARNING: expect this structure to change.  I will try to provide
- * reasonable accessors.
- */
-struct evhttp_request {
-#if defined(TAILQ_ENTRY)
-	TAILQ_ENTRY(evhttp_request) next;
-#else
-struct {
-	struct evhttp_request *tqe_next;
-	struct evhttp_request **tqe_prev;
-}       next;
-#endif
-
-	/* the connection object that this request belongs to */
-	struct evhttp_connection *evcon;
-	int flags;
-#define EVHTTP_REQ_OWN_CONNECTION	0x0001
-#define EVHTTP_PROXY_REQUEST		0x0002
-
-	struct evkeyvalq *input_headers;
-	struct evkeyvalq *output_headers;
-
-	/* address of the remote host and the port connection came from */
-	char *remote_host;
-	u_short remote_port;
-
-	enum evhttp_request_kind kind;
-	enum evhttp_cmd_type type;
-
-	char *uri;			/* uri after HTTP request was parsed */
-
-	char major;			/* HTTP Major number */
-	char minor;			/* HTTP Minor number */
-
-	int response_code;		/* HTTP Response code */
-	char *response_code_line;	/* Readable response */
-
-	struct evbuffer *input_buffer;	/* read data */
-	ev_int64_t ntoread;
-	int chunked:1,                  /* a chunked request */
-	    userdone:1;                 /* the user has sent all data */
-
-	struct evbuffer *output_buffer;	/* outgoing post or data */
-
-	/* Callback */
-	void (*cb)(struct evhttp_request *, void *);
-	void *cb_arg;
-
-	/*
-	 * Chunked data callback - call for each completed chunk if
-	 * specified.  If not specified, all the data is delivered via
-	 * the regular callback.
-	 */
-	void (*chunk_cb)(struct evhttp_request *, void *);
-};
-
-/**
- * Creates a new request object that needs to be filled in with the request
- * parameters.  The callback is executed when the request completed or an
- * error occurred.
- */
-struct evhttp_request *evhttp_request_new(
-	void (*cb)(struct evhttp_request *, void *), void *arg);
-
-/** enable delivery of chunks to requestor */
-void evhttp_request_set_chunked_cb(struct evhttp_request *,
-    void (*cb)(struct evhttp_request *, void *));
-
-/** Frees the request object and removes associated events. */
-void evhttp_request_free(struct evhttp_request *req);
-
-/** Returns the connection object associated with the request or NULL */
-struct evhttp_connection *evhttp_request_get_connection(struct evhttp_request *req);
-
-/**
- * A connection object that can be used to for making HTTP requests.  The
- * connection object tries to establish the connection when it is given an
- * http request object.
- */
-struct evhttp_connection *evhttp_connection_new(
-	const char *address, unsigned short port);
-
-/** Frees an http connection */
-void evhttp_connection_free(struct evhttp_connection *evcon);
-
-/** sets the ip address from which http connections are made */
-void evhttp_connection_set_local_address(struct evhttp_connection *evcon,
-    const char *address);
-
-/** sets the local port from which http connections are made */
-void evhttp_connection_set_local_port(struct evhttp_connection *evcon,
-    unsigned short port);
-
-/** Sets the timeout for events related to this connection */
-void evhttp_connection_set_timeout(struct evhttp_connection *evcon,
-    int timeout_in_secs);
-
-/** Sets the retry limit for this connection - -1 repeats indefnitely */
-void evhttp_connection_set_retries(struct evhttp_connection *evcon,
-    int retry_max);
-
-/** Set a callback for connection close. */
-void evhttp_connection_set_closecb(struct evhttp_connection *evcon,
-    void (*)(struct evhttp_connection *, void *), void *);
-
-/**
- * Associates an event base with the connection - can only be called
- * on a freshly created connection object that has not been used yet.
- */
-void evhttp_connection_set_base(struct evhttp_connection *evcon,
-    struct event_base *base);
-
-/** Get the remote address and port associated with this connection. */
-void evhttp_connection_get_peer(struct evhttp_connection *evcon,
-    char **address, u_short *port);
-
-/** The connection gets ownership of the request */
-int evhttp_make_request(struct evhttp_connection *evcon,
-    struct evhttp_request *req,
-    enum evhttp_cmd_type type, const char *uri);
-
-const char *evhttp_request_uri(struct evhttp_request *req);
-
-/* Interfaces for dealing with HTTP headers */
-
-const char *evhttp_find_header(const struct evkeyvalq *, const char *);
-int evhttp_remove_header(struct evkeyvalq *, const char *);
-int evhttp_add_header(struct evkeyvalq *, const char *, const char *);
-void evhttp_clear_headers(struct evkeyvalq *);
-
-/* Miscellaneous utility functions */
-
-
-/**
-  Helper function to encode a URI.
-
-  The returned string must be freed by the caller.
-
-  @param uri an unencoded URI
-  @return a newly allocated URI-encoded string
- */
-char *evhttp_encode_uri(const char *uri);
-
-
-/**
-  Helper function to decode a URI.
-
-  The returned string must be freed by the caller.
-
-  @param uri an encoded URI
-  @return a newly allocated unencoded URI
- */
-char *evhttp_decode_uri(const char *uri);
-
-
-/**
- * Helper function to parse out arguments in a query.
- *
- * Parsing a uri like
- *
- *    http://foo.com/?q=test&s=some+thing
- *
- * will result in two entries in the key value queue.
-
- * The first entry is: key="q", value="test"
- * The second entry is: key="s", value="some thing"
- *
- * @param uri the request URI
- * @param headers the head of the evkeyval queue
- */
-void evhttp_parse_query(const char *uri, struct evkeyvalq *headers);
-
-
-/**
- * Escape HTML character entities in a string.
- *
- * Replaces <, >, ", ' and & with &lt;, &gt;, &quot;,
- * &#039; and &amp; correspondingly.
- *
- * The returned string needs to be freed by the caller.
- *
- * @param html an unescaped HTML string
- * @return an escaped HTML string
- */
-char *evhttp_htmlescape(const char *html);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _EVHTTP_H_ */
diff --git a/base/third_party/libevent/evport.c b/base/third_party/libevent/evport.c
deleted file mode 100644
index 1f5ebc4..0000000
--- a/base/third_party/libevent/evport.c
+++ /dev/null
@@ -1,519 +0,0 @@
-/*
- * Submitted by David Pacheco (dp.spambait@gmail.com)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY SUN MICROSYSTEMS, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL SUN MICROSYSTEMS, INC. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
- */
-
-/*
- * Copyright (c) 2007 Sun Microsystems. All rights reserved.
- * Use is subject to license terms.
- */
-
-/*
- * evport.c: event backend using Solaris 10 event ports. See port_create(3C).
- * This implementation is loosely modeled after the one used for select(2) (in
- * select.c).
- *
- * The outstanding events are tracked in a data structure called evport_data.
- * Each entry in the ed_fds array corresponds to a file descriptor, and contains
- * pointers to the read and write events that correspond to that fd. (That is,
- * when the file is readable, the "read" event should handle it, etc.)
- *
- * evport_add and evport_del update this data structure. evport_dispatch uses it
- * to determine where to callback when an event occurs (which it gets from
- * port_getn). 
- *
- * Helper functions are used: grow() grows the file descriptor array as
- * necessary when large fd's come in. reassociate() takes care of maintaining
- * the proper file-descriptor/event-port associations.
- *
- * As in the select(2) implementation, signals are handled by evsignal.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <sys/time.h>
-#include <assert.h>
-#include <sys/queue.h>
-#include <errno.h>
-#include <poll.h>
-#include <port.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <unistd.h>
-#ifdef CHECK_INVARIANTS
-#include <assert.h>
-#endif
-
-#include "event.h"
-#include "event-internal.h"
-#include "log.h"
-#include "evsignal.h"
-
-
-/*
- * Default value for ed_nevents, which is the maximum file descriptor number we
- * can handle. If an event comes in for a file descriptor F > nevents, we will
- * grow the array of file descriptors, doubling its size.
- */
-#define DEFAULT_NFDS	16
-
-
-/*
- * EVENTS_PER_GETN is the maximum number of events to retrieve from port_getn on
- * any particular call. You can speed things up by increasing this, but it will
- * (obviously) require more memory.
- */
-#define EVENTS_PER_GETN 8
-
-/*
- * Per-file-descriptor information about what events we're subscribed to. These
- * fields are NULL if no event is subscribed to either of them.
- */
-
-struct fd_info {
-	struct event* fdi_revt; /* the event responsible for the "read"  */
-	struct event* fdi_wevt; /* the event responsible for the "write" */
-};
-
-#define FDI_HAS_READ(fdi)  ((fdi)->fdi_revt != NULL)
-#define FDI_HAS_WRITE(fdi) ((fdi)->fdi_wevt != NULL)
-#define FDI_HAS_EVENTS(fdi) (FDI_HAS_READ(fdi) || FDI_HAS_WRITE(fdi))
-#define FDI_TO_SYSEVENTS(fdi) (FDI_HAS_READ(fdi) ? POLLIN : 0) | \
-    (FDI_HAS_WRITE(fdi) ? POLLOUT : 0)
-
-struct evport_data {
-	int 		ed_port;	/* event port for system events  */
-	int		ed_nevents;	/* number of allocated fdi's 	 */
-	struct fd_info *ed_fds;		/* allocated fdi table 		 */
-	/* fdi's that we need to reassoc */
-	int ed_pending[EVENTS_PER_GETN]; /* fd's with pending events */
-};
-
-static void*	evport_init	(struct event_base *);
-static int 	evport_add	(void *, struct event *);
-static int 	evport_del	(void *, struct event *);
-static int 	evport_dispatch	(struct event_base *, void *, struct timeval *);
-static void	evport_dealloc	(struct event_base *, void *);
-
-const struct eventop evportops = {
-	"evport",
-	evport_init,
-	evport_add,
-	evport_del,
-	evport_dispatch,
-	evport_dealloc,
-	1 /* need reinit */
-};
-
-/*
- * Initialize the event port implementation.
- */
-
-static void*
-evport_init(struct event_base *base)
-{
-	struct evport_data *evpd;
-	int i;
-	/*
-	 * Disable event ports when this environment variable is set 
-	 */
-	if (evutil_getenv("EVENT_NOEVPORT"))
-		return (NULL);
-
-	if (!(evpd = calloc(1, sizeof(struct evport_data))))
-		return (NULL);
-
-	if ((evpd->ed_port = port_create()) == -1) {
-		free(evpd);
-		return (NULL);
-	}
-
-	/*
-	 * Initialize file descriptor structure
-	 */
-	evpd->ed_fds = calloc(DEFAULT_NFDS, sizeof(struct fd_info));
-	if (evpd->ed_fds == NULL) {
-		close(evpd->ed_port);
-		free(evpd);
-		return (NULL);
-	}
-	evpd->ed_nevents = DEFAULT_NFDS;
-	for (i = 0; i < EVENTS_PER_GETN; i++)
-		evpd->ed_pending[i] = -1;
-
-	evsignal_init(base);
-
-	return (evpd);
-}
-
-#ifdef CHECK_INVARIANTS
-/*
- * Checks some basic properties about the evport_data structure. Because it
- * checks all file descriptors, this function can be expensive when the maximum
- * file descriptor ever used is rather large.
- */
-
-static void
-check_evportop(struct evport_data *evpd)
-{
-	assert(evpd);
-	assert(evpd->ed_nevents > 0);
-	assert(evpd->ed_port > 0);
-	assert(evpd->ed_fds > 0);
-
-	/*
-	 * Verify the integrity of the fd_info struct as well as the events to
-	 * which it points (at least, that they're valid references and correct
-	 * for their position in the structure).
-	 */
-	int i;
-	for (i = 0; i < evpd->ed_nevents; ++i) {
-		struct event 	*ev;
-		struct fd_info 	*fdi;
-
-		fdi = &evpd->ed_fds[i];
-		if ((ev = fdi->fdi_revt) != NULL) {
-			assert(ev->ev_fd == i);
-		}
-		if ((ev = fdi->fdi_wevt) != NULL) {
-			assert(ev->ev_fd == i);
-		}
-	}
-}
-
-/*
- * Verifies very basic integrity of a given port_event.
- */
-static void
-check_event(port_event_t* pevt)
-{
-	/*
-	 * We've only registered for PORT_SOURCE_FD events. The only
-	 * other thing we can legitimately receive is PORT_SOURCE_ALERT,
-	 * but since we're not using port_alert either, we can assume
-	 * PORT_SOURCE_FD.
-	 */
-	assert(pevt->portev_source == PORT_SOURCE_FD);
-	assert(pevt->portev_user == NULL);
-}
-
-#else
-#define check_evportop(epop)
-#define check_event(pevt)
-#endif /* CHECK_INVARIANTS */
-
-/*
- * Doubles the size of the allocated file descriptor array.
- */
-static int
-grow(struct evport_data *epdp, int factor)
-{
-	struct fd_info *tmp;
-	int oldsize = epdp->ed_nevents;
-	int newsize = factor * oldsize;
-	assert(factor > 1);
-
-	check_evportop(epdp);
-
-	tmp = realloc(epdp->ed_fds, sizeof(struct fd_info) * newsize);
-	if (NULL == tmp)
-		return -1;
-	epdp->ed_fds = tmp;
-	memset((char*) (epdp->ed_fds + oldsize), 0, 
-	    (newsize - oldsize)*sizeof(struct fd_info));
-	epdp->ed_nevents = newsize;
-
-	check_evportop(epdp);
-
-	return 0;
-}
-
-
-/*
- * (Re)associates the given file descriptor with the event port. The OS events
- * are specified (implicitly) from the fd_info struct.
- */
-static int
-reassociate(struct evport_data *epdp, struct fd_info *fdip, int fd)
-{
-	int sysevents = FDI_TO_SYSEVENTS(fdip);
-
-	if (sysevents != 0) {
-		if (port_associate(epdp->ed_port, PORT_SOURCE_FD,
-				   fd, sysevents, NULL) == -1) {
-			event_warn("port_associate");
-			return (-1);
-		}
-	}
-
-	check_evportop(epdp);
-
-	return (0);
-}
-
-/*
- * Main event loop - polls port_getn for some number of events, and processes
- * them.
- */
-
-static int
-evport_dispatch(struct event_base *base, void *arg, struct timeval *tv)
-{
-	int i, res;
-	struct evport_data *epdp = arg;
-	port_event_t pevtlist[EVENTS_PER_GETN];
-
-	/*
-	 * port_getn will block until it has at least nevents events. It will
-	 * also return how many it's given us (which may be more than we asked
-	 * for, as long as it's less than our maximum (EVENTS_PER_GETN)) in
-	 * nevents.
-	 */
-	int nevents = 1;
-
-	/*
-	 * We have to convert a struct timeval to a struct timespec
-	 * (only difference is nanoseconds vs. microseconds). If no time-based
-	 * events are active, we should wait for I/O (and tv == NULL).
-	 */
-	struct timespec ts;
-	struct timespec *ts_p = NULL;
-	if (tv != NULL) {
-		ts.tv_sec = tv->tv_sec;
-		ts.tv_nsec = tv->tv_usec * 1000;
-		ts_p = &ts;
-	}
-
-	/*
-	 * Before doing anything else, we need to reassociate the events we hit
-	 * last time which need reassociation. See comment at the end of the
-	 * loop below.
-	 */
-	for (i = 0; i < EVENTS_PER_GETN; ++i) {
-		struct fd_info *fdi = NULL;
-		if (epdp->ed_pending[i] != -1) {
-			fdi = &(epdp->ed_fds[epdp->ed_pending[i]]);
-		}
-
-		if (fdi != NULL && FDI_HAS_EVENTS(fdi)) {
-			int fd = FDI_HAS_READ(fdi) ? fdi->fdi_revt->ev_fd : 
-			    fdi->fdi_wevt->ev_fd;
-			reassociate(epdp, fdi, fd);
-			epdp->ed_pending[i] = -1;
-		}
-	}
-
-	if ((res = port_getn(epdp->ed_port, pevtlist, EVENTS_PER_GETN, 
-		    (unsigned int *) &nevents, ts_p)) == -1) {
-		if (errno == EINTR || errno == EAGAIN) {
-			evsignal_process(base);
-			return (0);
-		} else if (errno == ETIME) {
-			if (nevents == 0)
-				return (0);
-		} else {
-			event_warn("port_getn");
-			return (-1);
-		}
-	} else if (base->sig.evsignal_caught) {
-		evsignal_process(base);
-	}
-	
-	event_debug(("%s: port_getn reports %d events", __func__, nevents));
-
-	for (i = 0; i < nevents; ++i) {
-		struct event *ev;
-		struct fd_info *fdi;
-		port_event_t *pevt = &pevtlist[i];
-		int fd = (int) pevt->portev_object;
-
-		check_evportop(epdp);
-		check_event(pevt);
-		epdp->ed_pending[i] = fd;
-
-		/*
-		 * Figure out what kind of event it was 
-		 * (because we have to pass this to the callback)
-		 */
-		res = 0;
-		if (pevt->portev_events & POLLIN)
-			res |= EV_READ;
-		if (pevt->portev_events & POLLOUT)
-			res |= EV_WRITE;
-
-		/*
-		 * Check for the error situations or a hangup situation
-		 */
-		if (pevt->portev_events & (POLLERR|POLLHUP|POLLNVAL))
-			res |= EV_READ|EV_WRITE;
-
-		assert(epdp->ed_nevents > fd);
-		fdi = &(epdp->ed_fds[fd]);
-
-		/*
-		 * We now check for each of the possible events (READ
-		 * or WRITE).  Then, we activate the event (which will
-		 * cause its callback to be executed).
-		 */
-
-		if ((res & EV_READ) && ((ev = fdi->fdi_revt) != NULL)) {
-			event_active(ev, res, 1);
-		}
-
-		if ((res & EV_WRITE) && ((ev = fdi->fdi_wevt) != NULL)) {
-			event_active(ev, res, 1);
-		}
-	} /* end of all events gotten */
-
-	check_evportop(epdp);
-
-	return (0);
-}
-
-
-/*
- * Adds the given event (so that you will be notified when it happens via
- * the callback function).
- */
-
-static int
-evport_add(void *arg, struct event *ev)
-{
-	struct evport_data *evpd = arg;
-	struct fd_info *fdi;
-	int factor;
-
-	check_evportop(evpd);
-
-	/*
-	 * Delegate, if it's not ours to handle.
-	 */
-	if (ev->ev_events & EV_SIGNAL)
-		return (evsignal_add(ev));
-
-	/*
-	 * If necessary, grow the file descriptor info table
-	 */
-
-	factor = 1;
-	while (ev->ev_fd >= factor * evpd->ed_nevents)
-		factor *= 2;
-
-	if (factor > 1) {
-		if (-1 == grow(evpd, factor)) {
-			return (-1);
-		}
-	}
-
-	fdi = &evpd->ed_fds[ev->ev_fd];
-	if (ev->ev_events & EV_READ)
-		fdi->fdi_revt = ev;
-	if (ev->ev_events & EV_WRITE)
-		fdi->fdi_wevt = ev;
-
-	return reassociate(evpd, fdi, ev->ev_fd);
-}
-
-/*
- * Removes the given event from the list of events to wait for.
- */
-
-static int
-evport_del(void *arg, struct event *ev)
-{
-	struct evport_data *evpd = arg;
-	struct fd_info *fdi;
-	int i;
-	int associated = 1;
-
-	check_evportop(evpd);
-
-	/*
-	 * Delegate, if it's not ours to handle
-	 */
-	if (ev->ev_events & EV_SIGNAL) {
-		return (evsignal_del(ev));
-	}
-
-	if (evpd->ed_nevents < ev->ev_fd) {
-		return (-1);
-	}
-
-	for (i = 0; i < EVENTS_PER_GETN; ++i) {
-		if (evpd->ed_pending[i] == ev->ev_fd) {
-			associated = 0;
-			break;
-		}
-	}
-
-	fdi = &evpd->ed_fds[ev->ev_fd];
-	if (ev->ev_events & EV_READ)
-		fdi->fdi_revt = NULL;
-	if (ev->ev_events & EV_WRITE)
-		fdi->fdi_wevt = NULL;
-
-	if (associated) {
-		if (!FDI_HAS_EVENTS(fdi) &&
-		    port_dissociate(evpd->ed_port, PORT_SOURCE_FD,
-		    ev->ev_fd) == -1) {	 
-			/*
-			 * Ignre EBADFD error the fd could have been closed
-			 * before event_del() was called.
-			 */
-			if (errno != EBADFD) {
-				event_warn("port_dissociate");
-				return (-1);
-			}
-		} else {
-			if (FDI_HAS_EVENTS(fdi)) {
-				return (reassociate(evpd, fdi, ev->ev_fd));
-			}
-		}
-	} else {
-		if (fdi->fdi_revt == NULL && fdi->fdi_wevt == NULL) {
-			evpd->ed_pending[i] = -1;
-		}
-	}
-	return 0;
-}
-
-
-static void
-evport_dealloc(struct event_base *base, void *arg)
-{
-	struct evport_data *evpd = arg;
-
-	evsignal_dealloc(base);
-
-	close(evpd->ed_port);
-
-	if (evpd->ed_fds)
-		free(evpd->ed_fds);
-	free(evpd);
-}
diff --git a/base/third_party/libevent/evrpc-internal.h b/base/third_party/libevent/evrpc-internal.h
deleted file mode 100644
index c900f95..0000000
--- a/base/third_party/libevent/evrpc-internal.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (c) 2006 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef _EVRPC_INTERNAL_H_
-#define _EVRPC_INTERNAL_H_
-
-#include "http-internal.h"
-
-struct evrpc;
-
-#define EVRPC_URI_PREFIX "/.rpc."
-
-struct evrpc_hook {
-	TAILQ_ENTRY(evrpc_hook) (next);
-
-	/* returns -1; if the rpc should be aborted, is allowed to rewrite */
-	int (*process)(struct evhttp_request *, struct evbuffer *, void *);
-	void *process_arg;
-};
-
-TAILQ_HEAD(evrpc_hook_list, evrpc_hook);
-
-/*
- * this is shared between the base and the pool, so that we can reuse
- * the hook adding functions; we alias both evrpc_pool and evrpc_base
- * to this common structure.
- */
-struct _evrpc_hooks {
-	/* hooks for processing outbound and inbound rpcs */
-	struct evrpc_hook_list in_hooks;
-	struct evrpc_hook_list out_hooks;
-};
-
-#define input_hooks common.in_hooks
-#define output_hooks common.out_hooks
-
-struct evrpc_base {
-	struct _evrpc_hooks common;
-
-	/* the HTTP server under which we register our RPC calls */
-	struct evhttp* http_server;
-
-	/* a list of all RPCs registered with us */
-	TAILQ_HEAD(evrpc_list, evrpc) registered_rpcs;
-};
-
-struct evrpc_req_generic;
-void evrpc_reqstate_free(struct evrpc_req_generic* rpc_state);
-
-/* A pool for holding evhttp_connection objects */
-struct evrpc_pool {
-	struct _evrpc_hooks common;
-
-	struct event_base *base;
-
-	struct evconq connections;
-
-	int timeout;
-
-	TAILQ_HEAD(evrpc_requestq, evrpc_request_wrapper) requests;
-};
-
-
-#endif /* _EVRPC_INTERNAL_H_ */
diff --git a/base/third_party/libevent/evrpc.c b/base/third_party/libevent/evrpc.c
deleted file mode 100644
index 070fd9e..0000000
--- a/base/third_party/libevent/evrpc.c
+++ /dev/null
@@ -1,657 +0,0 @@
-/*
- * Copyright (c) 2000-2004 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <winsock2.h>
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-#endif
-
-#include <sys/types.h>
-#ifndef WIN32
-#include <sys/socket.h>
-#endif
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#include <sys/queue.h>
-#include <stdio.h>
-#include <stdlib.h>
-#ifndef WIN32
-#include <unistd.h>
-#endif
-#include <errno.h>
-#include <signal.h>
-#include <string.h>
-#include <assert.h>
-
-#include "event.h"
-#include "evrpc.h"
-#include "evrpc-internal.h"
-#include "evhttp.h"
-#include "evutil.h"
-#include "log.h"
-
-struct evrpc_base *
-evrpc_init(struct evhttp *http_server)
-{
-	struct evrpc_base* base = calloc(1, sizeof(struct evrpc_base));
-	if (base == NULL)
-		return (NULL);
-
-	/* we rely on the tagging sub system */
-	evtag_init();
-
-	TAILQ_INIT(&base->registered_rpcs);
-	TAILQ_INIT(&base->input_hooks);
-	TAILQ_INIT(&base->output_hooks);
-	base->http_server = http_server;
-
-	return (base);
-}
-
-void
-evrpc_free(struct evrpc_base *base)
-{
-	struct evrpc *rpc;
-	struct evrpc_hook *hook;
-
-	while ((rpc = TAILQ_FIRST(&base->registered_rpcs)) != NULL) {
-		assert(evrpc_unregister_rpc(base, rpc->uri));
-	}
-	while ((hook = TAILQ_FIRST(&base->input_hooks)) != NULL) {
-		assert(evrpc_remove_hook(base, EVRPC_INPUT, hook));
-	}
-	while ((hook = TAILQ_FIRST(&base->output_hooks)) != NULL) {
-		assert(evrpc_remove_hook(base, EVRPC_OUTPUT, hook));
-	}
-	free(base);
-}
-
-void *
-evrpc_add_hook(void *vbase,
-    enum EVRPC_HOOK_TYPE hook_type,
-    int (*cb)(struct evhttp_request *, struct evbuffer *, void *),
-    void *cb_arg)
-{
-	struct _evrpc_hooks *base = vbase;
-	struct evrpc_hook_list *head = NULL;
-	struct evrpc_hook *hook = NULL;
-	switch (hook_type) {
-	case EVRPC_INPUT:
-		head = &base->in_hooks;
-		break;
-	case EVRPC_OUTPUT:
-		head = &base->out_hooks;
-		break;
-	default:
-		assert(hook_type == EVRPC_INPUT || hook_type == EVRPC_OUTPUT);
-	}
-
-	hook = calloc(1, sizeof(struct evrpc_hook));
-	assert(hook != NULL);
-	
-	hook->process = cb;
-	hook->process_arg = cb_arg;
-	TAILQ_INSERT_TAIL(head, hook, next);
-
-	return (hook);
-}
-
-static int
-evrpc_remove_hook_internal(struct evrpc_hook_list *head, void *handle)
-{
-	struct evrpc_hook *hook = NULL;
-	TAILQ_FOREACH(hook, head, next) {
-		if (hook == handle) {
-			TAILQ_REMOVE(head, hook, next);
-			free(hook);
-			return (1);
-		}
-	}
-
-	return (0);
-}
-
-/*
- * remove the hook specified by the handle
- */
-
-int
-evrpc_remove_hook(void *vbase, enum EVRPC_HOOK_TYPE hook_type, void *handle)
-{
-	struct _evrpc_hooks *base = vbase;
-	struct evrpc_hook_list *head = NULL;
-	switch (hook_type) {
-	case EVRPC_INPUT:
-		head = &base->in_hooks;
-		break;
-	case EVRPC_OUTPUT:
-		head = &base->out_hooks;
-		break;
-	default:
-		assert(hook_type == EVRPC_INPUT || hook_type == EVRPC_OUTPUT);
-	}
-
-	return (evrpc_remove_hook_internal(head, handle));
-}
-
-static int
-evrpc_process_hooks(struct evrpc_hook_list *head,
-    struct evhttp_request *req, struct evbuffer *evbuf)
-{
-	struct evrpc_hook *hook;
-	TAILQ_FOREACH(hook, head, next) {
-		if (hook->process(req, evbuf, hook->process_arg) == -1)
-			return (-1);
-	}
-
-	return (0);
-}
-
-static void evrpc_pool_schedule(struct evrpc_pool *pool);
-static void evrpc_request_cb(struct evhttp_request *, void *);
-void evrpc_request_done(struct evrpc_req_generic*);
-
-/*
- * Registers a new RPC with the HTTP server.   The evrpc object is expected
- * to have been filled in via the EVRPC_REGISTER_OBJECT macro which in turn
- * calls this function.
- */
-
-static char *
-evrpc_construct_uri(const char *uri)
-{
-	char *constructed_uri;
-	int constructed_uri_len;
-
-	constructed_uri_len = strlen(EVRPC_URI_PREFIX) + strlen(uri) + 1;
-	if ((constructed_uri = malloc(constructed_uri_len)) == NULL)
-		event_err(1, "%s: failed to register rpc at %s",
-		    __func__, uri);
-	memcpy(constructed_uri, EVRPC_URI_PREFIX, strlen(EVRPC_URI_PREFIX));
-	memcpy(constructed_uri + strlen(EVRPC_URI_PREFIX), uri, strlen(uri));
-	constructed_uri[constructed_uri_len - 1] = '\0';
-
-	return (constructed_uri);
-}
-
-int
-evrpc_register_rpc(struct evrpc_base *base, struct evrpc *rpc,
-    void (*cb)(struct evrpc_req_generic *, void *), void *cb_arg)
-{
-	char *constructed_uri = evrpc_construct_uri(rpc->uri);
-
-	rpc->base = base;
-	rpc->cb = cb;
-	rpc->cb_arg = cb_arg;
-
-	TAILQ_INSERT_TAIL(&base->registered_rpcs, rpc, next);
-
-	evhttp_set_cb(base->http_server,
-	    constructed_uri,
-	    evrpc_request_cb,
-	    rpc);
-	
-	free(constructed_uri);
-
-	return (0);
-}
-
-int
-evrpc_unregister_rpc(struct evrpc_base *base, const char *name)
-{
-	char *registered_uri = NULL;
-	struct evrpc *rpc;
-
-	/* find the right rpc; linear search might be slow */
-	TAILQ_FOREACH(rpc, &base->registered_rpcs, next) {
-		if (strcmp(rpc->uri, name) == 0)
-			break;
-	}
-	if (rpc == NULL) {
-		/* We did not find an RPC with this name */
-		return (-1);
-	}
-	TAILQ_REMOVE(&base->registered_rpcs, rpc, next);
-	
-	free((char *)rpc->uri);
-	free(rpc);
-
-        registered_uri = evrpc_construct_uri(name);
-
-	/* remove the http server callback */
-	assert(evhttp_del_cb(base->http_server, registered_uri) == 0);
-
-	free(registered_uri);
-	return (0);
-}
-
-static void
-evrpc_request_cb(struct evhttp_request *req, void *arg)
-{
-	struct evrpc *rpc = arg;
-	struct evrpc_req_generic *rpc_state = NULL;
-
-	/* let's verify the outside parameters */
-	if (req->type != EVHTTP_REQ_POST ||
-	    EVBUFFER_LENGTH(req->input_buffer) <= 0)
-		goto error;
-
-	/*
-	 * we might want to allow hooks to suspend the processing,
-	 * but at the moment, we assume that they just act as simple
-	 * filters.
-	 */
-	if (evrpc_process_hooks(&rpc->base->input_hooks,
-		req, req->input_buffer) == -1)
-		goto error;
-
-	rpc_state = calloc(1, sizeof(struct evrpc_req_generic));
-	if (rpc_state == NULL)
-		goto error;
-
-	/* let's check that we can parse the request */
-	rpc_state->request = rpc->request_new();
-	if (rpc_state->request == NULL)
-		goto error;
-
-	rpc_state->rpc = rpc;
-
-	if (rpc->request_unmarshal(
-		    rpc_state->request, req->input_buffer) == -1) {
-		/* we failed to parse the request; that's a bummer */
-		goto error;
-	}
-
-	/* at this point, we have a well formed request, prepare the reply */
-
-	rpc_state->reply = rpc->reply_new();
-	if (rpc_state->reply == NULL)
-		goto error;
-
-	rpc_state->http_req = req;
-	rpc_state->done = evrpc_request_done;
-
-	/* give the rpc to the user; they can deal with it */
-	rpc->cb(rpc_state, rpc->cb_arg);
-
-	return;
-
-error:
-	evrpc_reqstate_free(rpc_state);
-	evhttp_send_error(req, HTTP_SERVUNAVAIL, "Service Error");
-	return;
-}
-
-void
-evrpc_reqstate_free(struct evrpc_req_generic* rpc_state)
-{
-	/* clean up all memory */
-	if (rpc_state != NULL) {
-		struct evrpc *rpc = rpc_state->rpc;
-
-		if (rpc_state->request != NULL)
-			rpc->request_free(rpc_state->request);
-		if (rpc_state->reply != NULL)
-			rpc->reply_free(rpc_state->reply);
-		free(rpc_state);
-	}
-}
-
-void
-evrpc_request_done(struct evrpc_req_generic* rpc_state)
-{
-	struct evhttp_request *req = rpc_state->http_req;
-	struct evrpc *rpc = rpc_state->rpc;
-	struct evbuffer* data = NULL;
-
-	if (rpc->reply_complete(rpc_state->reply) == -1) {
-		/* the reply was not completely filled in.  error out */
-		goto error;
-	}
-
-	if ((data = evbuffer_new()) == NULL) {
-		/* out of memory */
-		goto error;
-	}
-
-	/* serialize the reply */
-	rpc->reply_marshal(data, rpc_state->reply);
-
-	/* do hook based tweaks to the request */
-	if (evrpc_process_hooks(&rpc->base->output_hooks,
-		req, data) == -1)
-		goto error;
-
-	/* on success, we are going to transmit marshaled binary data */
-	if (evhttp_find_header(req->output_headers, "Content-Type") == NULL) {
-		evhttp_add_header(req->output_headers,
-		    "Content-Type", "application/octet-stream");
-	}
-
-	evhttp_send_reply(req, HTTP_OK, "OK", data);
-
-	evbuffer_free(data);
-
-	evrpc_reqstate_free(rpc_state);
-
-	return;
-
-error:
-	if (data != NULL)
-		evbuffer_free(data);
-	evrpc_reqstate_free(rpc_state);
-	evhttp_send_error(req, HTTP_SERVUNAVAIL, "Service Error");
-	return;
-}
-
-/* Client implementation of RPC site */
-
-static int evrpc_schedule_request(struct evhttp_connection *connection,
-    struct evrpc_request_wrapper *ctx);
-
-struct evrpc_pool *
-evrpc_pool_new(struct event_base *base)
-{
-	struct evrpc_pool *pool = calloc(1, sizeof(struct evrpc_pool));
-	if (pool == NULL)
-		return (NULL);
-
-	TAILQ_INIT(&pool->connections);
-	TAILQ_INIT(&pool->requests);
-
-	TAILQ_INIT(&pool->input_hooks);
-	TAILQ_INIT(&pool->output_hooks);
-
-	pool->base = base;
-	pool->timeout = -1;
-
-	return (pool);
-}
-
-static void
-evrpc_request_wrapper_free(struct evrpc_request_wrapper *request)
-{
-	free(request->name);
-	free(request);
-}
-
-void
-evrpc_pool_free(struct evrpc_pool *pool)
-{
-	struct evhttp_connection *connection;
-	struct evrpc_request_wrapper *request;
-	struct evrpc_hook *hook;
-
-	while ((request = TAILQ_FIRST(&pool->requests)) != NULL) {
-		TAILQ_REMOVE(&pool->requests, request, next);
-		/* if this gets more complicated we need our own function */
-		evrpc_request_wrapper_free(request);
-	}
-
-	while ((connection = TAILQ_FIRST(&pool->connections)) != NULL) {
-		TAILQ_REMOVE(&pool->connections, connection, next);
-		evhttp_connection_free(connection);
-	}
-
-	while ((hook = TAILQ_FIRST(&pool->input_hooks)) != NULL) {
-		assert(evrpc_remove_hook(pool, EVRPC_INPUT, hook));
-	}
-
-	while ((hook = TAILQ_FIRST(&pool->output_hooks)) != NULL) {
-		assert(evrpc_remove_hook(pool, EVRPC_OUTPUT, hook));
-	}
-
-	free(pool);
-}
-
-/*
- * Add a connection to the RPC pool.   A request scheduled on the pool
- * may use any available connection.
- */
-
-void
-evrpc_pool_add_connection(struct evrpc_pool *pool,
-    struct evhttp_connection *connection) {
-	assert(connection->http_server == NULL);
-	TAILQ_INSERT_TAIL(&pool->connections, connection, next);
-
-	/*
-	 * associate an event base with this connection
-	 */
-	if (pool->base != NULL)
-		evhttp_connection_set_base(connection, pool->base);
-
-	/* 
-	 * unless a timeout was specifically set for a connection,
-	 * the connection inherits the timeout from the pool.
-	 */
-	if (connection->timeout == -1)
-		connection->timeout = pool->timeout;
-
-	/* 
-	 * if we have any requests pending, schedule them with the new
-	 * connections.
-	 */
-
-	if (TAILQ_FIRST(&pool->requests) != NULL) {
-		struct evrpc_request_wrapper *request = 
-		    TAILQ_FIRST(&pool->requests);
-		TAILQ_REMOVE(&pool->requests, request, next);
-		evrpc_schedule_request(connection, request);
-	}
-}
-
-void
-evrpc_pool_set_timeout(struct evrpc_pool *pool, int timeout_in_secs)
-{
-	struct evhttp_connection *evcon;
-	TAILQ_FOREACH(evcon, &pool->connections, next) {
-		evcon->timeout = timeout_in_secs;
-	}
-	pool->timeout = timeout_in_secs;
-}
-
-
-static void evrpc_reply_done(struct evhttp_request *, void *);
-static void evrpc_request_timeout(int, short, void *);
-
-/*
- * Finds a connection object associated with the pool that is currently
- * idle and can be used to make a request.
- */
-static struct evhttp_connection *
-evrpc_pool_find_connection(struct evrpc_pool *pool)
-{
-	struct evhttp_connection *connection;
-	TAILQ_FOREACH(connection, &pool->connections, next) {
-		if (TAILQ_FIRST(&connection->requests) == NULL)
-			return (connection);
-	}
-
-	return (NULL);
-}
-
-/*
- * We assume that the ctx is no longer queued on the pool.
- */
-static int
-evrpc_schedule_request(struct evhttp_connection *connection,
-    struct evrpc_request_wrapper *ctx)
-{
-	struct evhttp_request *req = NULL;
-	struct evrpc_pool *pool = ctx->pool;
-	struct evrpc_status status;
-	char *uri = NULL;
-	int res = 0;
-
-	if ((req = evhttp_request_new(evrpc_reply_done, ctx)) == NULL)
-		goto error;
-
-	/* serialize the request data into the output buffer */
-	ctx->request_marshal(req->output_buffer, ctx->request);
-
-	uri = evrpc_construct_uri(ctx->name);
-	if (uri == NULL)
-		goto error;
-
-	/* we need to know the connection that we might have to abort */
-	ctx->evcon = connection;
-
-	/* apply hooks to the outgoing request */
-	if (evrpc_process_hooks(&pool->output_hooks,
-		req, req->output_buffer) == -1)
-		goto error;
-
-	if (pool->timeout > 0) {
-		/* 
-		 * a timeout after which the whole rpc is going to be aborted.
-		 */
-		struct timeval tv;
-		evutil_timerclear(&tv);
-		tv.tv_sec = pool->timeout;
-		evtimer_add(&ctx->ev_timeout, &tv);
-	}
-
-	/* start the request over the connection */
-	res = evhttp_make_request(connection, req, EVHTTP_REQ_POST, uri);
-	free(uri);
-
-	if (res == -1)
-		goto error;
-
-	return (0);
-
-error:
-	memset(&status, 0, sizeof(status));
-	status.error = EVRPC_STATUS_ERR_UNSTARTED;
-	(*ctx->cb)(&status, ctx->request, ctx->reply, ctx->cb_arg);
-	evrpc_request_wrapper_free(ctx);
-	return (-1);
-}
-
-int
-evrpc_make_request(struct evrpc_request_wrapper *ctx)
-{
-	struct evrpc_pool *pool = ctx->pool;
-
-	/* initialize the event structure for this rpc */
-	evtimer_set(&ctx->ev_timeout, evrpc_request_timeout, ctx);
-	if (pool->base != NULL)
-		event_base_set(pool->base, &ctx->ev_timeout);
-
-	/* we better have some available connections on the pool */
-	assert(TAILQ_FIRST(&pool->connections) != NULL);
-
-	/* 
-	 * if no connection is available, we queue the request on the pool,
-	 * the next time a connection is empty, the rpc will be send on that.
-	 */
-	TAILQ_INSERT_TAIL(&pool->requests, ctx, next);
-
-	evrpc_pool_schedule(pool);
-
-	return (0);
-}
-
-static void
-evrpc_reply_done(struct evhttp_request *req, void *arg)
-{
-	struct evrpc_request_wrapper *ctx = arg;
-	struct evrpc_pool *pool = ctx->pool;
-	struct evrpc_status status;
-	int res = -1;
-	
-	/* cancel any timeout we might have scheduled */
-	event_del(&ctx->ev_timeout);
-
-	memset(&status, 0, sizeof(status));
-	status.http_req = req;
-
-	/* we need to get the reply now */
-	if (req != NULL) {
-		/* apply hooks to the incoming request */
-		if (evrpc_process_hooks(&pool->input_hooks,
-			req, req->input_buffer) == -1) {
-			status.error = EVRPC_STATUS_ERR_HOOKABORTED;
-			res = -1;
-		} else {
-			res = ctx->reply_unmarshal(ctx->reply,
-			    req->input_buffer);
-			if (res == -1) {
-				status.error = EVRPC_STATUS_ERR_BADPAYLOAD;
-			}
-		}
-	} else {
-		status.error = EVRPC_STATUS_ERR_TIMEOUT;
-	}
-
-	if (res == -1) {
-		/* clear everything that we might have written previously */
-		ctx->reply_clear(ctx->reply);
-	}
-
-	(*ctx->cb)(&status, ctx->request, ctx->reply, ctx->cb_arg);
-	
-	evrpc_request_wrapper_free(ctx);
-
-	/* the http layer owns the request structure */
-
-	/* see if we can schedule another request */
-	evrpc_pool_schedule(pool);
-}
-
-static void
-evrpc_pool_schedule(struct evrpc_pool *pool)
-{
-	struct evrpc_request_wrapper *ctx = TAILQ_FIRST(&pool->requests);
-	struct evhttp_connection *evcon;
-
-	/* if no requests are pending, we have no work */
-	if (ctx == NULL)
-		return;
-
-	if ((evcon = evrpc_pool_find_connection(pool)) != NULL) {
-		TAILQ_REMOVE(&pool->requests, ctx, next);
-		evrpc_schedule_request(evcon, ctx);
-	}
-}
-
-static void
-evrpc_request_timeout(int fd, short what, void *arg)
-{
-	struct evrpc_request_wrapper *ctx = arg;
-	struct evhttp_connection *evcon = ctx->evcon;
-	assert(evcon != NULL);
-
-	evhttp_connection_fail(evcon, EVCON_HTTP_TIMEOUT);
-}
diff --git a/base/third_party/libevent/evrpc.h b/base/third_party/libevent/evrpc.h
deleted file mode 100644
index 7c16b95..0000000
--- a/base/third_party/libevent/evrpc.h
+++ /dev/null
@@ -1,486 +0,0 @@
-/*
- * Copyright (c) 2006 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef _EVRPC_H_
-#define _EVRPC_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/** @file evrpc.h
- *
- * This header files provides basic support for an RPC server and client.
- *
- * To support RPCs in a server, every supported RPC command needs to be
- * defined and registered.
- *
- * EVRPC_HEADER(SendCommand, Request, Reply);
- *
- *  SendCommand is the name of the RPC command.
- *  Request is the name of a structure generated by event_rpcgen.py.
- *    It contains all parameters relating to the SendCommand RPC.  The
- *    server needs to fill in the Reply structure.
- *  Reply is the name of a structure generated by event_rpcgen.py.  It
- *    contains the answer to the RPC.
- *
- * To register an RPC with an HTTP server, you need to first create an RPC
- * base with:
- *
- *   struct evrpc_base *base = evrpc_init(http);
- *
- * A specific RPC can then be registered with
- *
- * EVRPC_REGISTER(base, SendCommand, Request, Reply,  FunctionCB, arg);
- *
- * when the server receives an appropriately formatted RPC, the user callback
- * is invokved.   The callback needs to fill in the reply structure.
- *
- * void FunctionCB(EVRPC_STRUCT(SendCommand)* rpc, void *arg);
- *
- * To send the reply, call EVRPC_REQUEST_DONE(rpc);
- *
- * See the regression test for an example.
- */
-
-struct evbuffer;
-struct event_base;
-struct evrpc_req_generic;
-
-/* Encapsulates a request */
-struct evrpc {
-	TAILQ_ENTRY(evrpc) next;
-
-	/* the URI at which the request handler lives */
-	const char* uri;
-
-	/* creates a new request structure */
-	void *(*request_new)(void);
-
-	/* frees the request structure */
-	void (*request_free)(void *);
-
-	/* unmarshals the buffer into the proper request structure */
-	int (*request_unmarshal)(void *, struct evbuffer *);
-
-	/* creates a new reply structure */
-	void *(*reply_new)(void);
-
-	/* creates a new reply structure */
-	void (*reply_free)(void *);
-
-	/* verifies that the reply is valid */
-	int (*reply_complete)(void *);
-	
-	/* marshals the reply into a buffer */
-	void (*reply_marshal)(struct evbuffer*, void *);
-
-	/* the callback invoked for each received rpc */
-	void (*cb)(struct evrpc_req_generic *, void *);
-	void *cb_arg;
-
-	/* reference for further configuration */
-	struct evrpc_base *base;
-};
-
-/** The type of a specific RPC Message
- *
- * @param rpcname the name of the RPC message
- */
-#define EVRPC_STRUCT(rpcname) struct evrpc_req__##rpcname
-
-struct evhttp_request;
-struct evrpc_status;
-
-/* We alias the RPC specific structs to this voided one */
-struct evrpc_req_generic {
-	/* the unmarshaled request object */
-	void *request;
-
-	/* the empty reply object that needs to be filled in */
-	void *reply;
-
-	/* 
-	 * the static structure for this rpc; that can be used to
-	 * automatically unmarshal and marshal the http buffers.
-	 */
-	struct evrpc *rpc;
-
-	/*
-	 * the http request structure on which we need to answer.
-	 */
-	struct evhttp_request* http_req;
-
-	/*
-	 * callback to reply and finish answering this rpc
-	 */
-	void (*done)(struct evrpc_req_generic* rpc); 
-};
-
-/** Creates the definitions and prototypes for an RPC
- *
- * You need to use EVRPC_HEADER to create structures and function prototypes
- * needed by the server and client implementation.  The structures have to be
- * defined in an .rpc file and converted to source code via event_rpcgen.py
- *
- * @param rpcname the name of the RPC
- * @param reqstruct the name of the RPC request structure
- * @param replystruct the name of the RPC reply structure
- * @see EVRPC_GENERATE()
- */
-#define EVRPC_HEADER(rpcname, reqstruct, rplystruct) \
-EVRPC_STRUCT(rpcname) {	\
-	struct reqstruct* request; \
-	struct rplystruct* reply; \
-	struct evrpc* rpc; \
-	struct evhttp_request* http_req; \
-	void (*done)(struct evrpc_status *, \
-	    struct evrpc* rpc, void *request, void *reply);	     \
-};								     \
-int evrpc_send_request_##rpcname(struct evrpc_pool *, \
-    struct reqstruct *, struct rplystruct *, \
-    void (*)(struct evrpc_status *, \
-	struct reqstruct *, struct rplystruct *, void *cbarg),	\
-    void *);
-
-/** Generates the code for receiving and sending an RPC message
- *
- * EVRPC_GENERATE is used to create the code corresponding to sending
- * and receiving a particular RPC message
- *
- * @param rpcname the name of the RPC
- * @param reqstruct the name of the RPC request structure
- * @param replystruct the name of the RPC reply structure
- * @see EVRPC_HEADER()
- */
-#define EVRPC_GENERATE(rpcname, reqstruct, rplystruct) \
-int evrpc_send_request_##rpcname(struct evrpc_pool *pool, \
-    struct reqstruct *request, struct rplystruct *reply, \
-    void (*cb)(struct evrpc_status *, \
-	struct reqstruct *, struct rplystruct *, void *cbarg),	\
-    void *cbarg) { \
-	struct evrpc_status status;				    \
-	struct evrpc_request_wrapper *ctx;			    \
-	ctx = (struct evrpc_request_wrapper *) \
-	    malloc(sizeof(struct evrpc_request_wrapper));	    \
-	if (ctx == NULL)					    \
-		goto error;					    \
-	ctx->pool = pool;					    \
-	ctx->evcon = NULL;					    \
-	ctx->name = strdup(#rpcname);				    \
-	if (ctx->name == NULL) {				    \
-		free(ctx);					    \
-		goto error;					    \
-	}							    \
-	ctx->cb = (void (*)(struct evrpc_status *, \
-		void *, void *, void *))cb;			    \
-	ctx->cb_arg = cbarg;					    \
-	ctx->request = (void *)request;				    \
-	ctx->reply = (void *)reply;				    \
-	ctx->request_marshal = (void (*)(struct evbuffer *, void *))reqstruct##_marshal; \
-	ctx->reply_clear = (void (*)(void *))rplystruct##_clear;    \
-	ctx->reply_unmarshal = (int (*)(void *, struct evbuffer *))rplystruct##_unmarshal; \
-	return (evrpc_make_request(ctx));			    \
-error:								    \
-	memset(&status, 0, sizeof(status));			    \
-	status.error = EVRPC_STATUS_ERR_UNSTARTED;		    \
-	(*(cb))(&status, request, reply, cbarg);		    \
-	return (-1);						    \
-}
-
-/** Provides access to the HTTP request object underlying an RPC
- *
- * Access to the underlying http object; can be used to look at headers or
- * for getting the remote ip address
- *
- * @param rpc_req the rpc request structure provided to the server callback
- * @return an struct evhttp_request object that can be inspected for
- * HTTP headers or sender information.
- */
-#define EVRPC_REQUEST_HTTP(rpc_req) (rpc_req)->http_req
-
-/** Creates the reply to an RPC request
- * 
- * EVRPC_REQUEST_DONE is used to answer a request; the reply is expected
- * to have been filled in.  The request and reply pointers become invalid
- * after this call has finished.
- * 
- * @param rpc_req the rpc request structure provided to the server callback
- */
-#define EVRPC_REQUEST_DONE(rpc_req) do { \
-  struct evrpc_req_generic *_req = (struct evrpc_req_generic *)(rpc_req); \
-  _req->done(_req); \
-} while (0)
-  
-
-/* Takes a request object and fills it in with the right magic */
-#define EVRPC_REGISTER_OBJECT(rpc, name, request, reply) \
-  do { \
-    (rpc)->uri = strdup(#name); \
-    if ((rpc)->uri == NULL) {			 \
-      fprintf(stderr, "failed to register object\n");	\
-      exit(1);						\
-    } \
-    (rpc)->request_new = (void *(*)(void))request##_new; \
-    (rpc)->request_free = (void (*)(void *))request##_free; \
-    (rpc)->request_unmarshal = (int (*)(void *, struct evbuffer *))request##_unmarshal; \
-    (rpc)->reply_new = (void *(*)(void))reply##_new; \
-    (rpc)->reply_free = (void (*)(void *))reply##_free; \
-    (rpc)->reply_complete = (int (*)(void *))reply##_complete; \
-    (rpc)->reply_marshal = (void (*)(struct evbuffer*, void *))reply##_marshal; \
-  } while (0)
-
-struct evrpc_base;
-struct evhttp;
-
-/* functions to start up the rpc system */
-
-/** Creates a new rpc base from which RPC requests can be received
- *
- * @param server a pointer to an existing HTTP server
- * @return a newly allocated evrpc_base struct
- * @see evrpc_free()
- */
-struct evrpc_base *evrpc_init(struct evhttp *server);
-
-/** 
- * Frees the evrpc base
- *
- * For now, you are responsible for making sure that no rpcs are ongoing.
- *
- * @param base the evrpc_base object to be freed
- * @see evrpc_init
- */
-void evrpc_free(struct evrpc_base *base);
-
-/** register RPCs with the HTTP Server
- *
- * registers a new RPC with the HTTP server, each RPC needs to have
- * a unique name under which it can be identified.
- *
- * @param base the evrpc_base structure in which the RPC should be
- *   registered.
- * @param name the name of the RPC
- * @param request the name of the RPC request structure
- * @param reply the name of the RPC reply structure
- * @param callback the callback that should be invoked when the RPC
- * is received.  The callback has the following prototype
- *   void (*callback)(EVRPC_STRUCT(Message)* rpc, void *arg)
- * @param cbarg an additional parameter that can be passed to the callback.
- *   The parameter can be used to carry around state.
- */
-#define EVRPC_REGISTER(base, name, request, reply, callback, cbarg) \
-  do { \
-    struct evrpc* rpc = (struct evrpc *)calloc(1, sizeof(struct evrpc)); \
-    EVRPC_REGISTER_OBJECT(rpc, name, request, reply); \
-    evrpc_register_rpc(base, rpc, \
-	(void (*)(struct evrpc_req_generic*, void *))callback, cbarg);	\
-  } while (0)
-
-int evrpc_register_rpc(struct evrpc_base *, struct evrpc *,
-    void (*)(struct evrpc_req_generic*, void *), void *);
-
-/**
- * Unregisters an already registered RPC
- *
- * @param base the evrpc_base object from which to unregister an RPC
- * @param name the name of the rpc to unregister
- * @return -1 on error or 0 when successful.
- * @see EVRPC_REGISTER()
- */
-#define EVRPC_UNREGISTER(base, name) evrpc_unregister_rpc(base, #name)
-
-int evrpc_unregister_rpc(struct evrpc_base *base, const char *name);
-
-/*
- * Client-side RPC support
- */
-
-struct evrpc_pool;
-struct evhttp_connection;
-
-/** 
- * provides information about the completed RPC request.
- */
-struct evrpc_status {
-#define EVRPC_STATUS_ERR_NONE		0
-#define EVRPC_STATUS_ERR_TIMEOUT	1
-#define EVRPC_STATUS_ERR_BADPAYLOAD	2
-#define EVRPC_STATUS_ERR_UNSTARTED	3
-#define EVRPC_STATUS_ERR_HOOKABORTED	4
-	int error;
-
-	/* for looking at headers or other information */
-	struct evhttp_request *http_req;
-};
-
-struct evrpc_request_wrapper {
-	TAILQ_ENTRY(evrpc_request_wrapper) next;
-
-        /* pool on which this rpc request is being made */
-        struct evrpc_pool *pool;
-
-        /* connection on which the request is being sent */
-	struct evhttp_connection *evcon;
-
-	/* event for implementing request timeouts */
-	struct event ev_timeout;
-
-	/* the name of the rpc */
-	char *name;
-
-	/* callback */
-	void (*cb)(struct evrpc_status*, void *request, void *reply, void *arg);
-	void *cb_arg;
-
-	void *request;
-	void *reply;
-
-	/* unmarshals the buffer into the proper request structure */
-	void (*request_marshal)(struct evbuffer *, void *);
-
-	/* removes all stored state in the reply */
-	void (*reply_clear)(void *);
-
-	/* marshals the reply into a buffer */
-	int (*reply_unmarshal)(void *, struct evbuffer*);
-};
-
-/** launches an RPC and sends it to the server
- *
- * EVRPC_MAKE_REQUEST() is used by the client to send an RPC to the server.
- *
- * @param name the name of the RPC
- * @param pool the evrpc_pool that contains the connection objects over which
- *   the request should be sent.
- * @param request a pointer to the RPC request structure - it contains the
- *   data to be sent to the server.
- * @param reply a pointer to the RPC reply structure.  It is going to be filled
- *   if the request was answered successfully
- * @param cb the callback to invoke when the RPC request has been answered
- * @param cbarg an additional argument to be passed to the client
- * @return 0 on success, -1 on failure
- */
-#define EVRPC_MAKE_REQUEST(name, pool, request, reply, cb, cbarg)	\
-	evrpc_send_request_##name(pool, request, reply, cb, cbarg)
-
-int evrpc_make_request(struct evrpc_request_wrapper *);
-
-/** creates an rpc connection pool
- * 
- * a pool has a number of connections associated with it.
- * rpc requests are always made via a pool.
- *
- * @param base a pointer to an struct event_based object; can be left NULL
- *   in singled-threaded applications
- * @return a newly allocated struct evrpc_pool object
- * @see evrpc_pool_free()
- */
-struct evrpc_pool *evrpc_pool_new(struct event_base *base);
-/** frees an rpc connection pool
- *
- * @param pool a pointer to an evrpc_pool allocated via evrpc_pool_new()
- * @see evrpc_pool_new()
- */
-void evrpc_pool_free(struct evrpc_pool *pool);
-/*
- * adds a connection over which rpc can be dispatched.  the connection
- * object must have been newly created.
- */
-void evrpc_pool_add_connection(struct evrpc_pool *, 
-    struct evhttp_connection *);
-
-/**
- * Sets the timeout in secs after which a request has to complete.  The
- * RPC is completely aborted if it does not complete by then.  Setting
- * the timeout to 0 means that it never timeouts and can be used to
- * implement callback type RPCs.
- *
- * Any connection already in the pool will be updated with the new
- * timeout.  Connections added to the pool after set_timeout has be
- * called receive the pool timeout only if no timeout has been set
- * for the connection itself.
- *
- * @param pool a pointer to a struct evrpc_pool object
- * @param timeout_in_secs the number of seconds after which a request should
- *   timeout and a failure be returned to the callback.
- */
-void evrpc_pool_set_timeout(struct evrpc_pool *pool, int timeout_in_secs);
-
-/**
- * Hooks for changing the input and output of RPCs; this can be used to
- * implement compression, authentication, encryption, ...
- */
-
-enum EVRPC_HOOK_TYPE {
-	EVRPC_INPUT,		/**< apply the function to an input hook */
-	EVRPC_OUTPUT		/**< apply the function to an output hook */
-};
-
-#ifndef WIN32
-/** Deprecated alias for EVRPC_INPUT.  Not available on windows, where it
- * conflicts with platform headers. */
-#define INPUT EVRPC_INPUT
-/** Deprecated alias for EVRPC_OUTPUT.  Not available on windows, where it
- * conflicts with platform headers. */
-#define OUTPUT EVRPC_OUTPUT
-#endif
-
-/** adds a processing hook to either an rpc base or rpc pool
- *
- * If a hook returns -1, the processing is aborted.
- *
- * The add functions return handles that can be used for removing hooks.
- *
- * @param vbase a pointer to either struct evrpc_base or struct evrpc_pool
- * @param hook_type either INPUT or OUTPUT
- * @param cb the callback to call when the hook is activated
- * @param cb_arg an additional argument for the callback
- * @return a handle to the hook so it can be removed later
- * @see evrpc_remove_hook()
- */
-void *evrpc_add_hook(void *vbase,
-    enum EVRPC_HOOK_TYPE hook_type,
-    int (*cb)(struct evhttp_request *, struct evbuffer *, void *),
-    void *cb_arg);
-
-/** removes a previously added hook
- *
- * @param vbase a pointer to either struct evrpc_base or struct evrpc_pool
- * @param hook_type either INPUT or OUTPUT
- * @param handle a handle returned by evrpc_add_hook()
- * @return 1 on success or 0 on failure
- * @see evrpc_add_hook()
- */
-int evrpc_remove_hook(void *vbase,
-    enum EVRPC_HOOK_TYPE hook_type,
-    void *handle);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _EVRPC_H_ */
diff --git a/base/third_party/libevent/evsignal.h b/base/third_party/libevent/evsignal.h
deleted file mode 100644
index 076cd8d..0000000
--- a/base/third_party/libevent/evsignal.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright 2000-2002 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef _EVSIGNAL_H_
-#define _EVSIGNAL_H_
-
-typedef void (*ev_sighandler_t)(int);
-
-struct evsignal_info {
-	struct event ev_signal;
-	int ev_signal_pair[2];
-	int ev_signal_added;
-	volatile sig_atomic_t evsignal_caught;
-	struct event_list evsigevents[NSIG];
-	sig_atomic_t evsigcaught[NSIG];
-#ifdef HAVE_SIGACTION
-	struct sigaction **sh_old;
-#else
-	ev_sighandler_t **sh_old;
-#endif
-	int sh_old_max;
-};
-int evsignal_init(struct event_base *);
-void evsignal_process(struct event_base *);
-int evsignal_add(struct event *);
-int evsignal_del(struct event *);
-void evsignal_dealloc(struct event_base *);
-
-#endif /* _EVSIGNAL_H_ */
diff --git a/base/third_party/libevent/evutil.c b/base/third_party/libevent/evutil.c
deleted file mode 100644
index cc6d0f4..0000000
--- a/base/third_party/libevent/evutil.c
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright (c) 2007 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef WIN32
-#include <winsock2.h>
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-#endif
-
-#include <sys/types.h>
-#ifdef HAVE_SYS_SOCKET_H
-#include <sys/socket.h>
-#endif
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif
-#ifdef HAVE_STDLIB_H
-#include <stdlib.h>
-#endif
-#include <errno.h>
-#if defined WIN32 && !defined(HAVE_GETTIMEOFDAY_H)
-#include <sys/timeb.h>
-#endif
-#include <stdio.h>
-#include <signal.h>
-
-#include <sys/queue.h>
-#include "event.h"
-#include "event-internal.h"
-#include "evutil.h"
-#include "log.h"
-
-int
-evutil_socketpair(int family, int type, int protocol, int fd[2])
-{
-#ifndef WIN32
-	return socketpair(family, type, protocol, fd);
-#else
-	/* This code is originally from Tor.  Used with permission. */
-
-	/* This socketpair does not work when localhost is down. So
-	 * it's really not the same thing at all. But it's close enough
-	 * for now, and really, when localhost is down sometimes, we
-	 * have other problems too.
-	 */
-	int listener = -1;
-	int connector = -1;
-	int acceptor = -1;
-	struct sockaddr_in listen_addr;
-	struct sockaddr_in connect_addr;
-	int size;
-	int saved_errno = -1;
-
-	if (protocol
-#ifdef AF_UNIX
-		|| family != AF_UNIX
-#endif
-		) {
-		EVUTIL_SET_SOCKET_ERROR(WSAEAFNOSUPPORT);
-		return -1;
-	}
-	if (!fd) {
-		EVUTIL_SET_SOCKET_ERROR(WSAEINVAL);
-		return -1;
-	}
-
-	listener = socket(AF_INET, type, 0);
-	if (listener < 0)
-		return -1;
-	memset(&listen_addr, 0, sizeof(listen_addr));
-	listen_addr.sin_family = AF_INET;
-	listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
-	listen_addr.sin_port = 0;	/* kernel chooses port.	 */
-	if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
-		== -1)
-		goto tidy_up_and_fail;
-	if (listen(listener, 1) == -1)
-		goto tidy_up_and_fail;
-
-	connector = socket(AF_INET, type, 0);
-	if (connector < 0)
-		goto tidy_up_and_fail;
-	/* We want to find out the port number to connect to.  */
-	size = sizeof(connect_addr);
-	if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
-		goto tidy_up_and_fail;
-	if (size != sizeof (connect_addr))
-		goto abort_tidy_up_and_fail;
-	if (connect(connector, (struct sockaddr *) &connect_addr,
-				sizeof(connect_addr)) == -1)
-		goto tidy_up_and_fail;
-
-	size = sizeof(listen_addr);
-	acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
-	if (acceptor < 0)
-		goto tidy_up_and_fail;
-	if (size != sizeof(listen_addr))
-		goto abort_tidy_up_and_fail;
-	EVUTIL_CLOSESOCKET(listener);
-	/* Now check we are talking to ourself by matching port and host on the
-	   two sockets.	 */
-	if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
-		goto tidy_up_and_fail;
-	if (size != sizeof (connect_addr)
-		|| listen_addr.sin_family != connect_addr.sin_family
-		|| listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
-		|| listen_addr.sin_port != connect_addr.sin_port)
-		goto abort_tidy_up_and_fail;
-	fd[0] = connector;
-	fd[1] = acceptor;
-
-	return 0;
-
- abort_tidy_up_and_fail:
-	saved_errno = WSAECONNABORTED;
- tidy_up_and_fail:
-	if (saved_errno < 0)
-		saved_errno = WSAGetLastError();
-	if (listener != -1)
-		EVUTIL_CLOSESOCKET(listener);
-	if (connector != -1)
-		EVUTIL_CLOSESOCKET(connector);
-	if (acceptor != -1)
-		EVUTIL_CLOSESOCKET(acceptor);
-
-	EVUTIL_SET_SOCKET_ERROR(saved_errno);
-	return -1;
-#endif
-}
-
-int
-evutil_make_socket_nonblocking(int fd)
-{
-#ifdef WIN32
-	{
-		unsigned long nonblocking = 1;
-		ioctlsocket(fd, FIONBIO, (unsigned long*) &nonblocking);
-	}
-#else
-	{
-		int flags;
-		if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
-			event_warn("fcntl(%d, F_GETFL)", fd);
-			return -1;
-		}
-		if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
-			event_warn("fcntl(%d, F_SETFL)", fd);
-			return -1;
-		}
-	}
-#endif
-	return 0;
-}
-
-ev_int64_t
-evutil_strtoll(const char *s, char **endptr, int base)
-{
-#ifdef HAVE_STRTOLL
-	return (ev_int64_t)strtoll(s, endptr, base);
-#elif SIZEOF_LONG == 8
-	return (ev_int64_t)strtol(s, endptr, base);
-#elif defined(WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
-	/* XXXX on old versions of MS APIs, we only support base
-	 * 10. */
-	ev_int64_t r;
-	if (base != 10)
-		return 0;
-	r = (ev_int64_t) _atoi64(s);
-	while (isspace(*s))
-		++s;
-	while (isdigit(*s))
-		++s;
-	if (endptr)
-		*endptr = (char*) s;
-	return r;
-#elif defined(WIN32)
-	return (ev_int64_t) _strtoi64(s, endptr, base);
-#else
-#error "I don't know how to parse 64-bit integers."
-#endif
-}
-
-#ifndef _EVENT_HAVE_GETTIMEOFDAY
-int
-evutil_gettimeofday(struct timeval *tv, struct timezone *tz)
-{
-	struct _timeb tb;
-
-	if(tv == NULL)
-		return -1;
-
-	_ftime(&tb);
-	tv->tv_sec = (long) tb.time;
-	tv->tv_usec = ((int) tb.millitm) * 1000;
-	return 0;
-}
-#endif
-
-int
-evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
-{
-	int r;
-	va_list ap;
-	va_start(ap, format);
-	r = evutil_vsnprintf(buf, buflen, format, ap);
-	va_end(ap);
-	return r;
-}
-
-int
-evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
-{
-#ifdef _MSC_VER
-	int r = _vsnprintf(buf, buflen, format, ap);
-	buf[buflen-1] = '\0';
-	if (r >= 0)
-		return r;
-	else
-		return _vscprintf(format, ap);
-#else
-	int r = vsnprintf(buf, buflen, format, ap);
-	buf[buflen-1] = '\0';
-	return r;
-#endif
-}
-
-static int
-evutil_issetugid(void)
-{
-#ifdef _EVENT_HAVE_ISSETUGID
-	return issetugid();
-#else
-
-#ifdef _EVENT_HAVE_GETEUID
-	if (getuid() != geteuid())
-		return 1;
-#endif
-#ifdef _EVENT_HAVE_GETEGID
-	if (getgid() != getegid())
-		return 1;
-#endif
-	return 0;
-#endif
-}
-
-const char *
-evutil_getenv(const char *varname)
-{
-	if (evutil_issetugid())
-		return NULL;
-
-	return getenv(varname);
-}
diff --git a/base/third_party/libevent/evutil.h b/base/third_party/libevent/evutil.h
deleted file mode 100644
index 8b664b9..0000000
--- a/base/third_party/libevent/evutil.h
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright (c) 2007 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef _EVUTIL_H_
-#define _EVUTIL_H_
-
-/** @file evutil.h
-
-  Common convenience functions for cross-platform portability and
-  related socket manipulations.
-
- */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "event-config.h"
-#ifdef _EVENT_HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#ifdef _EVENT_HAVE_STDINT_H
-#include <stdint.h>
-#elif defined(_EVENT_HAVE_INTTYPES_H)
-#include <inttypes.h>
-#endif
-#ifdef _EVENT_HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif
-#include <stdarg.h>
-
-#ifdef _EVENT_HAVE_UINT64_T
-#define ev_uint64_t uint64_t
-#define ev_int64_t int64_t
-#elif defined(WIN32)
-#define ev_uint64_t unsigned __int64
-#define ev_int64_t signed __int64
-#elif _EVENT_SIZEOF_LONG_LONG == 8
-#define ev_uint64_t unsigned long long
-#define ev_int64_t long long
-#elif _EVENT_SIZEOF_LONG == 8
-#define ev_uint64_t unsigned long
-#define ev_int64_t long
-#else
-#error "No way to define ev_uint64_t"
-#endif
-
-#ifdef _EVENT_HAVE_UINT32_T
-#define ev_uint32_t uint32_t
-#elif defined(WIN32)
-#define ev_uint32_t unsigned int
-#elif _EVENT_SIZEOF_LONG == 4
-#define ev_uint32_t unsigned long
-#elif _EVENT_SIZEOF_INT == 4
-#define ev_uint32_t unsigned int
-#else
-#error "No way to define ev_uint32_t"
-#endif
-
-#ifdef _EVENT_HAVE_UINT16_T
-#define ev_uint16_t uint16_t
-#elif defined(WIN32)
-#define ev_uint16_t unsigned short
-#elif _EVENT_SIZEOF_INT == 2
-#define ev_uint16_t unsigned int
-#elif _EVENT_SIZEOF_SHORT == 2
-#define ev_uint16_t unsigned short
-#else
-#error "No way to define ev_uint16_t"
-#endif
-
-#ifdef _EVENT_HAVE_UINT8_T
-#define ev_uint8_t uint8_t
-#else
-#define ev_uint8_t unsigned char
-#endif
-
-int evutil_socketpair(int d, int type, int protocol, int sv[2]);
-int evutil_make_socket_nonblocking(int sock);
-#ifdef WIN32
-#define EVUTIL_CLOSESOCKET(s) closesocket(s)
-#else
-#define EVUTIL_CLOSESOCKET(s) close(s)
-#endif
-
-#ifdef WIN32
-#define EVUTIL_SOCKET_ERROR() WSAGetLastError()
-#define EVUTIL_SET_SOCKET_ERROR(errcode)		\
-	do { WSASetLastError(errcode); } while (0)
-#else
-#define EVUTIL_SOCKET_ERROR() (errno)
-#define EVUTIL_SET_SOCKET_ERROR(errcode)		\
-		do { errno = (errcode); } while (0)
-#endif
-
-/*
- * Manipulation functions for struct timeval
- */
-#ifdef _EVENT_HAVE_TIMERADD
-#define evutil_timeradd(tvp, uvp, vvp) timeradd((tvp), (uvp), (vvp))
-#define evutil_timersub(tvp, uvp, vvp) timersub((tvp), (uvp), (vvp))
-#else
-#define evutil_timeradd(tvp, uvp, vvp)							\
-	do {														\
-		(vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec;			\
-		(vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec;       \
-		if ((vvp)->tv_usec >= 1000000) {						\
-			(vvp)->tv_sec++;									\
-			(vvp)->tv_usec -= 1000000;							\
-		}														\
-	} while (0)
-#define	evutil_timersub(tvp, uvp, vvp)						\
-	do {													\
-		(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;		\
-		(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;	\
-		if ((vvp)->tv_usec < 0) {							\
-			(vvp)->tv_sec--;								\
-			(vvp)->tv_usec += 1000000;						\
-		}													\
-	} while (0)
-#endif /* !_EVENT_HAVE_HAVE_TIMERADD */
-
-#ifdef _EVENT_HAVE_TIMERCLEAR
-#define evutil_timerclear(tvp) timerclear(tvp)
-#else
-#define	evutil_timerclear(tvp)	(tvp)->tv_sec = (tvp)->tv_usec = 0
-#endif
-
-#define	evutil_timercmp(tvp, uvp, cmp)							\
-	(((tvp)->tv_sec == (uvp)->tv_sec) ?							\
-	 ((tvp)->tv_usec cmp (uvp)->tv_usec) :						\
-	 ((tvp)->tv_sec cmp (uvp)->tv_sec))
-
-#ifdef _EVENT_HAVE_TIMERISSET
-#define evutil_timerisset(tvp) timerisset(tvp)
-#else
-#define	evutil_timerisset(tvp)	((tvp)->tv_sec || (tvp)->tv_usec)
-#endif
-
-
-/* big-int related functions */
-ev_int64_t evutil_strtoll(const char *s, char **endptr, int base);
-
-
-#ifdef _EVENT_HAVE_GETTIMEOFDAY
-#define evutil_gettimeofday(tv, tz) gettimeofday((tv), (tz))
-#else
-struct timezone;
-int evutil_gettimeofday(struct timeval *tv, struct timezone *tz);
-#endif
-
-int evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
-#ifdef __GNUC__
-	__attribute__((format(printf, 3, 4)))
-#endif
-	;
-int evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _EVUTIL_H_ */
diff --git a/base/third_party/libevent/freebsd/config.h b/base/third_party/libevent/freebsd/config.h
deleted file mode 100644
index 4fe3d6b..0000000
--- a/base/third_party/libevent/freebsd/config.h
+++ /dev/null
@@ -1,266 +0,0 @@
-/* config.h.  Generated from config.h.in by configure.  */
-/* config.h.in.  Generated from configure.in by autoheader.  */
-
-/* Define if clock_gettime is available in libc */
-#define DNS_USE_CPU_CLOCK_FOR_ID 1
-
-/* Define is no secure id variant is available */
-/* #undef DNS_USE_GETTIMEOFDAY_FOR_ID */
-
-/* Define to 1 if you have the `clock_gettime' function. */
-#define HAVE_CLOCK_GETTIME 1
-
-/* Define if /dev/poll is available */
-/* #undef HAVE_DEVPOLL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if your system supports the epoll system calls */
-/* #undef HAVE_EPOLL */
-
-/* Define to 1 if you have the `epoll_ctl' function. */
-/* #undef HAVE_EPOLL_CTL */
-
-/* Define if your system supports event ports */
-/* #undef HAVE_EVENT_PORTS */
-
-/* Define to 1 if you have the `fcntl' function. */
-#define HAVE_FCNTL 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H 1
-
-/* Define to 1 if the system has the type `fd_mask'. */
-#define HAVE_FD_MASK 1
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#define HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the `getegid' function. */
-#define HAVE_GETEGID 1
-
-/* Define to 1 if you have the `geteuid' function. */
-#define HAVE_GETEUID 1
-
-/* Define to 1 if you have the `getnameinfo' function. */
-#define HAVE_GETNAMEINFO 1
-
-/* Define to 1 if you have the `gettimeofday' function. */
-#define HAVE_GETTIMEOFDAY 1
-
-/* Define to 1 if you have the `inet_ntop' function. */
-#define HAVE_INET_NTOP 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `issetugid' function. */
-#define HAVE_ISSETUGID 1
-
-/* Define to 1 if you have the `kqueue' function. */
-#define HAVE_KQUEUE 1
-
-/* Define to 1 if you have the `nsl' library (-lnsl). */
-/* #undef HAVE_LIBNSL */
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-/* #undef HAVE_LIBRESOLV */
-
-/* Define to 1 if you have the `rt' library (-lrt). */
-#define HAVE_LIBRT 1
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-/* #undef HAVE_LIBSOCKET */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netinet/in6.h> header file. */
-/* #undef HAVE_NETINET_IN6_H */
-
-/* Define to 1 if you have the `poll' function. */
-#define HAVE_POLL 1
-
-/* Define to 1 if you have the <poll.h> header file. */
-#define HAVE_POLL_H 1
-
-/* Define to 1 if you have the `port_create' function. */
-/* #undef HAVE_PORT_CREATE */
-
-/* Define to 1 if you have the <port.h> header file. */
-/* #undef HAVE_PORT_H */
-
-/* Define to 1 if you have the `select' function. */
-#define HAVE_SELECT 1
-
-/* Define if F_SETFD is defined in <fcntl.h> */
-#define HAVE_SETFD 1
-
-/* Define to 1 if you have the `sigaction' function. */
-#define HAVE_SIGACTION 1
-
-/* Define to 1 if you have the `signal' function. */
-#define HAVE_SIGNAL 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the <stdarg.h> header file. */
-#define HAVE_STDARG_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-#define HAVE_STRLCPY 1
-
-/* Define to 1 if you have the `strsep' function. */
-#define HAVE_STRSEP 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-#define HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the `strtoll' function. */
-#define HAVE_STRTOLL 1
-
-/* Define to 1 if the system has the type `struct in6_addr'. */
-#define HAVE_STRUCT_IN6_ADDR 1
-
-/* Define to 1 if you have the <sys/devpoll.h> header file. */
-/* #undef HAVE_SYS_DEVPOLL_H */
-
-/* Define to 1 if you have the <sys/epoll.h> header file. */
-/* #undef HAVE_SYS_EPOLL_H */
-
-/* Define to 1 if you have the <sys/event.h> header file. */
-#define HAVE_SYS_EVENT_H 1
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-#define HAVE_SYS_IOCTL_H 1
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/queue.h> header file. */
-#define HAVE_SYS_QUEUE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#define HAVE_SYS_SELECT_H 1
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
-#define HAVE_TAILQFOREACH 1
-
-/* Define if timeradd is defined in <sys/time.h> */
-#define HAVE_TIMERADD 1
-
-/* Define if timerclear is defined in <sys/time.h> */
-#define HAVE_TIMERCLEAR 1
-
-/* Define if timercmp is defined in <sys/time.h> */
-#define HAVE_TIMERCMP 1
-
-/* Define if timerisset is defined in <sys/time.h> */
-#define HAVE_TIMERISSET 1
-
-/* Define to 1 if the system has the type `uint16_t'. */
-#define HAVE_UINT16_T 1
-
-/* Define to 1 if the system has the type `uint32_t'. */
-#define HAVE_UINT32_T 1
-
-/* Define to 1 if the system has the type `uint64_t'. */
-#define HAVE_UINT64_T 1
-
-/* Define to 1 if the system has the type `uint8_t'. */
-#define HAVE_UINT8_T 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `vasprintf' function. */
-#define HAVE_VASPRINTF 1
-
-/* Define if kqueue works correctly with pipes */
-#define HAVE_WORKING_KQUEUE 1
-
-/* Name of package */
-#define PACKAGE "libevent"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT ""
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME ""
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING ""
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION ""
-
-/* The size of `int', as computed by sizeof. */
-#define SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define SIZEOF_LONG 8
-
-/* The size of `long long', as computed by sizeof. */
-#define SIZEOF_LONG_LONG 8
-
-/* The size of `short', as computed by sizeof. */
-#define SIZEOF_SHORT 2
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define TIME_WITH_SYS_TIME 1
-
-/* Version number of package */
-#define VERSION "1.4.13-stable"
-
-/* Define to appropriate substitue if compiler doesnt have __func__ */
-/* #undef __func__ */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef const */
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
-   calls it, or to nothing if 'inline' is not supported under any name.  */
-#ifndef __cplusplus
-/* #undef inline */
-#endif
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef pid_t */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-/* Define to unsigned int if you dont have it */
-/* #undef socklen_t */
diff --git a/base/third_party/libevent/freebsd/event-config.h b/base/third_party/libevent/freebsd/event-config.h
deleted file mode 100644
index be1eae4..0000000
--- a/base/third_party/libevent/freebsd/event-config.h
+++ /dev/null
@@ -1,284 +0,0 @@
-/* event-config.h
- * Generated by autoconf; post-processed by libevent.
- * Do not edit this file.
- * Do not rely on macros in this file existing in later versions.
- */
-#ifndef _EVENT_CONFIG_H_
-#define _EVENT_CONFIG_H_
-/* config.h.  Generated from config.h.in by configure.  */
-/* config.h.in.  Generated from configure.in by autoheader.  */
-
-/* Define if clock_gettime is available in libc */
-#define _EVENT_DNS_USE_CPU_CLOCK_FOR_ID 1
-
-/* Define is no secure id variant is available */
-/* #undef _EVENT_DNS_USE_GETTIMEOFDAY_FOR_ID */
-
-/* Define to 1 if you have the `clock_gettime' function. */
-#define _EVENT_HAVE_CLOCK_GETTIME 1
-
-/* Define if /dev/poll is available */
-/* #undef _EVENT_HAVE_DEVPOLL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define _EVENT_HAVE_DLFCN_H 1
-
-/* Define if your system supports the epoll system calls */
-/* #undef _EVENT_HAVE_EPOLL */
-
-/* Define to 1 if you have the `epoll_ctl' function. */
-/* #undef _EVENT_HAVE_EPOLL_CTL */
-
-/* Define if your system supports event ports */
-/* #undef _EVENT_HAVE_EVENT_PORTS */
-
-/* Define to 1 if you have the `fcntl' function. */
-#define _EVENT_HAVE_FCNTL 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define _EVENT_HAVE_FCNTL_H 1
-
-/* Define to 1 if the system has the type `fd_mask'. */
-#define _EVENT_HAVE_FD_MASK 1
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#define _EVENT_HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the `getegid' function. */
-#define _EVENT_HAVE_GETEGID 1
-
-/* Define to 1 if you have the `geteuid' function. */
-#define _EVENT_HAVE_GETEUID 1
-
-/* Define to 1 if you have the `getnameinfo' function. */
-#define _EVENT_HAVE_GETNAMEINFO 1
-
-/* Define to 1 if you have the `gettimeofday' function. */
-#define _EVENT_HAVE_GETTIMEOFDAY 1
-
-/* Define to 1 if you have the `inet_ntop' function. */
-#define _EVENT_HAVE_INET_NTOP 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define _EVENT_HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `issetugid' function. */
-#define _EVENT_HAVE_ISSETUGID 1
-
-/* Define to 1 if you have the `kqueue' function. */
-#define _EVENT_HAVE_KQUEUE 1
-
-/* Define to 1 if you have the `nsl' library (-lnsl). */
-/* #undef _EVENT_HAVE_LIBNSL */
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-/* #undef _EVENT_HAVE_LIBRESOLV */
-
-/* Define to 1 if you have the `rt' library (-lrt). */
-#define _EVENT_HAVE_LIBRT 1
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-/* #undef _EVENT_HAVE_LIBSOCKET */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define _EVENT_HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netinet/in6.h> header file. */
-/* #undef _EVENT_HAVE_NETINET_IN6_H */
-
-/* Define to 1 if you have the `poll' function. */
-#define _EVENT_HAVE_POLL 1
-
-/* Define to 1 if you have the <poll.h> header file. */
-#define _EVENT_HAVE_POLL_H 1
-
-/* Define to 1 if you have the `port_create' function. */
-/* #undef _EVENT_HAVE_PORT_CREATE */
-
-/* Define to 1 if you have the <port.h> header file. */
-/* #undef _EVENT_HAVE_PORT_H */
-
-/* Define to 1 if you have the `select' function. */
-#define _EVENT_HAVE_SELECT 1
-
-/* Define if F_SETFD is defined in <fcntl.h> */
-#define _EVENT_HAVE_SETFD 1
-
-/* Define to 1 if you have the `sigaction' function. */
-#define _EVENT_HAVE_SIGACTION 1
-
-/* Define to 1 if you have the `signal' function. */
-#define _EVENT_HAVE_SIGNAL 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define _EVENT_HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the <stdarg.h> header file. */
-#define _EVENT_HAVE_STDARG_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define _EVENT_HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define _EVENT_HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define _EVENT_HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define _EVENT_HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-#define _EVENT_HAVE_STRLCPY 1
-
-/* Define to 1 if you have the `strsep' function. */
-#define _EVENT_HAVE_STRSEP 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-#define _EVENT_HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the `strtoll' function. */
-#define _EVENT_HAVE_STRTOLL 1
-
-/* Define to 1 if the system has the type `struct in6_addr'. */
-#define _EVENT_HAVE_STRUCT_IN6_ADDR 1
-
-/* Define to 1 if you have the <sys/devpoll.h> header file. */
-/* #undef _EVENT_HAVE_SYS_DEVPOLL_H */
-
-/* Define to 1 if you have the <sys/epoll.h> header file. */
-/* #undef _EVENT_HAVE_SYS_EPOLL_H */
-
-/* Define to 1 if you have the <sys/event.h> header file. */
-#define _EVENT_HAVE_SYS_EVENT_H 1
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-#define _EVENT_HAVE_SYS_IOCTL_H 1
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define _EVENT_HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/queue.h> header file. */
-#define _EVENT_HAVE_SYS_QUEUE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#define _EVENT_HAVE_SYS_SELECT_H 1
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define _EVENT_HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define _EVENT_HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define _EVENT_HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define _EVENT_HAVE_SYS_TYPES_H 1
-
-/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
-#define _EVENT_HAVE_TAILQFOREACH 1
-
-/* Define if timeradd is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERADD 1
-
-/* Define if timerclear is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERCLEAR 1
-
-/* Define if timercmp is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERCMP 1
-
-/* Define if timerisset is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERISSET 1
-
-/* Define to 1 if the system has the type `uint16_t'. */
-#define _EVENT_HAVE_UINT16_T 1
-
-/* Define to 1 if the system has the type `uint32_t'. */
-#define _EVENT_HAVE_UINT32_T 1
-
-/* Define to 1 if the system has the type `uint64_t'. */
-#define _EVENT_HAVE_UINT64_T 1
-
-/* Define to 1 if the system has the type `uint8_t'. */
-#define _EVENT_HAVE_UINT8_T 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define _EVENT_HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `vasprintf' function. */
-#define _EVENT_HAVE_VASPRINTF 1
-
-/* Define if kqueue works correctly with pipes */
-#define _EVENT_HAVE_WORKING_KQUEUE 1
-
-/* Define to the sub-directory in which libtool stores uninstalled libraries.
-   */
-#define _EVENT_LT_OBJDIR ".libs/"
-
-/* Numeric representation of the version */
-#define _EVENT_NUMERIC_VERSION 0x01040f00
-
-/* Name of package */
-#define _EVENT_PACKAGE "libevent"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define _EVENT_PACKAGE_BUGREPORT ""
-
-/* Define to the full name of this package. */
-#define _EVENT_PACKAGE_NAME ""
-
-/* Define to the full name and version of this package. */
-#define _EVENT_PACKAGE_STRING ""
-
-/* Define to the one symbol short name of this package. */
-#define _EVENT_PACKAGE_TARNAME ""
-
-/* Define to the home page for this package. */
-#define _EVENT_PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define _EVENT_PACKAGE_VERSION ""
-
-/* The size of `int', as computed by sizeof. */
-#define _EVENT_SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG 8
-
-/* The size of `long long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG_LONG 8
-
-/* The size of `short', as computed by sizeof. */
-#define _EVENT_SIZEOF_SHORT 2
-
-/* Define to 1 if you have the ANSI C header files. */
-#define _EVENT_STDC_HEADERS 1
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define _EVENT_TIME_WITH_SYS_TIME 1
-
-/* Version number of package */
-#define _EVENT_VERSION "1.4.15"
-
-/* Define to appropriate substitue if compiler doesnt have __func__ */
-/* #undef _EVENT___func__ */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef _EVENT_const */
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
-   calls it, or to nothing if 'inline' is not supported under any name.  */
-#ifndef _EVENT___cplusplus
-/* #undef _EVENT_inline */
-#endif
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef _EVENT_pid_t */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef _EVENT_size_t */
-
-/* Define to unsigned int if you dont have it */
-/* #undef _EVENT_socklen_t */
-#endif
diff --git a/base/third_party/libevent/http-internal.h b/base/third_party/libevent/http-internal.h
deleted file mode 100644
index 1c4c3db..0000000
--- a/base/third_party/libevent/http-internal.h
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright 2001 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * This header file contains definitions for dealing with HTTP requests
- * that are internal to libevent.  As user of the library, you should not
- * need to know about these.
- */
-
-#ifndef _HTTP_H_
-#define _HTTP_H_
-
-#define HTTP_CONNECT_TIMEOUT	45
-#define HTTP_WRITE_TIMEOUT	50
-#define HTTP_READ_TIMEOUT	50
-
-#define HTTP_PREFIX		"http://"
-#define HTTP_DEFAULTPORT	80
-
-enum message_read_status {
-	ALL_DATA_READ = 1,
-	MORE_DATA_EXPECTED = 0,
-	DATA_CORRUPTED = -1,
-	REQUEST_CANCELED = -2
-};
-
-enum evhttp_connection_error {
-	EVCON_HTTP_TIMEOUT,
-	EVCON_HTTP_EOF,
-	EVCON_HTTP_INVALID_HEADER
-};
-
-struct evbuffer;
-struct evhttp_request;
-
-/* A stupid connection object - maybe make this a bufferevent later */
-
-enum evhttp_connection_state {
-	EVCON_DISCONNECTED,	/**< not currently connected not trying either*/
-	EVCON_CONNECTING,	/**< tries to currently connect */
-	EVCON_IDLE,		/**< connection is established */
-	EVCON_READING_FIRSTLINE,/**< reading Request-Line (incoming conn) or
-				 **< Status-Line (outgoing conn) */
-	EVCON_READING_HEADERS,	/**< reading request/response headers */
-	EVCON_READING_BODY,	/**< reading request/response body */
-	EVCON_READING_TRAILER,	/**< reading request/response chunked trailer */
-	EVCON_WRITING		/**< writing request/response headers/body */
-};
-
-struct event_base;
-
-struct evhttp_connection {
-	/* we use tailq only if they were created for an http server */
-	TAILQ_ENTRY(evhttp_connection) (next);
-
-	int fd;
-	struct event ev;
-	struct event close_ev;
-	struct evbuffer *input_buffer;
-	struct evbuffer *output_buffer;
-	
-	char *bind_address;		/* address to use for binding the src */
-	u_short bind_port;		/* local port for binding the src */
-
-	char *address;			/* address to connect to */
-	u_short port;
-
-	int flags;
-#define EVHTTP_CON_INCOMING	0x0001	/* only one request on it ever */
-#define EVHTTP_CON_OUTGOING	0x0002  /* multiple requests possible */
-#define EVHTTP_CON_CLOSEDETECT  0x0004  /* detecting if persistent close */
-
-	int timeout;			/* timeout in seconds for events */
-	int retry_cnt;			/* retry count */
-	int retry_max;			/* maximum number of retries */
-	
-	enum evhttp_connection_state state;
-
-	/* for server connections, the http server they are connected with */
-	struct evhttp *http_server;
-
-	TAILQ_HEAD(evcon_requestq, evhttp_request) requests;
-	
-						   void (*cb)(struct evhttp_connection *, void *);
-	void *cb_arg;
-	
-	void (*closecb)(struct evhttp_connection *, void *);
-	void *closecb_arg;
-
-	struct event_base *base;
-};
-
-struct evhttp_cb {
-	TAILQ_ENTRY(evhttp_cb) next;
-
-	char *what;
-
-	void (*cb)(struct evhttp_request *req, void *);
-	void *cbarg;
-};
-
-/* both the http server as well as the rpc system need to queue connections */
-TAILQ_HEAD(evconq, evhttp_connection);
-
-/* each bound socket is stored in one of these */
-struct evhttp_bound_socket {
-	TAILQ_ENTRY(evhttp_bound_socket) (next);
-
-	struct event  bind_ev;
-};
-
-struct evhttp {
-	TAILQ_HEAD(boundq, evhttp_bound_socket) sockets;
-
-	TAILQ_HEAD(httpcbq, evhttp_cb) callbacks;
-        struct evconq connections;
-
-        int timeout;
-
-	void (*gencb)(struct evhttp_request *req, void *);
-	void *gencbarg;
-
-	struct event_base *base;
-};
-
-/* resets the connection; can be reused for more requests */
-void evhttp_connection_reset(struct evhttp_connection *);
-
-/* connects if necessary */
-int evhttp_connection_connect(struct evhttp_connection *);
-
-/* notifies the current request that it failed; resets connection */
-void evhttp_connection_fail(struct evhttp_connection *,
-    enum evhttp_connection_error error);
-
-void evhttp_get_request(struct evhttp *, int, struct sockaddr *, socklen_t);
-
-int evhttp_hostportfile(char *, char **, u_short *, char **);
-
-int evhttp_parse_firstline(struct evhttp_request *, struct evbuffer*);
-int evhttp_parse_headers(struct evhttp_request *, struct evbuffer*);
-
-void evhttp_start_read(struct evhttp_connection *);
-void evhttp_make_header(struct evhttp_connection *, struct evhttp_request *);
-
-void evhttp_write_buffer(struct evhttp_connection *,
-    void (*)(struct evhttp_connection *, void *), void *);
-
-/* response sending HTML the data in the buffer */
-void evhttp_response_code(struct evhttp_request *, int, const char *);
-void evhttp_send_page(struct evhttp_request *, struct evbuffer *);
-
-#endif /* _HTTP_H */
diff --git a/base/third_party/libevent/http.c b/base/third_party/libevent/http.c
deleted file mode 100644
index 4abce23..0000000
--- a/base/third_party/libevent/http.c
+++ /dev/null
@@ -1,2885 +0,0 @@
-/*
- * Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif
-#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif
-
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#ifdef HAVE_SYS_IOCCOM_H
-#include <sys/ioccom.h>
-#endif
-
-#ifndef WIN32
-#include <sys/resource.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/wait.h>
-#endif
-
-#include <sys/queue.h>
-
-#ifndef WIN32
-#include <netinet/in.h>
-#include <netdb.h>
-#endif
-
-#ifdef WIN32
-#include <winsock2.h>
-#endif
-
-#include <assert.h>
-#include <ctype.h>
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#ifndef WIN32
-#include <syslog.h>
-#endif
-#include <signal.h>
-#include <time.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif
-
-#undef timeout_pending
-#undef timeout_initialized
-
-#include "strlcpy-internal.h"
-#include "event.h"
-#include "evhttp.h"
-#include "evutil.h"
-#include "log.h"
-#include "http-internal.h"
-
-#ifdef WIN32
-#define strcasecmp _stricmp
-#define strncasecmp _strnicmp
-#define strdup _strdup
-#endif
-
-#ifndef HAVE_GETNAMEINFO
-#define NI_MAXSERV 32
-#define NI_MAXHOST 1025
-
-#ifndef NI_NUMERICHOST
-#define NI_NUMERICHOST 1
-#endif
-
-#ifndef NI_NUMERICSERV
-#define NI_NUMERICSERV 2
-#endif
-
-static int
-fake_getnameinfo(const struct sockaddr *sa, size_t salen, char *host, 
-	size_t hostlen, char *serv, size_t servlen, int flags)
-{
-        struct sockaddr_in *sin = (struct sockaddr_in *)sa;
-        
-        if (serv != NULL) {
-				char tmpserv[16];
-				evutil_snprintf(tmpserv, sizeof(tmpserv),
-					"%d", ntohs(sin->sin_port));
-                if (strlcpy(serv, tmpserv, servlen) >= servlen)
-                        return (-1);
-        }
-
-        if (host != NULL) {
-                if (flags & NI_NUMERICHOST) {
-                        if (strlcpy(host, inet_ntoa(sin->sin_addr),
-                            hostlen) >= hostlen)
-                                return (-1);
-                        else
-                                return (0);
-                } else {
-						struct hostent *hp;
-                        hp = gethostbyaddr((char *)&sin->sin_addr, 
-                            sizeof(struct in_addr), AF_INET);
-                        if (hp == NULL)
-                                return (-2);
-                        
-                        if (strlcpy(host, hp->h_name, hostlen) >= hostlen)
-                                return (-1);
-                        else
-                                return (0);
-                }
-        }
-        return (0);
-}
-
-#endif
-
-#ifndef HAVE_GETADDRINFO
-/* Apparently msvc2010 does have an addrinfo definition visible here */
-#if !defined(WIN32) || !defined(_MSC_VER) || (_MSC_VER < 1600)
-struct addrinfo {
-	int ai_family;
-	int ai_socktype;
-	int ai_protocol;
-	size_t ai_addrlen;
-	struct sockaddr *ai_addr;
-	struct addrinfo *ai_next;
-};
-#endif
-static int
-fake_getaddrinfo(const char *hostname, struct addrinfo *ai)
-{
-	struct hostent *he = NULL;
-	struct sockaddr_in *sa;
-	if (hostname) {
-		he = gethostbyname(hostname);
-		if (!he)
-			return (-1);
-	}
-	ai->ai_family = he ? he->h_addrtype : AF_INET;
-	ai->ai_socktype = SOCK_STREAM;
-	ai->ai_protocol = 0;
-	ai->ai_addrlen = sizeof(struct sockaddr_in);
-	if (NULL == (ai->ai_addr = malloc(ai->ai_addrlen)))
-		return (-1);
-	sa = (struct sockaddr_in*)ai->ai_addr;
-	memset(sa, 0, ai->ai_addrlen);
-	if (he) {
-		sa->sin_family = he->h_addrtype;
-		memcpy(&sa->sin_addr, he->h_addr_list[0], he->h_length);
-	} else {
-		sa->sin_family = AF_INET;
-		sa->sin_addr.s_addr = INADDR_ANY;
-	}
-	ai->ai_next = NULL;
-	return (0);
-}
-static void
-fake_freeaddrinfo(struct addrinfo *ai)
-{
-	free(ai->ai_addr);
-}
-#endif
-
-#ifndef MIN
-#define MIN(a,b) (((a)<(b))?(a):(b))
-#endif
-
-/* wrapper for setting the base from the http server */
-#define EVHTTP_BASE_SET(x, y) do { \
-	if ((x)->base != NULL) event_base_set((x)->base, y);	\
-} while (0) 
-
-extern int debug;
-
-static int socket_connect(int fd, const char *address, unsigned short port);
-static int bind_socket_ai(struct addrinfo *, int reuse);
-static int bind_socket(const char *, u_short, int reuse);
-static void name_from_addr(struct sockaddr *, socklen_t, char **, char **);
-static int evhttp_associate_new_request_with_connection(
-	struct evhttp_connection *evcon);
-static void evhttp_connection_start_detectclose(
-	struct evhttp_connection *evcon);
-static void evhttp_connection_stop_detectclose(
-	struct evhttp_connection *evcon);
-static void evhttp_request_dispatch(struct evhttp_connection* evcon);
-static void evhttp_read_firstline(struct evhttp_connection *evcon,
-				  struct evhttp_request *req);
-static void evhttp_read_header(struct evhttp_connection *evcon,
-    struct evhttp_request *req);
-static int evhttp_add_header_internal(struct evkeyvalq *headers,
-    const char *key, const char *value);
-static int evhttp_decode_uri_internal(const char *uri, size_t length,
-    char *ret, int always_decode_plus);
-
-void evhttp_read(int, short, void *);
-void evhttp_write(int, short, void *);
-
-#ifndef HAVE_STRSEP
-/* strsep replacement for platforms that lack it.  Only works if
- * del is one character long. */
-static char *
-strsep(char **s, const char *del)
-{
-	char *d, *tok;
-	assert(strlen(del) == 1);
-	if (!s || !*s)
-		return NULL;
-	tok = *s;
-	d = strstr(tok, del);
-	if (d) {
-		*d = '\0';
-		*s = d + 1;
-	} else
-		*s = NULL;
-	return tok;
-}
-#endif
-
-static const char *
-html_replace(char ch, char *buf)
-{
-	switch (ch) {
-	case '<':
-		return "&lt;";
-	case '>':
-		return "&gt;";
-	case '"':
-		return "&quot;";
-	case '\'':
-		return "&#039;";
-	case '&':
-		return "&amp;";
-	default:
-		break;
-	}
-
-	/* Echo the character back */
-	buf[0] = ch;
-	buf[1] = '\0';
-	
-	return buf;
-}
-
-/*
- * Replaces <, >, ", ' and & with &lt;, &gt;, &quot;,
- * &#039; and &amp; correspondingly.
- *
- * The returned string needs to be freed by the caller.
- */
-
-char *
-evhttp_htmlescape(const char *html)
-{
-	int i, new_size = 0, old_size = strlen(html);
-	char *escaped_html, *p;
-	char scratch_space[2];
-	
-	for (i = 0; i < old_size; ++i)
-          new_size += strlen(html_replace(html[i], scratch_space));
-
-	p = escaped_html = malloc(new_size + 1);
-	if (escaped_html == NULL)
-		event_err(1, "%s: malloc(%d)", __func__, new_size + 1);
-	for (i = 0; i < old_size; ++i) {
-		const char *replaced = html_replace(html[i], scratch_space);
-		/* this is length checked */
-		strcpy(p, replaced);
-		p += strlen(replaced);
-	}
-
-	*p = '\0';
-
-	return (escaped_html);
-}
-
-static const char *
-evhttp_method(enum evhttp_cmd_type type)
-{
-	const char *method;
-
-	switch (type) {
-	case EVHTTP_REQ_GET:
-		method = "GET";
-		break;
-	case EVHTTP_REQ_POST:
-		method = "POST";
-		break;
-	case EVHTTP_REQ_HEAD:
-		method = "HEAD";
-		break;
-	default:
-		method = NULL;
-		break;
-	}
-
-	return (method);
-}
-
-static void
-evhttp_add_event(struct event *ev, int timeout, int default_timeout)
-{
-	if (timeout != 0) {
-		struct timeval tv;
-		
-		evutil_timerclear(&tv);
-		tv.tv_sec = timeout != -1 ? timeout : default_timeout;
-		event_add(ev, &tv);
-	} else {
-		event_add(ev, NULL);
-	}
-}
-
-void
-evhttp_write_buffer(struct evhttp_connection *evcon,
-    void (*cb)(struct evhttp_connection *, void *), void *arg)
-{
-	event_debug(("%s: preparing to write buffer\n", __func__));
-
-	/* Set call back */
-	evcon->cb = cb;
-	evcon->cb_arg = arg;
-
-	/* check if the event is already pending */
-	if (event_pending(&evcon->ev, EV_WRITE|EV_TIMEOUT, NULL))
-		event_del(&evcon->ev);
-
-	event_set(&evcon->ev, evcon->fd, EV_WRITE, evhttp_write, evcon);
-	EVHTTP_BASE_SET(evcon, &evcon->ev);
-	evhttp_add_event(&evcon->ev, evcon->timeout, HTTP_WRITE_TIMEOUT);
-}
-
-static int
-evhttp_connected(struct evhttp_connection *evcon)
-{
-	switch (evcon->state) {
-	case EVCON_DISCONNECTED:
-	case EVCON_CONNECTING:
-		return (0);
-	case EVCON_IDLE:
-	case EVCON_READING_FIRSTLINE:
-	case EVCON_READING_HEADERS:
-	case EVCON_READING_BODY:
-	case EVCON_READING_TRAILER:
-	case EVCON_WRITING:
-	default:
-		return (1);
-	}
-}
-
-/*
- * Create the headers needed for an HTTP request
- */
-static void
-evhttp_make_header_request(struct evhttp_connection *evcon,
-    struct evhttp_request *req)
-{
-	const char *method;
-	
-	evhttp_remove_header(req->output_headers, "Proxy-Connection");
-
-	/* Generate request line */
-	method = evhttp_method(req->type);
-	evbuffer_add_printf(evcon->output_buffer, "%s %s HTTP/%d.%d\r\n",
-	    method, req->uri, req->major, req->minor);
-
-	/* Add the content length on a post request if missing */
-	if (req->type == EVHTTP_REQ_POST &&
-	    evhttp_find_header(req->output_headers, "Content-Length") == NULL){
-		char size[22];
-		evutil_snprintf(size, sizeof(size), "%ld",
-		    (long)EVBUFFER_LENGTH(req->output_buffer));
-		evhttp_add_header(req->output_headers, "Content-Length", size);
-	}
-}
-
-static int
-evhttp_is_connection_close(int flags, struct evkeyvalq* headers)
-{
-	if (flags & EVHTTP_PROXY_REQUEST) {
-		/* proxy connection */
-		const char *connection = evhttp_find_header(headers, "Proxy-Connection");
-		return (connection == NULL || strcasecmp(connection, "keep-alive") != 0);
-	} else {
-		const char *connection = evhttp_find_header(headers, "Connection");
-		return (connection != NULL && strcasecmp(connection, "close") == 0);
-	}
-}
-
-static int
-evhttp_is_connection_keepalive(struct evkeyvalq* headers)
-{
-	const char *connection = evhttp_find_header(headers, "Connection");
-	return (connection != NULL 
-	    && strncasecmp(connection, "keep-alive", 10) == 0);
-}
-
-static void
-evhttp_maybe_add_date_header(struct evkeyvalq *headers)
-{
-	if (evhttp_find_header(headers, "Date") == NULL) {
-		char date[50];
-#ifndef WIN32
-		struct tm cur;
-#endif
-		struct tm *cur_p;
-		time_t t = time(NULL);
-#ifdef WIN32
-		cur_p = gmtime(&t);
-#else
-		gmtime_r(&t, &cur);
-		cur_p = &cur;
-#endif
-		if (strftime(date, sizeof(date),
-			"%a, %d %b %Y %H:%M:%S GMT", cur_p) != 0) {
-			evhttp_add_header(headers, "Date", date);
-		}
-	}
-}
-
-static void
-evhttp_maybe_add_content_length_header(struct evkeyvalq *headers,
-    long content_length)
-{
-	if (evhttp_find_header(headers, "Transfer-Encoding") == NULL &&
-	    evhttp_find_header(headers,	"Content-Length") == NULL) {
-		char len[22];
-		evutil_snprintf(len, sizeof(len), "%ld", content_length);
-		evhttp_add_header(headers, "Content-Length", len);
-	}
-}
-
-/*
- * Create the headers needed for an HTTP reply
- */
-
-static void
-evhttp_make_header_response(struct evhttp_connection *evcon,
-    struct evhttp_request *req)
-{
-	int is_keepalive = evhttp_is_connection_keepalive(req->input_headers);
-	evbuffer_add_printf(evcon->output_buffer, "HTTP/%d.%d %d %s\r\n",
-	    req->major, req->minor, req->response_code,
-	    req->response_code_line);
-
-	if (req->major == 1) {
-		if (req->minor == 1)
-			evhttp_maybe_add_date_header(req->output_headers);
-
-		/*
-		 * if the protocol is 1.0; and the connection was keep-alive
-		 * we need to add a keep-alive header, too.
-		 */
-		if (req->minor == 0 && is_keepalive)
-			evhttp_add_header(req->output_headers,
-			    "Connection", "keep-alive");
-
-		if (req->minor == 1 || is_keepalive) {
-			/* 
-			 * we need to add the content length if the
-			 * user did not give it, this is required for
-			 * persistent connections to work.
-			 */
-			evhttp_maybe_add_content_length_header(
-				req->output_headers,
-				(long)EVBUFFER_LENGTH(req->output_buffer));
-		}
-	}
-
-	/* Potentially add headers for unidentified content. */
-	if (EVBUFFER_LENGTH(req->output_buffer)) {
-		if (evhttp_find_header(req->output_headers,
-			"Content-Type") == NULL) {
-			evhttp_add_header(req->output_headers,
-			    "Content-Type", "text/html; charset=ISO-8859-1");
-		}
-	}
-
-	/* if the request asked for a close, we send a close, too */
-	if (evhttp_is_connection_close(req->flags, req->input_headers)) {
-		evhttp_remove_header(req->output_headers, "Connection");
-		if (!(req->flags & EVHTTP_PROXY_REQUEST))
-		    evhttp_add_header(req->output_headers, "Connection", "close");
-		evhttp_remove_header(req->output_headers, "Proxy-Connection");
-	}
-}
-
-void
-evhttp_make_header(struct evhttp_connection *evcon, struct evhttp_request *req)
-{
-	struct evkeyval *header;
-
-	/*
-	 * Depending if this is a HTTP request or response, we might need to
-	 * add some new headers or remove existing headers.
-	 */
-	if (req->kind == EVHTTP_REQUEST) {
-		evhttp_make_header_request(evcon, req);
-	} else {
-		evhttp_make_header_response(evcon, req);
-	}
-
-	TAILQ_FOREACH(header, req->output_headers, next) {
-		evbuffer_add_printf(evcon->output_buffer, "%s: %s\r\n",
-		    header->key, header->value);
-	}
-	evbuffer_add(evcon->output_buffer, "\r\n", 2);
-
-	if (EVBUFFER_LENGTH(req->output_buffer) > 0) {
-		/*
-		 * For a request, we add the POST data, for a reply, this
-		 * is the regular data.
-		 */
-		evbuffer_add_buffer(evcon->output_buffer, req->output_buffer);
-	}
-}
-
-/* Separated host, port and file from URI */
-
-int
-evhttp_hostportfile(char *url, char **phost, u_short *pport, char **pfile)
-{
-	/* XXX not threadsafe. */
-	static char host[1024];
-	static char file[1024];
-	char *p;
-	const char *p2;
-	int len;
-	u_short port;
-
-	len = strlen(HTTP_PREFIX);
-	if (strncasecmp(url, HTTP_PREFIX, len))
-		return (-1);
-
-	url += len;
-
-	/* We might overrun */
-	if (strlcpy(host, url, sizeof (host)) >= sizeof(host))
-		return (-1);
-
-	p = strchr(host, '/');
-	if (p != NULL) {
-		*p = '\0';
-		p2 = p + 1;
-	} else
-		p2 = NULL;
-
-	if (pfile != NULL) {
-		/* Generate request file */
-		if (p2 == NULL)
-			p2 = "";
-		evutil_snprintf(file, sizeof(file), "/%s", p2);
-	}
-
-	p = strchr(host, ':');
-	if (p != NULL) {
-		*p = '\0';
-		port = atoi(p + 1);
-
-		if (port == 0)
-			return (-1);
-	} else
-		port = HTTP_DEFAULTPORT;
-
-	if (phost != NULL)
-		*phost = host;
-	if (pport != NULL)
-		*pport = port;
-	if (pfile != NULL)
-		*pfile = file;
-
-	return (0);
-}
-
-static int
-evhttp_connection_incoming_fail(struct evhttp_request *req,
-    enum evhttp_connection_error error)
-{
-	switch (error) {
-	case EVCON_HTTP_TIMEOUT:
-	case EVCON_HTTP_EOF:
-		/* 
-		 * these are cases in which we probably should just
-		 * close the connection and not send a reply.  this
-		 * case may happen when a browser keeps a persistent
-		 * connection open and we timeout on the read.  when
-		 * the request is still being used for sending, we
-		 * need to disassociated it from the connection here.
-		 */
-		if (!req->userdone) {
-			/* remove it so that it will not be freed */
-			TAILQ_REMOVE(&req->evcon->requests, req, next);
-			/* indicate that this request no longer has a
-			 * connection object
-			 */
-			req->evcon = NULL;
-		}
-		return (-1);
-	case EVCON_HTTP_INVALID_HEADER:
-	default:	/* xxx: probably should just error on default */
-		/* the callback looks at the uri to determine errors */
-		if (req->uri) {
-			free(req->uri);
-			req->uri = NULL;
-		}
-
-		/* 
-		 * the callback needs to send a reply, once the reply has
-		 * been send, the connection should get freed.
-		 */
-		(*req->cb)(req, req->cb_arg);
-	}
-	
-	return (0);
-}
-
-void
-evhttp_connection_fail(struct evhttp_connection *evcon,
-    enum evhttp_connection_error error)
-{
-	struct evhttp_request* req = TAILQ_FIRST(&evcon->requests);
-	void (*cb)(struct evhttp_request *, void *);
-	void *cb_arg;
-	assert(req != NULL);
-	
-	if (evcon->flags & EVHTTP_CON_INCOMING) {
-		/* 
-		 * for incoming requests, there are two different
-		 * failure cases.  it's either a network level error
-		 * or an http layer error. for problems on the network
-		 * layer like timeouts we just drop the connections.
-		 * For HTTP problems, we might have to send back a
-		 * reply before the connection can be freed.
-		 */
-		if (evhttp_connection_incoming_fail(req, error) == -1)
-			evhttp_connection_free(evcon);
-		return;
-	}
-
-	/* save the callback for later; the cb might free our object */
-	cb = req->cb;
-	cb_arg = req->cb_arg;
-
-	/* do not fail all requests; the next request is going to get
-	 * send over a new connection.   when a user cancels a request,
-	 * all other pending requests should be processed as normal
-	 */
-	TAILQ_REMOVE(&evcon->requests, req, next);
-	evhttp_request_free(req);
-
-	/* reset the connection */
-	evhttp_connection_reset(evcon);
-	
-	/* We are trying the next request that was queued on us */
-	if (TAILQ_FIRST(&evcon->requests) != NULL)
-		evhttp_connection_connect(evcon);
-
-	/* inform the user */
-	if (cb != NULL)
-		(*cb)(NULL, cb_arg);
-}
-
-void
-evhttp_write(int fd, short what, void *arg)
-{
-	struct evhttp_connection *evcon = arg;
-	int n;
-
-	if (what == EV_TIMEOUT) {
-		evhttp_connection_fail(evcon, EVCON_HTTP_TIMEOUT);
-		return;
-	}
-
-	n = evbuffer_write(evcon->output_buffer, fd);
-	if (n == -1) {
-		event_debug(("%s: evbuffer_write", __func__));
-		evhttp_connection_fail(evcon, EVCON_HTTP_EOF);
-		return;
-	}
-
-	if (n == 0) {
-		event_debug(("%s: write nothing", __func__));
-		evhttp_connection_fail(evcon, EVCON_HTTP_EOF);
-		return;
-	}
-
-	if (EVBUFFER_LENGTH(evcon->output_buffer) != 0) {
-		evhttp_add_event(&evcon->ev, 
-		    evcon->timeout, HTTP_WRITE_TIMEOUT);
-		return;
-	}
-
-	/* Activate our call back */
-	if (evcon->cb != NULL)
-		(*evcon->cb)(evcon, evcon->cb_arg);
-}
-
-/**
- * Advance the connection state.
- * - If this is an outgoing connection, we've just processed the response;
- *   idle or close the connection.
- * - If this is an incoming connection, we've just processed the request;
- *   respond.
- */
-static void
-evhttp_connection_done(struct evhttp_connection *evcon)
-{
-	struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
-	int con_outgoing = evcon->flags & EVHTTP_CON_OUTGOING;
-
-	if (con_outgoing) {
-		/* idle or close the connection */
-	        int need_close;
-		TAILQ_REMOVE(&evcon->requests, req, next);
-		req->evcon = NULL;
-
-		evcon->state = EVCON_IDLE;
-
-		need_close = 
-		    evhttp_is_connection_close(req->flags, req->input_headers)||
-		    evhttp_is_connection_close(req->flags, req->output_headers);
-
-		/* check if we got asked to close the connection */
-		if (need_close)
-			evhttp_connection_reset(evcon);
-
-		if (TAILQ_FIRST(&evcon->requests) != NULL) {
-			/*
-			 * We have more requests; reset the connection
-			 * and deal with the next request.
-			 */
-			if (!evhttp_connected(evcon))
-				evhttp_connection_connect(evcon);
-			else
-				evhttp_request_dispatch(evcon);
-		} else if (!need_close) {
-			/*
-			 * The connection is going to be persistent, but we
-			 * need to detect if the other side closes it.
-			 */
-			evhttp_connection_start_detectclose(evcon);
-		}
-	} else if (evcon->state != EVCON_DISCONNECTED) {
-		/*
-		 * incoming connection - we need to leave the request on the
-		 * connection so that we can reply to it.
-		 */
-		evcon->state = EVCON_WRITING;
-	}
-
-	/* notify the user of the request */
-	(*req->cb)(req, req->cb_arg);
-
-	/* if this was an outgoing request, we own and it's done. so free it */
-	if (con_outgoing) {
-		evhttp_request_free(req);
-	}
-}
-
-/*
- * Handles reading from a chunked request.
- *   return ALL_DATA_READ:
- *     all data has been read
- *   return MORE_DATA_EXPECTED:
- *     more data is expected
- *   return DATA_CORRUPTED:
- *     data is corrupted
- *   return REQUEST_CANCLED:
- *     request was canceled by the user calling evhttp_cancel_request
- */
-
-static enum message_read_status
-evhttp_handle_chunked_read(struct evhttp_request *req, struct evbuffer *buf)
-{
-	int len;
-
-	while ((len = EVBUFFER_LENGTH(buf)) > 0) {
-		if (req->ntoread < 0) {
-			/* Read chunk size */
-			ev_int64_t ntoread;
-			char *p = evbuffer_readline(buf);
-			char *endp;
-			int error;
-			if (p == NULL)
-				break;
-			/* the last chunk is on a new line? */
-			if (strlen(p) == 0) {
-				free(p);
-				continue;
-			}
-			ntoread = evutil_strtoll(p, &endp, 16);
-			error = (*p == '\0' ||
-			    (*endp != '\0' && *endp != ' ') ||
-			    ntoread < 0);
-			free(p);
-			if (error) {
-				/* could not get chunk size */
-				return (DATA_CORRUPTED);
-			}
-			req->ntoread = ntoread;
-			if (req->ntoread == 0) {
-				/* Last chunk */
-				return (ALL_DATA_READ);
-			}
-			continue;
-		}
-
-		/* don't have enough to complete a chunk; wait for more */
-		if (len < req->ntoread)
-			return (MORE_DATA_EXPECTED);
-
-		/* Completed chunk */
-		evbuffer_add(req->input_buffer,
-		    EVBUFFER_DATA(buf), (size_t)req->ntoread);
-		evbuffer_drain(buf, (size_t)req->ntoread);
-		req->ntoread = -1;
-		if (req->chunk_cb != NULL) {
-			(*req->chunk_cb)(req, req->cb_arg);
-			evbuffer_drain(req->input_buffer,
-			    EVBUFFER_LENGTH(req->input_buffer));
-		}
-	}
-
-	return (MORE_DATA_EXPECTED);
-}
-
-static void
-evhttp_read_trailer(struct evhttp_connection *evcon, struct evhttp_request *req)
-{
-	struct evbuffer *buf = evcon->input_buffer;
-
-	switch (evhttp_parse_headers(req, buf)) {
-	case DATA_CORRUPTED:
-		evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
-		break;
-	case ALL_DATA_READ:
-		event_del(&evcon->ev);
-		evhttp_connection_done(evcon);
-		break;
-	case MORE_DATA_EXPECTED:
-	default:
-		evhttp_add_event(&evcon->ev, evcon->timeout,
-		    HTTP_READ_TIMEOUT);
-		break;
-	}
-}
-
-static void
-evhttp_read_body(struct evhttp_connection *evcon, struct evhttp_request *req)
-{
-	struct evbuffer *buf = evcon->input_buffer;
-	
-	if (req->chunked) {
-		switch (evhttp_handle_chunked_read(req, buf)) {
-		case ALL_DATA_READ:
-			/* finished last chunk */
-			evcon->state = EVCON_READING_TRAILER;
-			evhttp_read_trailer(evcon, req);
-			return;
-		case DATA_CORRUPTED:
-			/* corrupted data */
-			evhttp_connection_fail(evcon,
-			    EVCON_HTTP_INVALID_HEADER);
-			return;
-		case REQUEST_CANCELED:
-			/* request canceled */
-			evhttp_request_free(req);
-			return;
-		case MORE_DATA_EXPECTED:
-		default:
-			break;
-		}
-	} else if (req->ntoread < 0) {
-		/* Read until connection close. */
-		evbuffer_add_buffer(req->input_buffer, buf);
-	} else if (EVBUFFER_LENGTH(buf) >= req->ntoread) {
-		/* Completed content length */
-		evbuffer_add(req->input_buffer, EVBUFFER_DATA(buf),
-		    (size_t)req->ntoread);
-		evbuffer_drain(buf, (size_t)req->ntoread);
-		req->ntoread = 0;
-		evhttp_connection_done(evcon);
-		return;
-	}
-	/* Read more! */
-	event_set(&evcon->ev, evcon->fd, EV_READ, evhttp_read, evcon);
-	EVHTTP_BASE_SET(evcon, &evcon->ev);
-	evhttp_add_event(&evcon->ev, evcon->timeout, HTTP_READ_TIMEOUT);
-}
-
-/*
- * Reads data into a buffer structure until no more data
- * can be read on the file descriptor or we have read all
- * the data that we wanted to read.
- * Execute callback when done.
- */
-
-void
-evhttp_read(int fd, short what, void *arg)
-{
-	struct evhttp_connection *evcon = arg;
-	struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
-	struct evbuffer *buf = evcon->input_buffer;
-	int n, len;
-
-	if (what == EV_TIMEOUT) {
-		evhttp_connection_fail(evcon, EVCON_HTTP_TIMEOUT);
-		return;
-	}
-	n = evbuffer_read(buf, fd, -1);
-	len = EVBUFFER_LENGTH(buf);
-	event_debug(("%s: got %d on %d\n", __func__, n, fd));
-	
-	if (n == -1) {
-		if (errno != EINTR && errno != EAGAIN) {
-			event_debug(("%s: evbuffer_read", __func__));
-			evhttp_connection_fail(evcon, EVCON_HTTP_EOF);
-		} else {
-			evhttp_add_event(&evcon->ev, evcon->timeout,
-			    HTTP_READ_TIMEOUT);	       
-		}
-		return;
-	} else if (n == 0) {
-		/* Connection closed */
-		evcon->state = EVCON_DISCONNECTED;
-		evhttp_connection_done(evcon);
-		return;
-	}
-
-	switch (evcon->state) {
-	case EVCON_READING_FIRSTLINE:
-		evhttp_read_firstline(evcon, req);
-		break;
-	case EVCON_READING_HEADERS:
-		evhttp_read_header(evcon, req);
-		break;
-	case EVCON_READING_BODY:
-		evhttp_read_body(evcon, req);
-		break;
-	case EVCON_READING_TRAILER:
-		evhttp_read_trailer(evcon, req);
-		break;
-	case EVCON_DISCONNECTED:
-	case EVCON_CONNECTING:
-	case EVCON_IDLE:
-	case EVCON_WRITING:
-	default:
-		event_errx(1, "%s: illegal connection state %d",
-			   __func__, evcon->state);
-	}
-}
-
-static void
-evhttp_write_connectioncb(struct evhttp_connection *evcon, void *arg)
-{
-	/* This is after writing the request to the server */
-	struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
-	assert(req != NULL);
-
-	assert(evcon->state == EVCON_WRITING);
-
-	/* We are done writing our header and are now expecting the response */
-	req->kind = EVHTTP_RESPONSE;
-
-	evhttp_start_read(evcon);
-}
-
-/*
- * Clean up a connection object
- */
-
-void
-evhttp_connection_free(struct evhttp_connection *evcon)
-{
-	struct evhttp_request *req;
-
-	/* notify interested parties that this connection is going down */
-	if (evcon->fd != -1) {
-		if (evhttp_connected(evcon) && evcon->closecb != NULL)
-			(*evcon->closecb)(evcon, evcon->closecb_arg);
-	}
-
-	/* remove all requests that might be queued on this
-	 * connection.  for server connections, this should be empty.
-	 * because it gets dequeued either in evhttp_connection_done or
-	 * evhttp_connection_fail.
-	 */
-	while ((req = TAILQ_FIRST(&evcon->requests)) != NULL) {
-		TAILQ_REMOVE(&evcon->requests, req, next);
-		evhttp_request_free(req);
-	}
-
-	if (evcon->http_server != NULL) {
-		struct evhttp *http = evcon->http_server;
-		TAILQ_REMOVE(&http->connections, evcon, next);
-	}
-
-	if (event_initialized(&evcon->close_ev))
-		event_del(&evcon->close_ev);
-
-	if (event_initialized(&evcon->ev))
-		event_del(&evcon->ev);
-	
-	if (evcon->fd != -1)
-		EVUTIL_CLOSESOCKET(evcon->fd);
-
-	if (evcon->bind_address != NULL)
-		free(evcon->bind_address);
-
-	if (evcon->address != NULL)
-		free(evcon->address);
-
-	if (evcon->input_buffer != NULL)
-		evbuffer_free(evcon->input_buffer);
-
-	if (evcon->output_buffer != NULL)
-		evbuffer_free(evcon->output_buffer);
-
-	free(evcon);
-}
-
-void
-evhttp_connection_set_local_address(struct evhttp_connection *evcon,
-    const char *address)
-{
-	assert(evcon->state == EVCON_DISCONNECTED);
-	if (evcon->bind_address)
-		free(evcon->bind_address);
-	if ((evcon->bind_address = strdup(address)) == NULL)
-		event_err(1, "%s: strdup", __func__);
-}
-
-void
-evhttp_connection_set_local_port(struct evhttp_connection *evcon,
-    unsigned short port)
-{
-	assert(evcon->state == EVCON_DISCONNECTED);
-	evcon->bind_port = port;
-}
-
-static void
-evhttp_request_dispatch(struct evhttp_connection* evcon)
-{
-	struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
-	
-	/* this should not usually happy but it's possible */
-	if (req == NULL)
-		return;
-
-	/* delete possible close detection events */
-	evhttp_connection_stop_detectclose(evcon);
-	
-	/* we assume that the connection is connected already */
-	assert(evcon->state == EVCON_IDLE);
-
-	evcon->state = EVCON_WRITING;
-
-	/* Create the header from the store arguments */
-	evhttp_make_header(evcon, req);
-
-	evhttp_write_buffer(evcon, evhttp_write_connectioncb, NULL);
-}
-
-/* Reset our connection state */
-void
-evhttp_connection_reset(struct evhttp_connection *evcon)
-{
-	if (event_initialized(&evcon->ev))
-		event_del(&evcon->ev);
-
-	if (evcon->fd != -1) {
-		/* inform interested parties about connection close */
-		if (evhttp_connected(evcon) && evcon->closecb != NULL)
-			(*evcon->closecb)(evcon, evcon->closecb_arg);
-
-		EVUTIL_CLOSESOCKET(evcon->fd);
-		evcon->fd = -1;
-	}
-	evcon->state = EVCON_DISCONNECTED;
-
-	evbuffer_drain(evcon->input_buffer,
-	    EVBUFFER_LENGTH(evcon->input_buffer));
-	evbuffer_drain(evcon->output_buffer,
-	    EVBUFFER_LENGTH(evcon->output_buffer));
-}
-
-static void
-evhttp_detect_close_cb(int fd, short what, void *arg)
-{
-	struct evhttp_connection *evcon = arg;
-	evhttp_connection_reset(evcon);
-}
-
-static void
-evhttp_connection_start_detectclose(struct evhttp_connection *evcon)
-{
-	evcon->flags |= EVHTTP_CON_CLOSEDETECT;
-
-	if (event_initialized(&evcon->close_ev))
-		event_del(&evcon->close_ev);
-	event_set(&evcon->close_ev, evcon->fd, EV_READ,
-	    evhttp_detect_close_cb, evcon);
-	EVHTTP_BASE_SET(evcon, &evcon->close_ev);
-	event_add(&evcon->close_ev, NULL);
-}
-
-static void
-evhttp_connection_stop_detectclose(struct evhttp_connection *evcon)
-{
-	evcon->flags &= ~EVHTTP_CON_CLOSEDETECT;
-	event_del(&evcon->close_ev);
-}
-
-static void
-evhttp_connection_retry(int fd, short what, void *arg)
-{
-	struct evhttp_connection *evcon = arg;
-
-	evcon->state = EVCON_DISCONNECTED;
-	evhttp_connection_connect(evcon);
-}
-
-/*
- * Call back for asynchronous connection attempt.
- */
-
-static void
-evhttp_connectioncb(int fd, short what, void *arg)
-{
-	struct evhttp_connection *evcon = arg;
-	int error;
-	socklen_t errsz = sizeof(error);
-		
-	if (what == EV_TIMEOUT) {
-		event_debug(("%s: connection timeout for \"%s:%d\" on %d",
-			__func__, evcon->address, evcon->port, evcon->fd));
-		goto cleanup;
-	}
-
-	/* Check if the connection completed */
-	if (getsockopt(evcon->fd, SOL_SOCKET, SO_ERROR, (void*)&error,
-		       &errsz) == -1) {
-		event_debug(("%s: getsockopt for \"%s:%d\" on %d",
-			__func__, evcon->address, evcon->port, evcon->fd));
-		goto cleanup;
-	}
-
-	if (error) {
-		event_debug(("%s: connect failed for \"%s:%d\" on %d: %s",
-		    __func__, evcon->address, evcon->port, evcon->fd,
-			strerror(error)));
-		goto cleanup;
-	}
-
-	/* We are connected to the server now */
-	event_debug(("%s: connected to \"%s:%d\" on %d\n",
-			__func__, evcon->address, evcon->port, evcon->fd));
-
-	/* Reset the retry count as we were successful in connecting */
-	evcon->retry_cnt = 0;
-	evcon->state = EVCON_IDLE;
-
-	/* try to start requests that have queued up on this connection */
-	evhttp_request_dispatch(evcon);
-	return;
-
- cleanup:
-	if (evcon->retry_max < 0 || evcon->retry_cnt < evcon->retry_max) {
-		evtimer_set(&evcon->ev, evhttp_connection_retry, evcon);
-		EVHTTP_BASE_SET(evcon, &evcon->ev);
-		evhttp_add_event(&evcon->ev, MIN(3600, 2 << evcon->retry_cnt),
-		    HTTP_CONNECT_TIMEOUT);
-		evcon->retry_cnt++;
-		return;
-	}
-	evhttp_connection_reset(evcon);
-
-	/* for now, we just signal all requests by executing their callbacks */
-	while (TAILQ_FIRST(&evcon->requests) != NULL) {
-		struct evhttp_request *request = TAILQ_FIRST(&evcon->requests);
-		TAILQ_REMOVE(&evcon->requests, request, next);
-		request->evcon = NULL;
-
-		/* we might want to set an error here */
-		request->cb(request, request->cb_arg);
-		evhttp_request_free(request);
-	}
-}
-
-/*
- * Check if we got a valid response code.
- */
-
-static int
-evhttp_valid_response_code(int code)
-{
-	if (code == 0)
-		return (0);
-
-	return (1);
-}
-
-/* Parses the status line of a web server */
-
-static int
-evhttp_parse_response_line(struct evhttp_request *req, char *line)
-{
-	char *protocol;
-	char *number;
-	const char *readable = "";
-
-	protocol = strsep(&line, " ");
-	if (line == NULL)
-		return (-1);
-	number = strsep(&line, " ");
-	if (line != NULL)
-		readable = line;
-
-	if (strcmp(protocol, "HTTP/1.0") == 0) {
-		req->major = 1;
-		req->minor = 0;
-	} else if (strcmp(protocol, "HTTP/1.1") == 0) {
-		req->major = 1;
-		req->minor = 1;
-	} else {
-		event_debug(("%s: bad protocol \"%s\"",
-			__func__, protocol));
-		return (-1);
-	}
-
-	req->response_code = atoi(number);
-	if (!evhttp_valid_response_code(req->response_code)) {
-		event_debug(("%s: bad response code \"%s\"",
-			__func__, number));
-		return (-1);
-	}
-
-	if ((req->response_code_line = strdup(readable)) == NULL)
-		event_err(1, "%s: strdup", __func__);
-
-	return (0);
-}
-
-/* Parse the first line of a HTTP request */
-
-static int
-evhttp_parse_request_line(struct evhttp_request *req, char *line)
-{
-	char *method;
-	char *uri;
-	char *version;
-
-	/* Parse the request line */
-	method = strsep(&line, " ");
-	if (line == NULL)
-		return (-1);
-	uri = strsep(&line, " ");
-	if (line == NULL)
-		return (-1);
-	version = strsep(&line, " ");
-	if (line != NULL)
-		return (-1);
-
-	/* First line */
-	if (strcmp(method, "GET") == 0) {
-		req->type = EVHTTP_REQ_GET;
-	} else if (strcmp(method, "POST") == 0) {
-		req->type = EVHTTP_REQ_POST;
-	} else if (strcmp(method, "HEAD") == 0) {
-		req->type = EVHTTP_REQ_HEAD;
-	} else {
-		event_debug(("%s: bad method %s on request %p from %s",
-			__func__, method, req, req->remote_host));
-		return (-1);
-	}
-
-	if (strcmp(version, "HTTP/1.0") == 0) {
-		req->major = 1;
-		req->minor = 0;
-	} else if (strcmp(version, "HTTP/1.1") == 0) {
-		req->major = 1;
-		req->minor = 1;
-	} else {
-		event_debug(("%s: bad version %s on request %p from %s",
-			__func__, version, req, req->remote_host));
-		return (-1);
-	}
-
-	if ((req->uri = strdup(uri)) == NULL) {
-		event_debug(("%s: strdup", __func__));
-		return (-1);
-	}
-
-	/* determine if it's a proxy request */
-	if (strlen(req->uri) > 0 && req->uri[0] != '/')
-		req->flags |= EVHTTP_PROXY_REQUEST;
-
-	return (0);
-}
-
-const char *
-evhttp_find_header(const struct evkeyvalq *headers, const char *key)
-{
-	struct evkeyval *header;
-
-	TAILQ_FOREACH(header, headers, next) {
-		if (strcasecmp(header->key, key) == 0)
-			return (header->value);
-	}
-
-	return (NULL);
-}
-
-void
-evhttp_clear_headers(struct evkeyvalq *headers)
-{
-	struct evkeyval *header;
-
-	for (header = TAILQ_FIRST(headers);
-	    header != NULL;
-	    header = TAILQ_FIRST(headers)) {
-		TAILQ_REMOVE(headers, header, next);
-		free(header->key);
-		free(header->value);
-		free(header);
-	}
-}
-
-/*
- * Returns 0,  if the header was successfully removed.
- * Returns -1, if the header could not be found.
- */
-
-int
-evhttp_remove_header(struct evkeyvalq *headers, const char *key)
-{
-	struct evkeyval *header;
-
-	TAILQ_FOREACH(header, headers, next) {
-		if (strcasecmp(header->key, key) == 0)
-			break;
-	}
-
-	if (header == NULL)
-		return (-1);
-
-	/* Free and remove the header that we found */
-	TAILQ_REMOVE(headers, header, next);
-	free(header->key);
-	free(header->value);
-	free(header);
-
-	return (0);
-}
-
-static int
-evhttp_header_is_valid_value(const char *value)
-{
-	const char *p = value;
-
-	while ((p = strpbrk(p, "\r\n")) != NULL) {
-		/* we really expect only one new line */
-		p += strspn(p, "\r\n");
-		/* we expect a space or tab for continuation */
-		if (*p != ' ' && *p != '\t')
-			return (0);
-	}
-	return (1);
-}
-
-int
-evhttp_add_header(struct evkeyvalq *headers,
-    const char *key, const char *value)
-{
-	event_debug(("%s: key: %s val: %s\n", __func__, key, value));
-
-	if (strchr(key, '\r') != NULL || strchr(key, '\n') != NULL) {
-		/* drop illegal headers */
-		event_debug(("%s: dropping illegal header key\n", __func__));
-		return (-1);
-	}
-	
-	if (!evhttp_header_is_valid_value(value)) {
-		event_debug(("%s: dropping illegal header value\n", __func__));
-		return (-1);
-	}
-
-	return (evhttp_add_header_internal(headers, key, value));
-}
-
-static int
-evhttp_add_header_internal(struct evkeyvalq *headers,
-    const char *key, const char *value)
-{
-	struct evkeyval *header = calloc(1, sizeof(struct evkeyval));
-	if (header == NULL) {
-		event_warn("%s: calloc", __func__);
-		return (-1);
-	}
-	if ((header->key = strdup(key)) == NULL) {
-		free(header);
-		event_warn("%s: strdup", __func__);
-		return (-1);
-	}
-	if ((header->value = strdup(value)) == NULL) {
-		free(header->key);
-		free(header);
-		event_warn("%s: strdup", __func__);
-		return (-1);
-	}
-
-	TAILQ_INSERT_TAIL(headers, header, next);
-
-	return (0);
-}
-
-/*
- * Parses header lines from a request or a response into the specified
- * request object given an event buffer.
- *
- * Returns
- *   DATA_CORRUPTED      on error
- *   MORE_DATA_EXPECTED  when we need to read more headers
- *   ALL_DATA_READ       when all headers have been read.
- */
-
-enum message_read_status
-evhttp_parse_firstline(struct evhttp_request *req, struct evbuffer *buffer)
-{
-	char *line;
-	enum message_read_status status = ALL_DATA_READ;
-
-	line = evbuffer_readline(buffer);
-	if (line == NULL)
-		return (MORE_DATA_EXPECTED);
-
-	switch (req->kind) {
-	case EVHTTP_REQUEST:
-		if (evhttp_parse_request_line(req, line) == -1)
-			status = DATA_CORRUPTED;
-		break;
-	case EVHTTP_RESPONSE:
-		if (evhttp_parse_response_line(req, line) == -1)
-			status = DATA_CORRUPTED;
-		break;
-	default:
-		status = DATA_CORRUPTED;
-	}
-
-	free(line);
-	return (status);
-}
-
-static int
-evhttp_append_to_last_header(struct evkeyvalq *headers, const char *line)
-{
-	struct evkeyval *header = TAILQ_LAST(headers, evkeyvalq);
-	char *newval;
-	size_t old_len, line_len;
-
-	if (header == NULL)
-		return (-1);
-
-	old_len = strlen(header->value);
-	line_len = strlen(line);
-
-	newval = realloc(header->value, old_len + line_len + 1);
-	if (newval == NULL)
-		return (-1);
-
-	memcpy(newval + old_len, line, line_len + 1);
-	header->value = newval;
-
-	return (0);
-}
-
-enum message_read_status
-evhttp_parse_headers(struct evhttp_request *req, struct evbuffer* buffer)
-{
-	char *line;
-	enum message_read_status status = MORE_DATA_EXPECTED;
-
-	struct evkeyvalq* headers = req->input_headers;
-	while ((line = evbuffer_readline(buffer))
-	       != NULL) {
-		char *skey, *svalue;
-
-		if (*line == '\0') { /* Last header - Done */
-			status = ALL_DATA_READ;
-			free(line);
-			break;
-		}
-
-		/* Check if this is a continuation line */
-		if (*line == ' ' || *line == '\t') {
-			if (evhttp_append_to_last_header(headers, line) == -1)
-				goto error;
-			free(line);
-			continue;
-		}
-
-		/* Processing of header lines */
-		svalue = line;
-		skey = strsep(&svalue, ":");
-		if (svalue == NULL)
-			goto error;
-
-		svalue += strspn(svalue, " ");
-
-		if (evhttp_add_header(headers, skey, svalue) == -1)
-			goto error;
-
-		free(line);
-	}
-
-	return (status);
-
- error:
-	free(line);
-	return (DATA_CORRUPTED);
-}
-
-static int
-evhttp_get_body_length(struct evhttp_request *req)
-{
-	struct evkeyvalq *headers = req->input_headers;
-	const char *content_length;
-	const char *connection;
-
-	content_length = evhttp_find_header(headers, "Content-Length");
-	connection = evhttp_find_header(headers, "Connection");
-		
-	if (content_length == NULL && connection == NULL)
-		req->ntoread = -1;
-	else if (content_length == NULL &&
-	    strcasecmp(connection, "Close") != 0) {
-		/* Bad combination, we don't know when it will end */
-		event_warnx("%s: we got no content length, but the "
-		    "server wants to keep the connection open: %s.",
-		    __func__, connection);
-		return (-1);
-	} else if (content_length == NULL) {
-		req->ntoread = -1;
-	} else {
-		char *endp;
-		ev_int64_t ntoread = evutil_strtoll(content_length, &endp, 10);
-		if (*content_length == '\0' || *endp != '\0' || ntoread < 0) {
-			event_debug(("%s: illegal content length: %s",
-				__func__, content_length));
-			return (-1);
-		}
-		req->ntoread = ntoread;
-	}
-		
-	event_debug(("%s: bytes to read: %lld (in buffer %ld)\n",
-		__func__, req->ntoread,
-		EVBUFFER_LENGTH(req->evcon->input_buffer)));
-
-	return (0);
-}
-
-static void
-evhttp_get_body(struct evhttp_connection *evcon, struct evhttp_request *req)
-{
-	const char *xfer_enc;
-	
-	/* If this is a request without a body, then we are done */
-	if (req->kind == EVHTTP_REQUEST && req->type != EVHTTP_REQ_POST) {
-		evhttp_connection_done(evcon);
-		return;
-	}
-	evcon->state = EVCON_READING_BODY;
-	xfer_enc = evhttp_find_header(req->input_headers, "Transfer-Encoding");
-	if (xfer_enc != NULL && strcasecmp(xfer_enc, "chunked") == 0) {
-		req->chunked = 1;
-		req->ntoread = -1;
-	} else {
-		if (evhttp_get_body_length(req) == -1) {
-			evhttp_connection_fail(evcon,
-			    EVCON_HTTP_INVALID_HEADER);
-			return;
-		}
-	}
-	evhttp_read_body(evcon, req);
-}
-
-static void
-evhttp_read_firstline(struct evhttp_connection *evcon,
-		      struct evhttp_request *req)
-{
-	enum message_read_status res;
-
-	res = evhttp_parse_firstline(req, evcon->input_buffer);
-	if (res == DATA_CORRUPTED) {
-		/* Error while reading, terminate */
-		event_debug(("%s: bad header lines on %d\n",
-			__func__, evcon->fd));
-		evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
-		return;
-	} else if (res == MORE_DATA_EXPECTED) {
-		/* Need more header lines */
-		evhttp_add_event(&evcon->ev, 
-                    evcon->timeout, HTTP_READ_TIMEOUT);
-		return;
-	}
-
-	evcon->state = EVCON_READING_HEADERS;
-	evhttp_read_header(evcon, req);
-}
-
-static void
-evhttp_read_header(struct evhttp_connection *evcon, struct evhttp_request *req)
-{
-	enum message_read_status res;
-	int fd = evcon->fd;
-
-	res = evhttp_parse_headers(req, evcon->input_buffer);
-	if (res == DATA_CORRUPTED) {
-		/* Error while reading, terminate */
-		event_debug(("%s: bad header lines on %d\n", __func__, fd));
-		evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
-		return;
-	} else if (res == MORE_DATA_EXPECTED) {
-		/* Need more header lines */
-		evhttp_add_event(&evcon->ev, 
-		    evcon->timeout, HTTP_READ_TIMEOUT);
-		return;
-	}
-
-	/* Done reading headers, do the real work */
-	switch (req->kind) {
-	case EVHTTP_REQUEST:
-		event_debug(("%s: checking for post data on %d\n",
-				__func__, fd));
-		evhttp_get_body(evcon, req);
-		break;
-
-	case EVHTTP_RESPONSE:
-		if (req->response_code == HTTP_NOCONTENT ||
-		    req->response_code == HTTP_NOTMODIFIED ||
-		    (req->response_code >= 100 && req->response_code < 200)) {
-			event_debug(("%s: skipping body for code %d\n",
-					__func__, req->response_code));
-			evhttp_connection_done(evcon);
-		} else {
-			event_debug(("%s: start of read body for %s on %d\n",
-				__func__, req->remote_host, fd));
-			evhttp_get_body(evcon, req);
-		}
-		break;
-
-	default:
-		event_warnx("%s: bad header on %d", __func__, fd);
-		evhttp_connection_fail(evcon, EVCON_HTTP_INVALID_HEADER);
-		break;
-	}
-}
-
-/*
- * Creates a TCP connection to the specified port and executes a callback
- * when finished.  Failure or sucess is indicate by the passed connection
- * object.
- *
- * Although this interface accepts a hostname, it is intended to take
- * only numeric hostnames so that non-blocking DNS resolution can
- * happen elsewhere.
- */
-
-struct evhttp_connection *
-evhttp_connection_new(const char *address, unsigned short port)
-{
-	struct evhttp_connection *evcon = NULL;
-	
-	event_debug(("Attempting connection to %s:%d\n", address, port));
-
-	if ((evcon = calloc(1, sizeof(struct evhttp_connection))) == NULL) {
-		event_warn("%s: calloc failed", __func__);
-		goto error;
-	}
-
-	evcon->fd = -1;
-	evcon->port = port;
-
-	evcon->timeout = -1;
-	evcon->retry_cnt = evcon->retry_max = 0;
-
-	if ((evcon->address = strdup(address)) == NULL) {
-		event_warn("%s: strdup failed", __func__);
-		goto error;
-	}
-
-	if ((evcon->input_buffer = evbuffer_new()) == NULL) {
-		event_warn("%s: evbuffer_new failed", __func__);
-		goto error;
-	}
-
-	if ((evcon->output_buffer = evbuffer_new()) == NULL) {
-		event_warn("%s: evbuffer_new failed", __func__);
-		goto error;
-	}
-	
-	evcon->state = EVCON_DISCONNECTED;
-	TAILQ_INIT(&evcon->requests);
-
-	return (evcon);
-	
- error:
-	if (evcon != NULL)
-		evhttp_connection_free(evcon);
-	return (NULL);
-}
-
-void evhttp_connection_set_base(struct evhttp_connection *evcon,
-    struct event_base *base)
-{
-	assert(evcon->base == NULL);
-	assert(evcon->state == EVCON_DISCONNECTED);
-	evcon->base = base;
-}
-
-void
-evhttp_connection_set_timeout(struct evhttp_connection *evcon,
-    int timeout_in_secs)
-{
-	evcon->timeout = timeout_in_secs;
-}
-
-void
-evhttp_connection_set_retries(struct evhttp_connection *evcon,
-    int retry_max)
-{
-	evcon->retry_max = retry_max;
-}
-
-void
-evhttp_connection_set_closecb(struct evhttp_connection *evcon,
-    void (*cb)(struct evhttp_connection *, void *), void *cbarg)
-{
-	evcon->closecb = cb;
-	evcon->closecb_arg = cbarg;
-}
-
-void
-evhttp_connection_get_peer(struct evhttp_connection *evcon,
-    char **address, u_short *port)
-{
-	*address = evcon->address;
-	*port = evcon->port;
-}
-
-int
-evhttp_connection_connect(struct evhttp_connection *evcon)
-{
-	if (evcon->state == EVCON_CONNECTING)
-		return (0);
-	
-	evhttp_connection_reset(evcon);
-
-	assert(!(evcon->flags & EVHTTP_CON_INCOMING));
-	evcon->flags |= EVHTTP_CON_OUTGOING;
-	
-	evcon->fd = bind_socket(
-		evcon->bind_address, evcon->bind_port, 0 /*reuse*/);
-	if (evcon->fd == -1) {
-		event_debug(("%s: failed to bind to \"%s\"",
-			__func__, evcon->bind_address));
-		return (-1);
-	}
-
-	if (socket_connect(evcon->fd, evcon->address, evcon->port) == -1) {
-		EVUTIL_CLOSESOCKET(evcon->fd); evcon->fd = -1;
-		return (-1);
-	}
-
-	/* Set up a callback for successful connection setup */
-	event_set(&evcon->ev, evcon->fd, EV_WRITE, evhttp_connectioncb, evcon);
-	EVHTTP_BASE_SET(evcon, &evcon->ev);
-	evhttp_add_event(&evcon->ev, evcon->timeout, HTTP_CONNECT_TIMEOUT);
-
-	evcon->state = EVCON_CONNECTING;
-	
-	return (0);
-}
-
-/*
- * Starts an HTTP request on the provided evhttp_connection object.
- * If the connection object is not connected to the web server already,
- * this will start the connection.
- */
-
-int
-evhttp_make_request(struct evhttp_connection *evcon,
-    struct evhttp_request *req,
-    enum evhttp_cmd_type type, const char *uri)
-{
-	/* We are making a request */
-	req->kind = EVHTTP_REQUEST;
-	req->type = type;
-	if (req->uri != NULL)
-		free(req->uri);
-	if ((req->uri = strdup(uri)) == NULL)
-		event_err(1, "%s: strdup", __func__);
-
-	/* Set the protocol version if it is not supplied */
-	if (!req->major && !req->minor) {
-		req->major = 1;
-		req->minor = 1;
-	}
-	
-	assert(req->evcon == NULL);
-	req->evcon = evcon;
-	assert(!(req->flags & EVHTTP_REQ_OWN_CONNECTION));
-	
-	TAILQ_INSERT_TAIL(&evcon->requests, req, next);
-
-	/* If the connection object is not connected; make it so */
-	if (!evhttp_connected(evcon))
-		return (evhttp_connection_connect(evcon));
-
-	/*
-	 * If it's connected already and we are the first in the queue,
-	 * then we can dispatch this request immediately.  Otherwise, it
-	 * will be dispatched once the pending requests are completed.
-	 */
-	if (TAILQ_FIRST(&evcon->requests) == req)
-		evhttp_request_dispatch(evcon);
-
-	return (0);
-}
-
-/*
- * Reads data from file descriptor into request structure
- * Request structure needs to be set up correctly.
- */
-
-void
-evhttp_start_read(struct evhttp_connection *evcon)
-{
-	/* Set up an event to read the headers */
-	if (event_initialized(&evcon->ev))
-		event_del(&evcon->ev);
-	event_set(&evcon->ev, evcon->fd, EV_READ, evhttp_read, evcon);
-	EVHTTP_BASE_SET(evcon, &evcon->ev);
-	
-	evhttp_add_event(&evcon->ev, evcon->timeout, HTTP_READ_TIMEOUT);
-	evcon->state = EVCON_READING_FIRSTLINE;
-}
-
-static void
-evhttp_send_done(struct evhttp_connection *evcon, void *arg)
-{
-	int need_close;
-	struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
-	TAILQ_REMOVE(&evcon->requests, req, next);
-
-	/* delete possible close detection events */
-	evhttp_connection_stop_detectclose(evcon);
-	
-	need_close =
-	    (req->minor == 0 &&
-		!evhttp_is_connection_keepalive(req->input_headers))||
-	    evhttp_is_connection_close(req->flags, req->input_headers) ||
-	    evhttp_is_connection_close(req->flags, req->output_headers);
-
-	assert(req->flags & EVHTTP_REQ_OWN_CONNECTION);
-	evhttp_request_free(req);
-
-	if (need_close) {
-		evhttp_connection_free(evcon);
-		return;
-	} 
-
-	/* we have a persistent connection; try to accept another request. */
-	if (evhttp_associate_new_request_with_connection(evcon) == -1)
-		evhttp_connection_free(evcon);
-}
-
-/*
- * Returns an error page.
- */
-
-void
-evhttp_send_error(struct evhttp_request *req, int error, const char *reason)
-{
-#define ERR_FORMAT "<HTML><HEAD>\n" \
-	    "<TITLE>%d %s</TITLE>\n" \
-	    "</HEAD><BODY>\n" \
-	    "<H1>Method Not Implemented</H1>\n" \
-	    "Invalid method in request<P>\n" \
-	    "</BODY></HTML>\n"
-
-	struct evbuffer *buf = evbuffer_new();
-
-	/* close the connection on error */
-	evhttp_add_header(req->output_headers, "Connection", "close");
-
-	evhttp_response_code(req, error, reason);
-
-	evbuffer_add_printf(buf, ERR_FORMAT, error, reason);
-
-	evhttp_send_page(req, buf);
-
-	evbuffer_free(buf);
-#undef ERR_FORMAT
-}
-
-/* Requires that headers and response code are already set up */
-
-static inline void
-evhttp_send(struct evhttp_request *req, struct evbuffer *databuf)
-{
-	struct evhttp_connection *evcon = req->evcon;
-
-	if (evcon == NULL) {
-		evhttp_request_free(req);
-		return;
-	}
-
-	assert(TAILQ_FIRST(&evcon->requests) == req);
-
-	/* we expect no more calls form the user on this request */
-	req->userdone = 1;
-
-	/* xxx: not sure if we really should expose the data buffer this way */
-	if (databuf != NULL)
-		evbuffer_add_buffer(req->output_buffer, databuf);
-	
-	/* Adds headers to the response */
-	evhttp_make_header(evcon, req);
-
-	evhttp_write_buffer(evcon, evhttp_send_done, NULL);
-}
-
-void
-evhttp_send_reply(struct evhttp_request *req, int code, const char *reason,
-    struct evbuffer *databuf)
-{
-	evhttp_response_code(req, code, reason);
-	
-	evhttp_send(req, databuf);
-}
-
-void
-evhttp_send_reply_start(struct evhttp_request *req, int code,
-    const char *reason)
-{
-	evhttp_response_code(req, code, reason);
-	if (req->major == 1 && req->minor == 1) {
-		/* use chunked encoding for HTTP/1.1 */
-		evhttp_add_header(req->output_headers, "Transfer-Encoding",
-		    "chunked");
-		req->chunked = 1;
-	}
-	evhttp_make_header(req->evcon, req);
-	evhttp_write_buffer(req->evcon, NULL, NULL);
-}
-
-void
-evhttp_send_reply_chunk(struct evhttp_request *req, struct evbuffer *databuf)
-{
-	struct evhttp_connection *evcon = req->evcon;
-
-	if (evcon == NULL)
-		return;
-
-	if (req->chunked) {
-		evbuffer_add_printf(evcon->output_buffer, "%x\r\n",
-				    (unsigned)EVBUFFER_LENGTH(databuf));
-	}
-	evbuffer_add_buffer(evcon->output_buffer, databuf);
-	if (req->chunked) {
-		evbuffer_add(evcon->output_buffer, "\r\n", 2);
-	}
-	evhttp_write_buffer(evcon, NULL, NULL);
-}
-
-void
-evhttp_send_reply_end(struct evhttp_request *req)
-{
-	struct evhttp_connection *evcon = req->evcon;
-
-	if (evcon == NULL) {
-		evhttp_request_free(req);
-		return;
-	}
-
-	/* we expect no more calls form the user on this request */
-	req->userdone = 1;
-
-	if (req->chunked) {
-		evbuffer_add(req->evcon->output_buffer, "0\r\n\r\n", 5);
-		evhttp_write_buffer(req->evcon, evhttp_send_done, NULL);
-		req->chunked = 0;
-	} else if (!event_pending(&evcon->ev, EV_WRITE|EV_TIMEOUT, NULL)) {
-		/* let the connection know that we are done with the request */
-		evhttp_send_done(evcon, NULL);
-	} else {
-		/* make the callback execute after all data has been written */
-		evcon->cb = evhttp_send_done;
-		evcon->cb_arg = NULL;
-	}
-}
-
-void
-evhttp_response_code(struct evhttp_request *req, int code, const char *reason)
-{
-	req->kind = EVHTTP_RESPONSE;
-	req->response_code = code;
-	if (req->response_code_line != NULL)
-		free(req->response_code_line);
-	req->response_code_line = strdup(reason);
-}
-
-void
-evhttp_send_page(struct evhttp_request *req, struct evbuffer *databuf)
-{
-	if (!req->major || !req->minor) {
-		req->major = 1;
-		req->minor = 1;
-	}
-	
-	if (req->kind != EVHTTP_RESPONSE)
-		evhttp_response_code(req, 200, "OK");
-
-	evhttp_clear_headers(req->output_headers);
-	evhttp_add_header(req->output_headers, "Content-Type", "text/html");
-	evhttp_add_header(req->output_headers, "Connection", "close");
-
-	evhttp_send(req, databuf);
-}
-
-static const char uri_chars[256] = {
-	0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
-	0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
-	0, 1, 0, 0, 1, 0, 0, 1,   1, 1, 1, 1, 1, 1, 1, 1,
-	1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 1, 0, 0,
-	/* 64 */
-	1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
-	1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 1,
-	0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
-	1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 1, 0,
-	/* 128 */
-	0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
-	0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
-	0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
-	0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
-	/* 192 */
-	0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
-	0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
-	0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
-	0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
-};
-
-/*
- * Helper functions to encode/decode a URI.
- * The returned string must be freed by the caller.
- */
-char *
-evhttp_encode_uri(const char *uri)
-{
-	struct evbuffer *buf = evbuffer_new();
-	char *p;
-
-	for (p = (char *)uri; *p != '\0'; p++) {
-		if (uri_chars[(u_char)(*p)]) {
-			evbuffer_add(buf, p, 1);
-		} else {
-			evbuffer_add_printf(buf, "%%%02X", (u_char)(*p));
-		}
-	}
-	evbuffer_add(buf, "", 1);
-	p = strdup((char *)EVBUFFER_DATA(buf));
-	evbuffer_free(buf);
-	
-	return (p);
-}
-
-/*
- * @param always_decode_plus: when true we transform plus to space even
- *     if we have not seen a ?.
- */
-static int
-evhttp_decode_uri_internal(
-	const char *uri, size_t length, char *ret, int always_decode_plus)
-{
-	char c;
-	int i, j, in_query = always_decode_plus;
-	
-	for (i = j = 0; uri[i] != '\0'; i++) {
-		c = uri[i];
-		if (c == '?') {
-			in_query = 1;
-		} else if (c == '+' && in_query) {
-			c = ' ';
-		} else if (c == '%' && isxdigit((unsigned char)uri[i+1]) &&
-		    isxdigit((unsigned char)uri[i+2])) {
-			char tmp[] = { uri[i+1], uri[i+2], '\0' };
-			c = (char)strtol(tmp, NULL, 16);
-			i += 2;
-		}
-		ret[j++] = c;
-	}
-	ret[j] = '\0';
-
-	return (j);
-}
-
-char *
-evhttp_decode_uri(const char *uri)
-{
-	char *ret;
-
-	if ((ret = malloc(strlen(uri) + 1)) == NULL)
-		event_err(1, "%s: malloc(%lu)", __func__,
-			  (unsigned long)(strlen(uri) + 1));
-
-	evhttp_decode_uri_internal(uri, strlen(uri),
-	    ret, 0 /*always_decode_plus*/);
-
-	return (ret);
-}
-
-/* 
- * Helper function to parse out arguments in a query.
- * The arguments are separated by key and value.
- */
-
-void
-evhttp_parse_query(const char *uri, struct evkeyvalq *headers)
-{
-	char *line;
-	char *argument;
-	char *p;
-
-	TAILQ_INIT(headers);
-
-	/* No arguments - we are done */
-	if (strchr(uri, '?') == NULL)
-		return;
-
-	if ((line = strdup(uri)) == NULL)
-		event_err(1, "%s: strdup", __func__);
-
-
-	argument = line;
-
-	/* We already know that there has to be a ? */
-	strsep(&argument, "?");
-
-	p = argument;
-	while (p != NULL && *p != '\0') {
-		char *key, *value, *decoded_value;
-		argument = strsep(&p, "&");
-
-		value = argument;
-		key = strsep(&value, "=");
-		if (value == NULL)
-			goto error;
-
-		if ((decoded_value = malloc(strlen(value) + 1)) == NULL)
-			event_err(1, "%s: malloc", __func__);
-
-		evhttp_decode_uri_internal(value, strlen(value),
-		    decoded_value, 1 /*always_decode_plus*/);
-		event_debug(("Query Param: %s -> %s\n", key, decoded_value));
-		evhttp_add_header_internal(headers, key, decoded_value);
-		free(decoded_value);
-	}
-
- error:
-	free(line);
-}
-
-static struct evhttp_cb *
-evhttp_dispatch_callback(struct httpcbq *callbacks, struct evhttp_request *req)
-{
-	struct evhttp_cb *cb;
-	size_t offset = 0;
-
-	/* Test for different URLs */
-	char *p = strchr(req->uri, '?');
-	if (p != NULL)
-		offset = (size_t)(p - req->uri);
-
-	TAILQ_FOREACH(cb, callbacks, next) {
-		int res = 0;
-		if (p == NULL) {
-			res = strcmp(cb->what, req->uri) == 0;
-		} else {
-			res = ((strncmp(cb->what, req->uri, offset) == 0) &&
-					(cb->what[offset] == '\0'));
-		}
-
-		if (res)
-			return (cb);
-	}
-
-	return (NULL);
-}
-
-static void
-evhttp_handle_request(struct evhttp_request *req, void *arg)
-{
-	struct evhttp *http = arg;
-	struct evhttp_cb *cb = NULL;
-
-	event_debug(("%s: req->uri=%s", __func__, req->uri));
-	if (req->uri == NULL) {
-		event_debug(("%s: bad request", __func__));
-		if (req->evcon->state == EVCON_DISCONNECTED) {
-			evhttp_connection_fail(req->evcon, EVCON_HTTP_EOF);
-		} else {
-			event_debug(("%s: sending error", __func__));
-			evhttp_send_error(req, HTTP_BADREQUEST, "Bad Request");
-		}
-		return;
-	}
-
-	if ((cb = evhttp_dispatch_callback(&http->callbacks, req)) != NULL) {
-		(*cb->cb)(req, cb->cbarg);
-		return;
-	}
-
-	/* Generic call back */
-	if (http->gencb) {
-		(*http->gencb)(req, http->gencbarg);
-		return;
-	} else {
-		/* We need to send a 404 here */
-#define ERR_FORMAT "<html><head>" \
-		    "<title>404 Not Found</title>" \
-		    "</head><body>" \
-		    "<h1>Not Found</h1>" \
-		    "<p>The requested URL %s was not found on this server.</p>"\
-		    "</body></html>\n"
-
-		char *escaped_html = evhttp_htmlescape(req->uri);
-		struct evbuffer *buf = evbuffer_new();
-
-		evhttp_response_code(req, HTTP_NOTFOUND, "Not Found");
-
-		evbuffer_add_printf(buf, ERR_FORMAT, escaped_html);
-
-		free(escaped_html);
-
-		evhttp_send_page(req, buf);
-
-		evbuffer_free(buf);
-#undef ERR_FORMAT
-	}
-}
-
-static void
-accept_socket(int fd, short what, void *arg)
-{
-	struct evhttp *http = arg;
-	struct sockaddr_storage ss;
-	socklen_t addrlen = sizeof(ss);
-	int nfd;
-
-	if ((nfd = accept(fd, (struct sockaddr *)&ss, &addrlen)) == -1) {
-		if (errno != EAGAIN && errno != EINTR)
-			event_warn("%s: bad accept", __func__);
-		return;
-	}
-	if (evutil_make_socket_nonblocking(nfd) < 0)
-		return;
-
-	evhttp_get_request(http, nfd, (struct sockaddr *)&ss, addrlen);
-}
-
-int
-evhttp_bind_socket(struct evhttp *http, const char *address, u_short port)
-{
-	int fd;
-	int res;
-
-	if ((fd = bind_socket(address, port, 1 /*reuse*/)) == -1)
-		return (-1);
-
-	if (listen(fd, 128) == -1) {
-		event_warn("%s: listen", __func__);
-		EVUTIL_CLOSESOCKET(fd);
-		return (-1);
-	}
-
-	res = evhttp_accept_socket(http, fd);
-	
-	if (res != -1)
-		event_debug(("Bound to port %d - Awaiting connections ... ",
-			port));
-
-	return (res);
-}
-
-int
-evhttp_accept_socket(struct evhttp *http, int fd)
-{
-	struct evhttp_bound_socket *bound;
-	struct event *ev;
-	int res;
-
-	bound = malloc(sizeof(struct evhttp_bound_socket));
-	if (bound == NULL)
-		return (-1);
-
-	ev = &bound->bind_ev;
-
-	/* Schedule the socket for accepting */
-	event_set(ev, fd, EV_READ | EV_PERSIST, accept_socket, http);
-	EVHTTP_BASE_SET(http, ev);
-
-	res = event_add(ev, NULL);
-
-	if (res == -1) {
-		free(bound);
-		return (-1);
-	}
-
-	TAILQ_INSERT_TAIL(&http->sockets, bound, next);
-
-	return (0);
-}
-
-static struct evhttp*
-evhttp_new_object(void)
-{
-	struct evhttp *http = NULL;
-
-	if ((http = calloc(1, sizeof(struct evhttp))) == NULL) {
-		event_warn("%s: calloc", __func__);
-		return (NULL);
-	}
-
-	http->timeout = -1;
-
-	TAILQ_INIT(&http->sockets);
-	TAILQ_INIT(&http->callbacks);
-	TAILQ_INIT(&http->connections);
-
-	return (http);
-}
-
-struct evhttp *
-evhttp_new(struct event_base *base)
-{
-	struct evhttp *http = evhttp_new_object();
-
-	http->base = base;
-
-	return (http);
-}
-
-/*
- * Start a web server on the specified address and port.
- */
-
-struct evhttp *
-evhttp_start(const char *address, u_short port)
-{
-	struct evhttp *http = evhttp_new_object();
-
-	if (evhttp_bind_socket(http, address, port) == -1) {
-		free(http);
-		return (NULL);
-	}
-
-	return (http);
-}
-
-void
-evhttp_free(struct evhttp* http)
-{
-	struct evhttp_cb *http_cb;
-	struct evhttp_connection *evcon;
-	struct evhttp_bound_socket *bound;
-	int fd;
-
-	/* Remove the accepting part */
-	while ((bound = TAILQ_FIRST(&http->sockets)) != NULL) {
-		TAILQ_REMOVE(&http->sockets, bound, next);
-
-		fd = bound->bind_ev.ev_fd;
-		event_del(&bound->bind_ev);
-		EVUTIL_CLOSESOCKET(fd);
-
-		free(bound);
-	}
-
-	while ((evcon = TAILQ_FIRST(&http->connections)) != NULL) {
-		/* evhttp_connection_free removes the connection */
-		evhttp_connection_free(evcon);
-	}
-
-	while ((http_cb = TAILQ_FIRST(&http->callbacks)) != NULL) {
-		TAILQ_REMOVE(&http->callbacks, http_cb, next);
-		free(http_cb->what);
-		free(http_cb);
-	}
-	
-	free(http);
-}
-
-void
-evhttp_set_timeout(struct evhttp* http, int timeout_in_secs)
-{
-	http->timeout = timeout_in_secs;
-}
-
-void
-evhttp_set_cb(struct evhttp *http, const char *uri,
-    void (*cb)(struct evhttp_request *, void *), void *cbarg)
-{
-	struct evhttp_cb *http_cb;
-
-	if ((http_cb = calloc(1, sizeof(struct evhttp_cb))) == NULL)
-		event_err(1, "%s: calloc", __func__);
-
-	http_cb->what = strdup(uri);
-	http_cb->cb = cb;
-	http_cb->cbarg = cbarg;
-
-	TAILQ_INSERT_TAIL(&http->callbacks, http_cb, next);
-}
-
-int
-evhttp_del_cb(struct evhttp *http, const char *uri)
-{
-	struct evhttp_cb *http_cb;
-
-	TAILQ_FOREACH(http_cb, &http->callbacks, next) {
-		if (strcmp(http_cb->what, uri) == 0)
-			break;
-	}
-	if (http_cb == NULL)
-		return (-1);
-
-	TAILQ_REMOVE(&http->callbacks, http_cb, next);
-	free(http_cb->what);
-	free(http_cb);
-
-	return (0);
-}
-
-void
-evhttp_set_gencb(struct evhttp *http,
-    void (*cb)(struct evhttp_request *, void *), void *cbarg)
-{
-	http->gencb = cb;
-	http->gencbarg = cbarg;
-}
-
-/*
- * Request related functions
- */
-
-struct evhttp_request *
-evhttp_request_new(void (*cb)(struct evhttp_request *, void *), void *arg)
-{
-	struct evhttp_request *req = NULL;
-
-	/* Allocate request structure */
-	if ((req = calloc(1, sizeof(struct evhttp_request))) == NULL) {
-		event_warn("%s: calloc", __func__);
-		goto error;
-	}
-
-	req->kind = EVHTTP_RESPONSE;
-	req->input_headers = calloc(1, sizeof(struct evkeyvalq));
-	if (req->input_headers == NULL) {
-		event_warn("%s: calloc", __func__);
-		goto error;
-	}
-	TAILQ_INIT(req->input_headers);
-
-	req->output_headers = calloc(1, sizeof(struct evkeyvalq));
-	if (req->output_headers == NULL) {
-		event_warn("%s: calloc", __func__);
-		goto error;
-	}
-	TAILQ_INIT(req->output_headers);
-
-	if ((req->input_buffer = evbuffer_new()) == NULL) {
-		event_warn("%s: evbuffer_new", __func__);
-		goto error;
-	}
-
-	if ((req->output_buffer = evbuffer_new()) == NULL) {
-		event_warn("%s: evbuffer_new", __func__);
-		goto error;
-	}
-
-	req->cb = cb;
-	req->cb_arg = arg;
-
-	return (req);
-
- error:
-	if (req != NULL)
-		evhttp_request_free(req);
-	return (NULL);
-}
-
-void
-evhttp_request_free(struct evhttp_request *req)
-{
-	if (req->remote_host != NULL)
-		free(req->remote_host);
-	if (req->uri != NULL)
-		free(req->uri);
-	if (req->response_code_line != NULL)
-		free(req->response_code_line);
-
-	evhttp_clear_headers(req->input_headers);
-	free(req->input_headers);
-
-	evhttp_clear_headers(req->output_headers);
-	free(req->output_headers);
-
-	if (req->input_buffer != NULL)
-		evbuffer_free(req->input_buffer);
-
-	if (req->output_buffer != NULL)
-		evbuffer_free(req->output_buffer);
-
-	free(req);
-}
-
-struct evhttp_connection *
-evhttp_request_get_connection(struct evhttp_request *req)
-{
-	return req->evcon;
-}
-
-
-void
-evhttp_request_set_chunked_cb(struct evhttp_request *req,
-    void (*cb)(struct evhttp_request *, void *))
-{
-	req->chunk_cb = cb;
-}
-
-/*
- * Allows for inspection of the request URI
- */
-
-const char *
-evhttp_request_uri(struct evhttp_request *req) {
-	if (req->uri == NULL)
-		event_debug(("%s: request %p has no uri\n", __func__, req));
-	return (req->uri);
-}
-
-/*
- * Takes a file descriptor to read a request from.
- * The callback is executed once the whole request has been read.
- */
-
-static struct evhttp_connection*
-evhttp_get_request_connection(
-	struct evhttp* http,
-	int fd, struct sockaddr *sa, socklen_t salen)
-{
-	struct evhttp_connection *evcon;
-	char *hostname = NULL, *portname = NULL;
-
-	name_from_addr(sa, salen, &hostname, &portname);
-	if (hostname == NULL || portname == NULL) {
-		if (hostname) free(hostname);
-		if (portname) free(portname);
-		return (NULL);
-	}
-
-	event_debug(("%s: new request from %s:%s on %d\n",
-			__func__, hostname, portname, fd));
-
-	/* we need a connection object to put the http request on */
-	evcon = evhttp_connection_new(hostname, atoi(portname));
-	free(hostname);
-	free(portname);
-	if (evcon == NULL)
-		return (NULL);
-
-	/* associate the base if we have one*/
-	evhttp_connection_set_base(evcon, http->base);
-
-	evcon->flags |= EVHTTP_CON_INCOMING;
-	evcon->state = EVCON_READING_FIRSTLINE;
-	
-	evcon->fd = fd;
-
-	return (evcon);
-}
-
-static int
-evhttp_associate_new_request_with_connection(struct evhttp_connection *evcon)
-{
-	struct evhttp *http = evcon->http_server;
-	struct evhttp_request *req;
-	if ((req = evhttp_request_new(evhttp_handle_request, http)) == NULL)
-		return (-1);
-
-	req->evcon = evcon;	/* the request ends up owning the connection */
-	req->flags |= EVHTTP_REQ_OWN_CONNECTION;
-	
-	TAILQ_INSERT_TAIL(&evcon->requests, req, next);
-	
-	req->kind = EVHTTP_REQUEST;
-	
-	if ((req->remote_host = strdup(evcon->address)) == NULL)
-		event_err(1, "%s: strdup", __func__);
-	req->remote_port = evcon->port;
-
-	evhttp_start_read(evcon);
-	
-	return (0);
-}
-
-void
-evhttp_get_request(struct evhttp *http, int fd,
-    struct sockaddr *sa, socklen_t salen)
-{
-	struct evhttp_connection *evcon;
-
-	evcon = evhttp_get_request_connection(http, fd, sa, salen);
-	if (evcon == NULL)
-		return;
-
-	/* the timeout can be used by the server to close idle connections */
-	if (http->timeout != -1)
-		evhttp_connection_set_timeout(evcon, http->timeout);
-
-	/* 
-	 * if we want to accept more than one request on a connection,
-	 * we need to know which http server it belongs to.
-	 */
-	evcon->http_server = http;
-	TAILQ_INSERT_TAIL(&http->connections, evcon, next);
-	
-	if (evhttp_associate_new_request_with_connection(evcon) == -1)
-		evhttp_connection_free(evcon);
-}
-
-
-/*
- * Network helper functions that we do not want to export to the rest of
- * the world.
- */
-#if 0 /* Unused */
-static struct addrinfo *
-addr_from_name(char *address)
-{
-#ifdef HAVE_GETADDRINFO
-        struct addrinfo ai, *aitop;
-        int ai_result;
-
-        memset(&ai, 0, sizeof(ai));
-        ai.ai_family = AF_INET;
-        ai.ai_socktype = SOCK_RAW;
-        ai.ai_flags = 0;
-        if ((ai_result = getaddrinfo(address, NULL, &ai, &aitop)) != 0) {
-                if ( ai_result == EAI_SYSTEM )
-                        event_warn("getaddrinfo");
-                else
-                        event_warnx("getaddrinfo: %s", gai_strerror(ai_result));
-        }
-
-	return (aitop);
-#else
-	assert(0);
-	return NULL; /* XXXXX Use gethostbyname, if this function is ever used. */
-#endif
-}
-#endif
-
-static void
-name_from_addr(struct sockaddr *sa, socklen_t salen,
-    char **phost, char **pport)
-{
-	char ntop[NI_MAXHOST];
-	char strport[NI_MAXSERV];
-	int ni_result;
-
-#ifdef HAVE_GETNAMEINFO
-	ni_result = getnameinfo(sa, salen,
-		ntop, sizeof(ntop), strport, sizeof(strport),
-		NI_NUMERICHOST|NI_NUMERICSERV);
-	
-	if (ni_result != 0) {
-		if (ni_result == EAI_SYSTEM)
-			event_err(1, "getnameinfo failed");
-		else
-			event_errx(1, "getnameinfo failed: %s", gai_strerror(ni_result));
-		return;
-	}
-#else
-	ni_result = fake_getnameinfo(sa, salen,
-		ntop, sizeof(ntop), strport, sizeof(strport),
-		NI_NUMERICHOST|NI_NUMERICSERV);
-	if (ni_result != 0)
-			return;
-#endif
-	*phost = strdup(ntop);
-	*pport = strdup(strport);
-}
-
-/* Create a non-blocking socket and bind it */
-/* todo: rename this function */
-static int
-bind_socket_ai(struct addrinfo *ai, int reuse)
-{
-        int fd, on = 1, r;
-	int serrno;
-
-        /* Create listen socket */
-        fd = socket(AF_INET, SOCK_STREAM, 0);
-        if (fd == -1) {
-                event_warn("socket");
-                return (-1);
-        }
-
-        if (evutil_make_socket_nonblocking(fd) < 0)
-                goto out;
-
-#ifndef WIN32
-        if (fcntl(fd, F_SETFD, 1) == -1) {
-                event_warn("fcntl(F_SETFD)");
-                goto out;
-        }
-#endif
-
-        setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on));
-	if (reuse) {
-		setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
-		    (void *)&on, sizeof(on));
-	}
-
-	if (ai != NULL) {
-		r = bind(fd, ai->ai_addr, ai->ai_addrlen);
-		if (r == -1)
-			goto out;
-	}
-
-	return (fd);
-
- out:
-	serrno = EVUTIL_SOCKET_ERROR();
-	EVUTIL_CLOSESOCKET(fd);
-	EVUTIL_SET_SOCKET_ERROR(serrno);
-	return (-1);
-}
-
-static struct addrinfo *
-make_addrinfo(const char *address, u_short port)
-{
-        struct addrinfo *aitop = NULL;
-
-#ifdef HAVE_GETADDRINFO
-        struct addrinfo ai;
-        char strport[NI_MAXSERV];
-        int ai_result;
-
-        memset(&ai, 0, sizeof(ai));
-        ai.ai_family = AF_INET;
-        ai.ai_socktype = SOCK_STREAM;
-        ai.ai_flags = AI_PASSIVE;  /* turn NULL host name into INADDR_ANY */
-        evutil_snprintf(strport, sizeof(strport), "%d", port);
-        if ((ai_result = getaddrinfo(address, strport, &ai, &aitop)) != 0) {
-                if ( ai_result == EAI_SYSTEM )
-                        event_warn("getaddrinfo");
-                else
-                        event_warnx("getaddrinfo: %s", gai_strerror(ai_result));
-		return (NULL);
-        }
-#else
-	static int cur;
-	static struct addrinfo ai[2]; /* We will be returning the address of some of this memory so it has to last even after this call. */
-	if (++cur == 2) cur = 0;   /* allow calling this function twice */
-
-	if (fake_getaddrinfo(address, &ai[cur]) < 0) {
-		event_warn("fake_getaddrinfo");
-		return (NULL);
-	}
-	aitop = &ai[cur];
-	((struct sockaddr_in *) aitop->ai_addr)->sin_port = htons(port);
-#endif
-
-	return (aitop);
-}
-
-static int
-bind_socket(const char *address, u_short port, int reuse)
-{
-	int fd;
-	struct addrinfo *aitop = NULL;
-
-	/* just create an unbound socket */
-	if (address == NULL && port == 0)
-		return bind_socket_ai(NULL, 0);
-		
-	aitop = make_addrinfo(address, port);
-
-	if (aitop == NULL)
-		return (-1);
-
-	fd = bind_socket_ai(aitop, reuse);
-
-#ifdef HAVE_GETADDRINFO
-	freeaddrinfo(aitop);
-#else
-	fake_freeaddrinfo(aitop);
-#endif
-
-	return (fd);
-}
-
-static int
-socket_connect(int fd, const char *address, unsigned short port)
-{
-	struct addrinfo *ai = make_addrinfo(address, port);
-	int res = -1;
-
-	if (ai == NULL) {
-		event_debug(("%s: make_addrinfo: \"%s:%d\"",
-			__func__, address, port));
-		return (-1);
-	}
-
-	if (connect(fd, ai->ai_addr, ai->ai_addrlen) == -1) {
-#ifdef WIN32
-		int tmp_error = WSAGetLastError();
-		if (tmp_error != WSAEWOULDBLOCK && tmp_error != WSAEINVAL &&
-		    tmp_error != WSAEINPROGRESS) {
-			goto out;
-		}
-#else
-		if (errno != EINPROGRESS) {
-			goto out;
-		}
-#endif
-	}
-
-	/* everything is fine */
-	res = 0;
-
-out:
-#ifdef HAVE_GETADDRINFO
-	freeaddrinfo(ai);
-#else
-	fake_freeaddrinfo(ai);
-#endif
-
-	return (res);
-}
diff --git a/base/third_party/libevent/kqueue.c b/base/third_party/libevent/kqueue.c
deleted file mode 100644
index 3c2ffd5..0000000
--- a/base/third_party/libevent/kqueue.c
+++ /dev/null
@@ -1,433 +0,0 @@
-/*	$OpenBSD: kqueue.c,v 1.5 2002/07/10 14:41:31 art Exp $	*/
-
-/*
- * Copyright 2000-2002 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#define _GNU_SOURCE 1
-
-#include <sys/types.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#else
-#include <sys/_libevent_time.h>
-#endif
-#include <sys/queue.h>
-#include <sys/event.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <errno.h>
-#include <assert.h>
-#ifdef HAVE_INTTYPES_H
-#include <inttypes.h>
-#endif
-
-/* Some platforms apparently define the udata field of struct kevent as
- * intptr_t, whereas others define it as void*.  There doesn't seem to be an
- * easy way to tell them apart via autoconf, so we need to use OS macros. */
-#if defined(HAVE_INTTYPES_H) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && !defined(__darwin__) && !defined(__APPLE__)
-#define PTR_TO_UDATA(x)	((intptr_t)(x))
-#else
-#define PTR_TO_UDATA(x)	(x)
-#endif
-
-#include "event.h"
-#include "event-internal.h"
-#include "log.h"
-#include "evsignal.h"
-
-#define EVLIST_X_KQINKERNEL	0x1000
-
-#define NEVENT		64
-
-struct kqop {
-	struct kevent *changes;
-	int nchanges;
-	struct kevent *events;
-	struct event_list evsigevents[NSIG];
-	int nevents;
-	int kq;
-	pid_t pid;
-};
-
-static void *kq_init	(struct event_base *);
-static int kq_add	(void *, struct event *);
-static int kq_del	(void *, struct event *);
-static int kq_dispatch	(struct event_base *, void *, struct timeval *);
-static int kq_insert	(struct kqop *, struct kevent *);
-static void kq_dealloc (struct event_base *, void *);
-
-const struct eventop kqops = {
-	"kqueue",
-	kq_init,
-	kq_add,
-	kq_del,
-	kq_dispatch,
-	kq_dealloc,
-	1 /* need reinit */
-};
-
-static void *
-kq_init(struct event_base *base)
-{
-	int i, kq;
-	struct kqop *kqueueop;
-
-	/* Disable kqueue when this environment variable is set */
-	if (evutil_getenv("EVENT_NOKQUEUE"))
-		return (NULL);
-
-	if (!(kqueueop = calloc(1, sizeof(struct kqop))))
-		return (NULL);
-
-	/* Initalize the kernel queue */
-	
-	if ((kq = kqueue()) == -1) {
-		event_warn("kqueue");
-		free (kqueueop);
-		return (NULL);
-	}
-
-	kqueueop->kq = kq;
-
-	kqueueop->pid = getpid();
-
-	/* Initalize fields */
-	kqueueop->changes = malloc(NEVENT * sizeof(struct kevent));
-	if (kqueueop->changes == NULL) {
-		free (kqueueop);
-		return (NULL);
-	}
-	kqueueop->events = malloc(NEVENT * sizeof(struct kevent));
-	if (kqueueop->events == NULL) {
-		free (kqueueop->changes);
-		free (kqueueop);
-		return (NULL);
-	}
-	kqueueop->nevents = NEVENT;
-
-	/* we need to keep track of multiple events per signal */
-	for (i = 0; i < NSIG; ++i) {
-		TAILQ_INIT(&kqueueop->evsigevents[i]);
-	}
-
-	return (kqueueop);
-}
-
-static int
-kq_insert(struct kqop *kqop, struct kevent *kev)
-{
-	int nevents = kqop->nevents;
-
-	if (kqop->nchanges == nevents) {
-		struct kevent *newchange;
-		struct kevent *newresult;
-
-		nevents *= 2;
-
-		newchange = realloc(kqop->changes,
-				    nevents * sizeof(struct kevent));
-		if (newchange == NULL) {
-			event_warn("%s: malloc", __func__);
-			return (-1);
-		}
-		kqop->changes = newchange;
-
-		newresult = realloc(kqop->events,
-				    nevents * sizeof(struct kevent));
-
-		/*
-		 * If we fail, we don't have to worry about freeing,
-		 * the next realloc will pick it up.
-		 */
-		if (newresult == NULL) {
-			event_warn("%s: malloc", __func__);
-			return (-1);
-		}
-		kqop->events = newresult;
-
-		kqop->nevents = nevents;
-	}
-
-	memcpy(&kqop->changes[kqop->nchanges++], kev, sizeof(struct kevent));
-
-	event_debug(("%s: fd %d %s%s",
-		__func__, (int)kev->ident, 
-		kev->filter == EVFILT_READ ? "EVFILT_READ" : "EVFILT_WRITE",
-		kev->flags == EV_DELETE ? " (del)" : ""));
-
-	return (0);
-}
-
-static void
-kq_sighandler(int sig)
-{
-	/* Do nothing here */
-}
-
-static int
-kq_dispatch(struct event_base *base, void *arg, struct timeval *tv)
-{
-	struct kqop *kqop = arg;
-	struct kevent *changes = kqop->changes;
-	struct kevent *events = kqop->events;
-	struct event *ev;
-	struct timespec ts, *ts_p = NULL;
-	int i, res;
-
-	if (tv != NULL) {
-		TIMEVAL_TO_TIMESPEC(tv, &ts);
-		ts_p = &ts;
-	}
-
-	res = kevent(kqop->kq, changes, kqop->nchanges,
-	    events, kqop->nevents, ts_p);
-	kqop->nchanges = 0;
-	if (res == -1) {
-		if (errno != EINTR) {
-                        event_warn("kevent");
-			return (-1);
-		}
-
-		return (0);
-	}
-
-	event_debug(("%s: kevent reports %d", __func__, res));
-
-	for (i = 0; i < res; i++) {
-		int which = 0;
-
-		if (events[i].flags & EV_ERROR) {
-			/* 
-			 * Error messages that can happen, when a delete fails.
-			 *   EBADF happens when the file discriptor has been
-			 *   closed,
-			 *   ENOENT when the file discriptor was closed and
-			 *   then reopened.
-			 *   EINVAL for some reasons not understood; EINVAL
-			 *   should not be returned ever; but FreeBSD does :-\
-			 * An error is also indicated when a callback deletes
-			 * an event we are still processing.  In that case
-			 * the data field is set to ENOENT.
-			 */
-			if (events[i].data == EBADF ||
-			    events[i].data == EINVAL ||
-			    events[i].data == ENOENT)
-				continue;
-			errno = events[i].data;
-			return (-1);
-		}
-
-		if (events[i].filter == EVFILT_READ) {
-			which |= EV_READ;
-		} else if (events[i].filter == EVFILT_WRITE) {
-			which |= EV_WRITE;
-		} else if (events[i].filter == EVFILT_SIGNAL) {
-			which |= EV_SIGNAL;
-		}
-
-		if (!which)
-			continue;
-
-		if (events[i].filter == EVFILT_SIGNAL) {
-			struct event_list *head =
-			    (struct event_list *)events[i].udata;
-			TAILQ_FOREACH(ev, head, ev_signal_next) {
-				event_active(ev, which, events[i].data);
-			}
-		} else {
-			ev = (struct event *)events[i].udata;
-
-			if (!(ev->ev_events & EV_PERSIST))
-				ev->ev_flags &= ~EVLIST_X_KQINKERNEL;
-
-			event_active(ev, which, 1);
-		}
-	}
-
-	return (0);
-}
-
-
-static int
-kq_add(void *arg, struct event *ev)
-{
-	struct kqop *kqop = arg;
-	struct kevent kev;
-
-	if (ev->ev_events & EV_SIGNAL) {
-		int nsignal = EVENT_SIGNAL(ev);
-
-		assert(nsignal >= 0 && nsignal < NSIG);
-		if (TAILQ_EMPTY(&kqop->evsigevents[nsignal])) {
-			struct timespec timeout = { 0, 0 };
-			
-			memset(&kev, 0, sizeof(kev));
-			kev.ident = nsignal;
-			kev.filter = EVFILT_SIGNAL;
-			kev.flags = EV_ADD;
-			kev.udata = PTR_TO_UDATA(&kqop->evsigevents[nsignal]);
-			
-			/* Be ready for the signal if it is sent any
-			 * time between now and the next call to
-			 * kq_dispatch. */
-			if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1)
-				return (-1);
-			
-			if (_evsignal_set_handler(ev->ev_base, nsignal,
-				kq_sighandler) == -1)
-				return (-1);
-		}
-
-		TAILQ_INSERT_TAIL(&kqop->evsigevents[nsignal], ev,
-		    ev_signal_next);
-		ev->ev_flags |= EVLIST_X_KQINKERNEL;
-		return (0);
-	}
-
-	if (ev->ev_events & EV_READ) {
- 		memset(&kev, 0, sizeof(kev));
-		kev.ident = ev->ev_fd;
-		kev.filter = EVFILT_READ;
-#ifdef NOTE_EOF
-		/* Make it behave like select() and poll() */
-		kev.fflags = NOTE_EOF;
-#endif
-		kev.flags = EV_ADD;
-		if (!(ev->ev_events & EV_PERSIST))
-			kev.flags |= EV_ONESHOT;
-		kev.udata = PTR_TO_UDATA(ev);
-		
-		if (kq_insert(kqop, &kev) == -1)
-			return (-1);
-
-		ev->ev_flags |= EVLIST_X_KQINKERNEL;
-	}
-
-	if (ev->ev_events & EV_WRITE) {
- 		memset(&kev, 0, sizeof(kev));
-		kev.ident = ev->ev_fd;
-		kev.filter = EVFILT_WRITE;
-		kev.flags = EV_ADD;
-		if (!(ev->ev_events & EV_PERSIST))
-			kev.flags |= EV_ONESHOT;
-		kev.udata = PTR_TO_UDATA(ev);
-		
-		if (kq_insert(kqop, &kev) == -1)
-			return (-1);
-
-		ev->ev_flags |= EVLIST_X_KQINKERNEL;
-	}
-
-	return (0);
-}
-
-static int
-kq_del(void *arg, struct event *ev)
-{
-	struct kqop *kqop = arg;
-	struct kevent kev;
-
-	if (!(ev->ev_flags & EVLIST_X_KQINKERNEL))
-		return (0);
-
-	if (ev->ev_events & EV_SIGNAL) {
-		int nsignal = EVENT_SIGNAL(ev);
-		struct timespec timeout = { 0, 0 };
-
-		assert(nsignal >= 0 && nsignal < NSIG);
-		TAILQ_REMOVE(&kqop->evsigevents[nsignal], ev, ev_signal_next);
-		if (TAILQ_EMPTY(&kqop->evsigevents[nsignal])) {
-			memset(&kev, 0, sizeof(kev));
-			kev.ident = nsignal;
-			kev.filter = EVFILT_SIGNAL;
-			kev.flags = EV_DELETE;
-		
-			/* Because we insert signal events
-			 * immediately, we need to delete them
-			 * immediately, too */
-			if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1)
-				return (-1);
-
-			if (_evsignal_restore_handler(ev->ev_base,
-				nsignal) == -1)
-				return (-1);
-		}
-
-		ev->ev_flags &= ~EVLIST_X_KQINKERNEL;
-		return (0);
-	}
-
-	if (ev->ev_events & EV_READ) {
- 		memset(&kev, 0, sizeof(kev));
-		kev.ident = ev->ev_fd;
-		kev.filter = EVFILT_READ;
-		kev.flags = EV_DELETE;
-		
-		if (kq_insert(kqop, &kev) == -1)
-			return (-1);
-
-		ev->ev_flags &= ~EVLIST_X_KQINKERNEL;
-	}
-
-	if (ev->ev_events & EV_WRITE) {
- 		memset(&kev, 0, sizeof(kev));
-		kev.ident = ev->ev_fd;
-		kev.filter = EVFILT_WRITE;
-		kev.flags = EV_DELETE;
-		
-		if (kq_insert(kqop, &kev) == -1)
-			return (-1);
-
-		ev->ev_flags &= ~EVLIST_X_KQINKERNEL;
-	}
-
-	return (0);
-}
-
-static void
-kq_dealloc(struct event_base *base, void *arg)
-{
-	struct kqop *kqop = arg;
-
-	evsignal_dealloc(base);
-
-	if (kqop->changes)
-		free(kqop->changes);
-	if (kqop->events)
-		free(kqop->events);
-	if (kqop->kq >= 0 && kqop->pid == getpid())
-		close(kqop->kq);
-
-	memset(kqop, 0, sizeof(struct kqop));
-	free(kqop);
-}
diff --git a/base/third_party/libevent/linux/config.h b/base/third_party/libevent/linux/config.h
deleted file mode 100644
index c01ceb5..0000000
--- a/base/third_party/libevent/linux/config.h
+++ /dev/null
@@ -1,266 +0,0 @@
-/* config.h.  Generated from config.h.in by configure.  */
-/* config.h.in.  Generated from configure.in by autoheader.  */
-
-/* Define if clock_gettime is available in libc */
-#define DNS_USE_CPU_CLOCK_FOR_ID 1
-
-/* Define is no secure id variant is available */
-/* #undef DNS_USE_GETTIMEOFDAY_FOR_ID */
-
-/* Define to 1 if you have the `clock_gettime' function. */
-#define HAVE_CLOCK_GETTIME 1
-
-/* Define if /dev/poll is available */
-/* #undef HAVE_DEVPOLL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if your system supports the epoll system calls */
-#define HAVE_EPOLL 1
-
-/* Define to 1 if you have the `epoll_ctl' function. */
-#define HAVE_EPOLL_CTL 1
-
-/* Define if your system supports event ports */
-/* #undef HAVE_EVENT_PORTS */
-
-/* Define to 1 if you have the `fcntl' function. */
-#define HAVE_FCNTL 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H 1
-
-/* Define to 1 if the system has the type `fd_mask'. */
-#define HAVE_FD_MASK 1
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#define HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the `getegid' function. */
-#define HAVE_GETEGID 1
-
-/* Define to 1 if you have the `geteuid' function. */
-#define HAVE_GETEUID 1
-
-/* Define to 1 if you have the `getnameinfo' function. */
-#define HAVE_GETNAMEINFO 1
-
-/* Define to 1 if you have the `gettimeofday' function. */
-#define HAVE_GETTIMEOFDAY 1
-
-/* Define to 1 if you have the `inet_ntop' function. */
-#define HAVE_INET_NTOP 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `issetugid' function. */
-/* #undef HAVE_ISSETUGID */
-
-/* Define to 1 if you have the `kqueue' function. */
-/* #undef HAVE_KQUEUE */
-
-/* Define to 1 if you have the `nsl' library (-lnsl). */
-#define HAVE_LIBNSL 1
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-#define HAVE_LIBRESOLV 1
-
-/* Define to 1 if you have the `rt' library (-lrt). */
-#define HAVE_LIBRT 1
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-/* #undef HAVE_LIBSOCKET */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netinet/in6.h> header file. */
-/* #undef HAVE_NETINET_IN6_H */
-
-/* Define to 1 if you have the `poll' function. */
-#define HAVE_POLL 1
-
-/* Define to 1 if you have the <poll.h> header file. */
-#define HAVE_POLL_H 1
-
-/* Define to 1 if you have the `port_create' function. */
-/* #undef HAVE_PORT_CREATE */
-
-/* Define to 1 if you have the <port.h> header file. */
-/* #undef HAVE_PORT_H */
-
-/* Define to 1 if you have the `select' function. */
-#define HAVE_SELECT 1
-
-/* Define if F_SETFD is defined in <fcntl.h> */
-#define HAVE_SETFD 1
-
-/* Define to 1 if you have the `sigaction' function. */
-#define HAVE_SIGACTION 1
-
-/* Define to 1 if you have the `signal' function. */
-#define HAVE_SIGNAL 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the <stdarg.h> header file. */
-#define HAVE_STDARG_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-/* #undef HAVE_STRLCPY */
-
-/* Define to 1 if you have the `strsep' function. */
-#define HAVE_STRSEP 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-#define HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the `strtoll' function. */
-#define HAVE_STRTOLL 1
-
-/* Define to 1 if the system has the type `struct in6_addr'. */
-#define HAVE_STRUCT_IN6_ADDR 1
-
-/* Define to 1 if you have the <sys/devpoll.h> header file. */
-/* #undef HAVE_SYS_DEVPOLL_H */
-
-/* Define to 1 if you have the <sys/epoll.h> header file. */
-#define HAVE_SYS_EPOLL_H 1
-
-/* Define to 1 if you have the <sys/event.h> header file. */
-/* #undef HAVE_SYS_EVENT_H */
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-#define HAVE_SYS_IOCTL_H 1
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/queue.h> header file. */
-#define HAVE_SYS_QUEUE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#define HAVE_SYS_SELECT_H 1
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
-#define HAVE_TAILQFOREACH 1
-
-/* Define if timeradd is defined in <sys/time.h> */
-#define HAVE_TIMERADD 1
-
-/* Define if timerclear is defined in <sys/time.h> */
-#define HAVE_TIMERCLEAR 1
-
-/* Define if timercmp is defined in <sys/time.h> */
-#define HAVE_TIMERCMP 1
-
-/* Define if timerisset is defined in <sys/time.h> */
-#define HAVE_TIMERISSET 1
-
-/* Define to 1 if the system has the type `uint16_t'. */
-#define HAVE_UINT16_T 1
-
-/* Define to 1 if the system has the type `uint32_t'. */
-#define HAVE_UINT32_T 1
-
-/* Define to 1 if the system has the type `uint64_t'. */
-#define HAVE_UINT64_T 1
-
-/* Define to 1 if the system has the type `uint8_t'. */
-#define HAVE_UINT8_T 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `vasprintf' function. */
-#define HAVE_VASPRINTF 1
-
-/* Define if kqueue works correctly with pipes */
-/* #undef HAVE_WORKING_KQUEUE */
-
-/* Name of package */
-#define PACKAGE "libevent"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT ""
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME ""
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING ""
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION ""
-
-/* The size of `int', as computed by sizeof. */
-#define SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define SIZEOF_LONG 8
-
-/* The size of `long long', as computed by sizeof. */
-#define SIZEOF_LONG_LONG 8
-
-/* The size of `short', as computed by sizeof. */
-#define SIZEOF_SHORT 2
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define TIME_WITH_SYS_TIME 1
-
-/* Version number of package */
-#define VERSION "1.4.13-stable"
-
-/* Define to appropriate substitue if compiler doesnt have __func__ */
-/* #undef __func__ */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef const */
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
-   calls it, or to nothing if 'inline' is not supported under any name.  */
-#ifndef __cplusplus
-/* #undef inline */
-#endif
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef pid_t */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-/* Define to unsigned int if you dont have it */
-/* #undef socklen_t */
diff --git a/base/third_party/libevent/linux/event-config.h b/base/third_party/libevent/linux/event-config.h
deleted file mode 100644
index 2203253..0000000
--- a/base/third_party/libevent/linux/event-config.h
+++ /dev/null
@@ -1,284 +0,0 @@
-/* event-config.h
- * Generated by autoconf; post-processed by libevent.
- * Do not edit this file.
- * Do not rely on macros in this file existing in later versions.
- */
-#ifndef _EVENT_CONFIG_H_
-#define _EVENT_CONFIG_H_
-/* config.h.  Generated from config.h.in by configure.  */
-/* config.h.in.  Generated from configure.in by autoheader.  */
-
-/* Define if clock_gettime is available in libc */
-#define _EVENT_DNS_USE_CPU_CLOCK_FOR_ID 1
-
-/* Define is no secure id variant is available */
-/* #undef _EVENT_DNS_USE_GETTIMEOFDAY_FOR_ID */
-
-/* Define to 1 if you have the `clock_gettime' function. */
-#define _EVENT_HAVE_CLOCK_GETTIME 1
-
-/* Define if /dev/poll is available */
-/* #undef _EVENT_HAVE_DEVPOLL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define _EVENT_HAVE_DLFCN_H 1
-
-/* Define if your system supports the epoll system calls */
-#define _EVENT_HAVE_EPOLL 1
-
-/* Define to 1 if you have the `epoll_ctl' function. */
-#define _EVENT_HAVE_EPOLL_CTL 1
-
-/* Define if your system supports event ports */
-/* #undef _EVENT_HAVE_EVENT_PORTS */
-
-/* Define to 1 if you have the `fcntl' function. */
-#define _EVENT_HAVE_FCNTL 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define _EVENT_HAVE_FCNTL_H 1
-
-/* Define to 1 if the system has the type `fd_mask'. */
-#define _EVENT_HAVE_FD_MASK 1
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#define _EVENT_HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the `getegid' function. */
-#define _EVENT_HAVE_GETEGID 1
-
-/* Define to 1 if you have the `geteuid' function. */
-#define _EVENT_HAVE_GETEUID 1
-
-/* Define to 1 if you have the `getnameinfo' function. */
-#define _EVENT_HAVE_GETNAMEINFO 1
-
-/* Define to 1 if you have the `gettimeofday' function. */
-#define _EVENT_HAVE_GETTIMEOFDAY 1
-
-/* Define to 1 if you have the `inet_ntop' function. */
-#define _EVENT_HAVE_INET_NTOP 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define _EVENT_HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `issetugid' function. */
-/* #undef _EVENT_HAVE_ISSETUGID */
-
-/* Define to 1 if you have the `kqueue' function. */
-/* #undef _EVENT_HAVE_KQUEUE */
-
-/* Define to 1 if you have the `nsl' library (-lnsl). */
-#define _EVENT_HAVE_LIBNSL 1
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-#define _EVENT_HAVE_LIBRESOLV 1
-
-/* Define to 1 if you have the `rt' library (-lrt). */
-#define _EVENT_HAVE_LIBRT 1
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-/* #undef _EVENT_HAVE_LIBSOCKET */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define _EVENT_HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netinet/in6.h> header file. */
-/* #undef _EVENT_HAVE_NETINET_IN6_H */
-
-/* Define to 1 if you have the `poll' function. */
-#define _EVENT_HAVE_POLL 1
-
-/* Define to 1 if you have the <poll.h> header file. */
-#define _EVENT_HAVE_POLL_H 1
-
-/* Define to 1 if you have the `port_create' function. */
-/* #undef _EVENT_HAVE_PORT_CREATE */
-
-/* Define to 1 if you have the <port.h> header file. */
-/* #undef _EVENT_HAVE_PORT_H */
-
-/* Define to 1 if you have the `select' function. */
-#define _EVENT_HAVE_SELECT 1
-
-/* Define if F_SETFD is defined in <fcntl.h> */
-#define _EVENT_HAVE_SETFD 1
-
-/* Define to 1 if you have the `sigaction' function. */
-#define _EVENT_HAVE_SIGACTION 1
-
-/* Define to 1 if you have the `signal' function. */
-#define _EVENT_HAVE_SIGNAL 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define _EVENT_HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the <stdarg.h> header file. */
-#define _EVENT_HAVE_STDARG_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define _EVENT_HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define _EVENT_HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define _EVENT_HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define _EVENT_HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-/* #undef _EVENT_HAVE_STRLCPY */
-
-/* Define to 1 if you have the `strsep' function. */
-#define _EVENT_HAVE_STRSEP 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-#define _EVENT_HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the `strtoll' function. */
-#define _EVENT_HAVE_STRTOLL 1
-
-/* Define to 1 if the system has the type `struct in6_addr'. */
-#define _EVENT_HAVE_STRUCT_IN6_ADDR 1
-
-/* Define to 1 if you have the <sys/devpoll.h> header file. */
-/* #undef _EVENT_HAVE_SYS_DEVPOLL_H */
-
-/* Define to 1 if you have the <sys/epoll.h> header file. */
-#define _EVENT_HAVE_SYS_EPOLL_H 1
-
-/* Define to 1 if you have the <sys/event.h> header file. */
-/* #undef _EVENT_HAVE_SYS_EVENT_H */
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-#define _EVENT_HAVE_SYS_IOCTL_H 1
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define _EVENT_HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/queue.h> header file. */
-#define _EVENT_HAVE_SYS_QUEUE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#define _EVENT_HAVE_SYS_SELECT_H 1
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define _EVENT_HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define _EVENT_HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define _EVENT_HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define _EVENT_HAVE_SYS_TYPES_H 1
-
-/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
-#define _EVENT_HAVE_TAILQFOREACH 1
-
-/* Define if timeradd is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERADD 1
-
-/* Define if timerclear is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERCLEAR 1
-
-/* Define if timercmp is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERCMP 1
-
-/* Define if timerisset is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERISSET 1
-
-/* Define to 1 if the system has the type `uint16_t'. */
-#define _EVENT_HAVE_UINT16_T 1
-
-/* Define to 1 if the system has the type `uint32_t'. */
-#define _EVENT_HAVE_UINT32_T 1
-
-/* Define to 1 if the system has the type `uint64_t'. */
-#define _EVENT_HAVE_UINT64_T 1
-
-/* Define to 1 if the system has the type `uint8_t'. */
-#define _EVENT_HAVE_UINT8_T 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define _EVENT_HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `vasprintf' function. */
-#define _EVENT_HAVE_VASPRINTF 1
-
-/* Define if kqueue works correctly with pipes */
-/* #undef _EVENT_HAVE_WORKING_KQUEUE */
-
-/* Define to the sub-directory in which libtool stores uninstalled libraries.
-   */
-#define _EVENT_LT_OBJDIR ".libs/"
-
-/* Numeric representation of the version */
-#define _EVENT_NUMERIC_VERSION 0x01040f00
-
-/* Name of package */
-#define _EVENT_PACKAGE "libevent"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define _EVENT_PACKAGE_BUGREPORT ""
-
-/* Define to the full name of this package. */
-#define _EVENT_PACKAGE_NAME ""
-
-/* Define to the full name and version of this package. */
-#define _EVENT_PACKAGE_STRING ""
-
-/* Define to the one symbol short name of this package. */
-#define _EVENT_PACKAGE_TARNAME ""
-
-/* Define to the home page for this package. */
-#define _EVENT_PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define _EVENT_PACKAGE_VERSION ""
-
-/* The size of `int', as computed by sizeof. */
-#define _EVENT_SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG 8
-
-/* The size of `long long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG_LONG 8
-
-/* The size of `short', as computed by sizeof. */
-#define _EVENT_SIZEOF_SHORT 2
-
-/* Define to 1 if you have the ANSI C header files. */
-#define _EVENT_STDC_HEADERS 1
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define _EVENT_TIME_WITH_SYS_TIME 1
-
-/* Version number of package */
-#define _EVENT_VERSION "1.4.15"
-
-/* Define to appropriate substitue if compiler doesnt have __func__ */
-/* #undef _EVENT___func__ */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef _EVENT_const */
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
-   calls it, or to nothing if 'inline' is not supported under any name.  */
-#ifndef _EVENT___cplusplus
-/* #undef _EVENT_inline */
-#endif
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef _EVENT_pid_t */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef _EVENT_size_t */
-
-/* Define to unsigned int if you dont have it */
-/* #undef _EVENT_socklen_t */
-#endif
diff --git a/base/third_party/libevent/log.c b/base/third_party/libevent/log.c
deleted file mode 100644
index 48ebb26..0000000
--- a/base/third_party/libevent/log.c
+++ /dev/null
@@ -1,187 +0,0 @@
-/*	$OpenBSD: err.c,v 1.2 2002/06/25 15:50:15 mickey Exp $	*/
-
-/*
- * log.c
- *
- * Based on err.c, which was adapted from OpenBSD libc *err* *warn* code.
- *
- * Copyright (c) 2005 Nick Mathewson <nickm@freehaven.net>
- *
- * Copyright (c) 2000 Dug Song <dugsong@monkey.org>
- *
- * Copyright (c) 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-#endif
-#include <sys/types.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#else
-#include <sys/_libevent_time.h>
-#endif
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <errno.h>
-#include "event.h"
-
-#include "log.h"
-#include "evutil.h"
-
-static void _warn_helper(int severity, int log_errno, const char *fmt,
-                         va_list ap);
-static void event_log(int severity, const char *msg);
-
-void
-event_err(int eval, const char *fmt, ...)
-{
-	va_list ap;
-	
-	va_start(ap, fmt);
-	_warn_helper(_EVENT_LOG_ERR, errno, fmt, ap);
-	va_end(ap);
-	exit(eval);
-}
-
-void
-event_warn(const char *fmt, ...)
-{
-	va_list ap;
-	
-	va_start(ap, fmt);
-	_warn_helper(_EVENT_LOG_WARN, errno, fmt, ap);
-	va_end(ap);
-}
-
-void
-event_errx(int eval, const char *fmt, ...)
-{
-	va_list ap;
-	
-	va_start(ap, fmt);
-	_warn_helper(_EVENT_LOG_ERR, -1, fmt, ap);
-	va_end(ap);
-	exit(eval);
-}
-
-void
-event_warnx(const char *fmt, ...)
-{
-	va_list ap;
-	
-	va_start(ap, fmt);
-	_warn_helper(_EVENT_LOG_WARN, -1, fmt, ap);
-	va_end(ap);
-}
-
-void
-event_msgx(const char *fmt, ...)
-{
-	va_list ap;
-	
-	va_start(ap, fmt);
-	_warn_helper(_EVENT_LOG_MSG, -1, fmt, ap);
-	va_end(ap);
-}
-
-void
-_event_debugx(const char *fmt, ...)
-{
-	va_list ap;
-	
-	va_start(ap, fmt);
-	_warn_helper(_EVENT_LOG_DEBUG, -1, fmt, ap);
-	va_end(ap);
-}
-
-static void
-_warn_helper(int severity, int log_errno, const char *fmt, va_list ap)
-{
-	char buf[1024];
-	size_t len;
-
-	if (fmt != NULL)
-		evutil_vsnprintf(buf, sizeof(buf), fmt, ap);
-	else
-		buf[0] = '\0';
-
-	if (log_errno >= 0) {
-		len = strlen(buf);
-		if (len < sizeof(buf) - 3) {
-			evutil_snprintf(buf + len, sizeof(buf) - len, ": %s",
-			    strerror(log_errno));
-		}
-	}
-
-	event_log(severity, buf);
-}
-
-static event_log_cb log_fn = NULL;
-
-void
-event_set_log_callback(event_log_cb cb)
-{
-	log_fn = cb;
-}
-
-static void
-event_log(int severity, const char *msg)
-{
-	if (log_fn)
-		log_fn(severity, msg);
-	else {
-		const char *severity_str;
-		switch (severity) {
-		case _EVENT_LOG_DEBUG:
-			severity_str = "debug";
-			break;
-		case _EVENT_LOG_MSG:
-			severity_str = "msg";
-			break;
-		case _EVENT_LOG_WARN:
-			severity_str = "warn";
-			break;
-		case _EVENT_LOG_ERR:
-			severity_str = "err";
-			break;
-		default:
-			severity_str = "???";
-			break;
-		}
-		(void)fprintf(stderr, "[%s] %s\n", severity_str, msg);
-	}
-}
diff --git a/base/third_party/libevent/log.h b/base/third_party/libevent/log.h
deleted file mode 100644
index 7bc6632..0000000
--- a/base/third_party/libevent/log.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2000-2004 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef _LOG_H_
-#define _LOG_H_
-
-#ifdef __GNUC__
-#define EV_CHECK_FMT(a,b) __attribute__((format(printf, a, b)))
-#else
-#define EV_CHECK_FMT(a,b)
-#endif
-
-void event_err(int eval, const char *fmt, ...) EV_CHECK_FMT(2,3);
-void event_warn(const char *fmt, ...) EV_CHECK_FMT(1,2);
-void event_errx(int eval, const char *fmt, ...) EV_CHECK_FMT(2,3);
-void event_warnx(const char *fmt, ...) EV_CHECK_FMT(1,2);
-void event_msgx(const char *fmt, ...) EV_CHECK_FMT(1,2);
-void _event_debugx(const char *fmt, ...) EV_CHECK_FMT(1,2);
-
-#ifdef USE_DEBUG
-#define event_debug(x) _event_debugx x
-#else
-#define event_debug(x) do {;} while (0)
-#endif
-
-#undef EV_CHECK_FMT
-
-#endif
diff --git a/base/third_party/libevent/m4/.dummy b/base/third_party/libevent/m4/.dummy
deleted file mode 100644
index a0a72d6..0000000
--- a/base/third_party/libevent/m4/.dummy
+++ /dev/null
@@ -1 +0,0 @@
-(This dummy file exists so that git will create the m4 directory)
diff --git a/base/third_party/libevent/mac/config.h b/base/third_party/libevent/mac/config.h
deleted file mode 100644
index f73f0c6..0000000
--- a/base/third_party/libevent/mac/config.h
+++ /dev/null
@@ -1,266 +0,0 @@
-/* config.h.  Generated from config.h.in by configure.  */
-/* config.h.in.  Generated from configure.in by autoheader.  */
-
-/* Define if clock_gettime is available in libc */
-/* #undef DNS_USE_CPU_CLOCK_FOR_ID */
-
-/* Define is no secure id variant is available */
-#define DNS_USE_GETTIMEOFDAY_FOR_ID 1
-
-/* Define to 1 if you have the `clock_gettime' function. */
-/* #undef HAVE_CLOCK_GETTIME */
-
-/* Define if /dev/poll is available */
-/* #undef HAVE_DEVPOLL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if your system supports the epoll system calls */
-/* #undef HAVE_EPOLL */
-
-/* Define to 1 if you have the `epoll_ctl' function. */
-/* #undef HAVE_EPOLL_CTL */
-
-/* Define if your system supports event ports */
-/* #undef HAVE_EVENT_PORTS */
-
-/* Define to 1 if you have the `fcntl' function. */
-#define HAVE_FCNTL 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H 1
-
-/* Define to 1 if the system has the type `fd_mask'. */
-#define HAVE_FD_MASK 1
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#define HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the `getegid' function. */
-#define HAVE_GETEGID 1
-
-/* Define to 1 if you have the `geteuid' function. */
-#define HAVE_GETEUID 1
-
-/* Define to 1 if you have the `getnameinfo' function. */
-#define HAVE_GETNAMEINFO 1
-
-/* Define to 1 if you have the `gettimeofday' function. */
-#define HAVE_GETTIMEOFDAY 1
-
-/* Define to 1 if you have the `inet_ntop' function. */
-#define HAVE_INET_NTOP 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `issetugid' function. */
-#define HAVE_ISSETUGID 1
-
-/* Define to 1 if you have the `kqueue' function. */
-#define HAVE_KQUEUE 1
-
-/* Define to 1 if you have the `nsl' library (-lnsl). */
-/* #undef HAVE_LIBNSL */
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-#define HAVE_LIBRESOLV 1
-
-/* Define to 1 if you have the `rt' library (-lrt). */
-/* #undef HAVE_LIBRT */
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-/* #undef HAVE_LIBSOCKET */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netinet/in6.h> header file. */
-/* #undef HAVE_NETINET_IN6_H */
-
-/* Define to 1 if you have the `poll' function. */
-#define HAVE_POLL 1
-
-/* Define to 1 if you have the <poll.h> header file. */
-#define HAVE_POLL_H 1
-
-/* Define to 1 if you have the `port_create' function. */
-/* #undef HAVE_PORT_CREATE */
-
-/* Define to 1 if you have the <port.h> header file. */
-/* #undef HAVE_PORT_H */
-
-/* Define to 1 if you have the `select' function. */
-#define HAVE_SELECT 1
-
-/* Define if F_SETFD is defined in <fcntl.h> */
-#define HAVE_SETFD 1
-
-/* Define to 1 if you have the `sigaction' function. */
-#define HAVE_SIGACTION 1
-
-/* Define to 1 if you have the `signal' function. */
-#define HAVE_SIGNAL 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the <stdarg.h> header file. */
-#define HAVE_STDARG_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-#define HAVE_STRLCPY 1
-
-/* Define to 1 if you have the `strsep' function. */
-#define HAVE_STRSEP 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-#define HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the `strtoll' function. */
-#define HAVE_STRTOLL 1
-
-/* Define to 1 if the system has the type `struct in6_addr'. */
-#define HAVE_STRUCT_IN6_ADDR 1
-
-/* Define to 1 if you have the <sys/devpoll.h> header file. */
-/* #undef HAVE_SYS_DEVPOLL_H */
-
-/* Define to 1 if you have the <sys/epoll.h> header file. */
-/* #undef HAVE_SYS_EPOLL_H */
-
-/* Define to 1 if you have the <sys/event.h> header file. */
-#define HAVE_SYS_EVENT_H 1
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-#define HAVE_SYS_IOCTL_H 1
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/queue.h> header file. */
-#define HAVE_SYS_QUEUE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#define HAVE_SYS_SELECT_H 1
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
-#define HAVE_TAILQFOREACH 1
-
-/* Define if timeradd is defined in <sys/time.h> */
-#define HAVE_TIMERADD 1
-
-/* Define if timerclear is defined in <sys/time.h> */
-#define HAVE_TIMERCLEAR 1
-
-/* Define if timercmp is defined in <sys/time.h> */
-#define HAVE_TIMERCMP 1
-
-/* Define if timerisset is defined in <sys/time.h> */
-#define HAVE_TIMERISSET 1
-
-/* Define to 1 if the system has the type `uint16_t'. */
-#define HAVE_UINT16_T 1
-
-/* Define to 1 if the system has the type `uint32_t'. */
-#define HAVE_UINT32_T 1
-
-/* Define to 1 if the system has the type `uint64_t'. */
-#define HAVE_UINT64_T 1
-
-/* Define to 1 if the system has the type `uint8_t'. */
-#define HAVE_UINT8_T 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `vasprintf' function. */
-#define HAVE_VASPRINTF 1
-
-/* Define if kqueue works correctly with pipes */
-#define HAVE_WORKING_KQUEUE 1
-
-/* Name of package */
-#define PACKAGE "libevent"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT ""
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME ""
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING ""
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION ""
-
-/* The size of `int', as computed by sizeof. */
-#define SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define SIZEOF_LONG 4
-
-/* The size of `long long', as computed by sizeof. */
-#define SIZEOF_LONG_LONG 8
-
-/* The size of `short', as computed by sizeof. */
-#define SIZEOF_SHORT 2
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define TIME_WITH_SYS_TIME 1
-
-/* Version number of package */
-#define VERSION "1.4.13-stable"
-
-/* Define to appropriate substitue if compiler doesnt have __func__ */
-/* #undef __func__ */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef const */
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
-   calls it, or to nothing if 'inline' is not supported under any name.  */
-#ifndef __cplusplus
-/* #undef inline */
-#endif
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef pid_t */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-/* Define to unsigned int if you dont have it */
-/* #undef socklen_t */
diff --git a/base/third_party/libevent/mac/event-config.h b/base/third_party/libevent/mac/event-config.h
deleted file mode 100644
index 92e212d..0000000
--- a/base/third_party/libevent/mac/event-config.h
+++ /dev/null
@@ -1,284 +0,0 @@
-/* event-config.h
- * Generated by autoconf; post-processed by libevent.
- * Do not edit this file.
- * Do not rely on macros in this file existing in later versions.
- */
-#ifndef _EVENT_CONFIG_H_
-#define _EVENT_CONFIG_H_
-/* config.h.  Generated from config.h.in by configure.  */
-/* config.h.in.  Generated from configure.in by autoheader.  */
-
-/* Define if clock_gettime is available in libc */
-/* #undef _EVENT_DNS_USE_CPU_CLOCK_FOR_ID */
-
-/* Define is no secure id variant is available */
-#define _EVENT_DNS_USE_GETTIMEOFDAY_FOR_ID 1
-
-/* Define to 1 if you have the `clock_gettime' function. */
-/* #undef _EVENT_HAVE_CLOCK_GETTIME */
-
-/* Define if /dev/poll is available */
-/* #undef _EVENT_HAVE_DEVPOLL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define _EVENT_HAVE_DLFCN_H 1
-
-/* Define if your system supports the epoll system calls */
-/* #undef _EVENT_HAVE_EPOLL */
-
-/* Define to 1 if you have the `epoll_ctl' function. */
-/* #undef _EVENT_HAVE_EPOLL_CTL */
-
-/* Define if your system supports event ports */
-/* #undef _EVENT_HAVE_EVENT_PORTS */
-
-/* Define to 1 if you have the `fcntl' function. */
-#define _EVENT_HAVE_FCNTL 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define _EVENT_HAVE_FCNTL_H 1
-
-/* Define to 1 if the system has the type `fd_mask'. */
-#define _EVENT_HAVE_FD_MASK 1
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#define _EVENT_HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the `getegid' function. */
-#define _EVENT_HAVE_GETEGID 1
-
-/* Define to 1 if you have the `geteuid' function. */
-#define _EVENT_HAVE_GETEUID 1
-
-/* Define to 1 if you have the `getnameinfo' function. */
-#define _EVENT_HAVE_GETNAMEINFO 1
-
-/* Define to 1 if you have the `gettimeofday' function. */
-#define _EVENT_HAVE_GETTIMEOFDAY 1
-
-/* Define to 1 if you have the `inet_ntop' function. */
-#define _EVENT_HAVE_INET_NTOP 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define _EVENT_HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `issetugid' function. */
-#define _EVENT_HAVE_ISSETUGID 1
-
-/* Define to 1 if you have the `kqueue' function. */
-#define _EVENT_HAVE_KQUEUE 1
-
-/* Define to 1 if you have the `nsl' library (-lnsl). */
-/* #undef _EVENT_HAVE_LIBNSL */
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-#define _EVENT_HAVE_LIBRESOLV 1
-
-/* Define to 1 if you have the `rt' library (-lrt). */
-/* #undef _EVENT_HAVE_LIBRT */
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-/* #undef _EVENT_HAVE_LIBSOCKET */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define _EVENT_HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netinet/in6.h> header file. */
-/* #undef _EVENT_HAVE_NETINET_IN6_H */
-
-/* Define to 1 if you have the `poll' function. */
-#define _EVENT_HAVE_POLL 1
-
-/* Define to 1 if you have the <poll.h> header file. */
-#define _EVENT_HAVE_POLL_H 1
-
-/* Define to 1 if you have the `port_create' function. */
-/* #undef _EVENT_HAVE_PORT_CREATE */
-
-/* Define to 1 if you have the <port.h> header file. */
-/* #undef _EVENT_HAVE_PORT_H */
-
-/* Define to 1 if you have the `select' function. */
-#define _EVENT_HAVE_SELECT 1
-
-/* Define if F_SETFD is defined in <fcntl.h> */
-#define _EVENT_HAVE_SETFD 1
-
-/* Define to 1 if you have the `sigaction' function. */
-#define _EVENT_HAVE_SIGACTION 1
-
-/* Define to 1 if you have the `signal' function. */
-#define _EVENT_HAVE_SIGNAL 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define _EVENT_HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the <stdarg.h> header file. */
-#define _EVENT_HAVE_STDARG_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define _EVENT_HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define _EVENT_HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define _EVENT_HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define _EVENT_HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-#define _EVENT_HAVE_STRLCPY 1
-
-/* Define to 1 if you have the `strsep' function. */
-#define _EVENT_HAVE_STRSEP 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-#define _EVENT_HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the `strtoll' function. */
-#define _EVENT_HAVE_STRTOLL 1
-
-/* Define to 1 if the system has the type `struct in6_addr'. */
-#define _EVENT_HAVE_STRUCT_IN6_ADDR 1
-
-/* Define to 1 if you have the <sys/devpoll.h> header file. */
-/* #undef _EVENT_HAVE_SYS_DEVPOLL_H */
-
-/* Define to 1 if you have the <sys/epoll.h> header file. */
-/* #undef _EVENT_HAVE_SYS_EPOLL_H */
-
-/* Define to 1 if you have the <sys/event.h> header file. */
-#define _EVENT_HAVE_SYS_EVENT_H 1
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-#define _EVENT_HAVE_SYS_IOCTL_H 1
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define _EVENT_HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/queue.h> header file. */
-#define _EVENT_HAVE_SYS_QUEUE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#define _EVENT_HAVE_SYS_SELECT_H 1
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define _EVENT_HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define _EVENT_HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define _EVENT_HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define _EVENT_HAVE_SYS_TYPES_H 1
-
-/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
-#define _EVENT_HAVE_TAILQFOREACH 1
-
-/* Define if timeradd is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERADD 1
-
-/* Define if timerclear is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERCLEAR 1
-
-/* Define if timercmp is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERCMP 1
-
-/* Define if timerisset is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERISSET 1
-
-/* Define to 1 if the system has the type `uint16_t'. */
-#define _EVENT_HAVE_UINT16_T 1
-
-/* Define to 1 if the system has the type `uint32_t'. */
-#define _EVENT_HAVE_UINT32_T 1
-
-/* Define to 1 if the system has the type `uint64_t'. */
-#define _EVENT_HAVE_UINT64_T 1
-
-/* Define to 1 if the system has the type `uint8_t'. */
-#define _EVENT_HAVE_UINT8_T 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define _EVENT_HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `vasprintf' function. */
-#define _EVENT_HAVE_VASPRINTF 1
-
-/* Define if kqueue works correctly with pipes */
-#define _EVENT_HAVE_WORKING_KQUEUE 1
-
-/* Define to the sub-directory in which libtool stores uninstalled libraries.
-   */
-#define _EVENT_LT_OBJDIR ".libs/"
-
-/* Numeric representation of the version */
-#define _EVENT_NUMERIC_VERSION 0x01040f00
-
-/* Name of package */
-#define _EVENT_PACKAGE "libevent"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define _EVENT_PACKAGE_BUGREPORT ""
-
-/* Define to the full name of this package. */
-#define _EVENT_PACKAGE_NAME ""
-
-/* Define to the full name and version of this package. */
-#define _EVENT_PACKAGE_STRING ""
-
-/* Define to the one symbol short name of this package. */
-#define _EVENT_PACKAGE_TARNAME ""
-
-/* Define to the home page for this package. */
-#define _EVENT_PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define _EVENT_PACKAGE_VERSION ""
-
-/* The size of `int', as computed by sizeof. */
-#define _EVENT_SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG 4
-
-/* The size of `long long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG_LONG 8
-
-/* The size of `short', as computed by sizeof. */
-#define _EVENT_SIZEOF_SHORT 2
-
-/* Define to 1 if you have the ANSI C header files. */
-#define _EVENT_STDC_HEADERS 1
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define _EVENT_TIME_WITH_SYS_TIME 1
-
-/* Version number of package */
-#define _EVENT_VERSION "1.4.15"
-
-/* Define to appropriate substitue if compiler doesnt have __func__ */
-/* #undef _EVENT___func__ */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef _EVENT_const */
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
-   calls it, or to nothing if 'inline' is not supported under any name.  */
-#ifndef _EVENT___cplusplus
-/* #undef _EVENT_inline */
-#endif
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef _EVENT_pid_t */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef _EVENT_size_t */
-
-/* Define to unsigned int if you dont have it */
-/* #undef _EVENT_socklen_t */
-#endif
diff --git a/base/third_party/libevent/min_heap.h b/base/third_party/libevent/min_heap.h
deleted file mode 100644
index 14d8e37..0000000
--- a/base/third_party/libevent/min_heap.h
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (c) 2006 Maxim Yegorushkin <maxim.yegorushkin@gmail.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef _MIN_HEAP_H_
-#define _MIN_HEAP_H_
-
-#include "event.h"
-#include "evutil.h"
-
-typedef struct min_heap
-{
-    struct event** p;
-    unsigned n, a;
-} min_heap_t;
-
-static inline void           min_heap_ctor(min_heap_t* s);
-static inline void           min_heap_dtor(min_heap_t* s);
-static inline void           min_heap_elem_init(struct event* e);
-static inline int            min_heap_elem_greater(struct event *a, struct event *b);
-static inline int            min_heap_empty(min_heap_t* s);
-static inline unsigned       min_heap_size(min_heap_t* s);
-static inline struct event*  min_heap_top(min_heap_t* s);
-static inline int            min_heap_reserve(min_heap_t* s, unsigned n);
-static inline int            min_heap_push(min_heap_t* s, struct event* e);
-static inline struct event*  min_heap_pop(min_heap_t* s);
-static inline int            min_heap_erase(min_heap_t* s, struct event* e);
-static inline void           min_heap_shift_up_(min_heap_t* s, unsigned hole_index, struct event* e);
-static inline void           min_heap_shift_down_(min_heap_t* s, unsigned hole_index, struct event* e);
-
-int min_heap_elem_greater(struct event *a, struct event *b)
-{
-    return evutil_timercmp(&a->ev_timeout, &b->ev_timeout, >);
-}
-
-void min_heap_ctor(min_heap_t* s) { s->p = 0; s->n = 0; s->a = 0; }
-void min_heap_dtor(min_heap_t* s) { if(s->p) free(s->p); }
-void min_heap_elem_init(struct event* e) { e->min_heap_idx = -1; }
-int min_heap_empty(min_heap_t* s) { return 0u == s->n; }
-unsigned min_heap_size(min_heap_t* s) { return s->n; }
-struct event* min_heap_top(min_heap_t* s) { return s->n ? *s->p : 0; }
-
-int min_heap_push(min_heap_t* s, struct event* e)
-{
-    if(min_heap_reserve(s, s->n + 1))
-        return -1;
-    min_heap_shift_up_(s, s->n++, e);
-    return 0;
-}
-
-struct event* min_heap_pop(min_heap_t* s)
-{
-    if(s->n)
-    {
-        struct event* e = *s->p;
-        min_heap_shift_down_(s, 0u, s->p[--s->n]);
-        e->min_heap_idx = -1;
-        return e;
-    }
-    return 0;
-}
-
-int min_heap_erase(min_heap_t* s, struct event* e)
-{
-    if(((unsigned int)-1) != e->min_heap_idx)
-    {
-        struct event *last = s->p[--s->n];
-        unsigned parent = (e->min_heap_idx - 1) / 2;
-	/* we replace e with the last element in the heap.  We might need to
-	   shift it upward if it is less than its parent, or downward if it is
-	   greater than one or both its children. Since the children are known
-	   to be less than the parent, it can't need to shift both up and
-	   down. */
-        if (e->min_heap_idx > 0 && min_heap_elem_greater(s->p[parent], last))
-             min_heap_shift_up_(s, e->min_heap_idx, last);
-        else
-             min_heap_shift_down_(s, e->min_heap_idx, last);
-        e->min_heap_idx = -1;
-        return 0;
-    }
-    return -1;
-}
-
-int min_heap_reserve(min_heap_t* s, unsigned n)
-{
-    if(s->a < n)
-    {
-        struct event** p;
-        unsigned a = s->a ? s->a * 2 : 8;
-        if(a < n)
-            a = n;
-        if(!(p = (struct event**)realloc(s->p, a * sizeof *p)))
-            return -1;
-        s->p = p;
-        s->a = a;
-    }
-    return 0;
-}
-
-void min_heap_shift_up_(min_heap_t* s, unsigned hole_index, struct event* e)
-{
-    unsigned parent = (hole_index - 1) / 2;
-    while(hole_index && min_heap_elem_greater(s->p[parent], e))
-    {
-        (s->p[hole_index] = s->p[parent])->min_heap_idx = hole_index;
-        hole_index = parent;
-        parent = (hole_index - 1) / 2;
-    }
-    (s->p[hole_index] = e)->min_heap_idx = hole_index;
-}
-
-void min_heap_shift_down_(min_heap_t* s, unsigned hole_index, struct event* e)
-{
-    unsigned min_child = 2 * (hole_index + 1);
-    while(min_child <= s->n)
-	{
-        min_child -= min_child == s->n || min_heap_elem_greater(s->p[min_child], s->p[min_child - 1]);
-        if(!(min_heap_elem_greater(e, s->p[min_child])))
-            break;
-        (s->p[hole_index] = s->p[min_child])->min_heap_idx = hole_index;
-        hole_index = min_child;
-        min_child = 2 * (hole_index + 1);
-	}
-    min_heap_shift_up_(s, hole_index,  e);
-}
-
-#endif /* _MIN_HEAP_H_ */
diff --git a/base/third_party/libevent/nacl_nonsfi/config.h b/base/third_party/libevent/nacl_nonsfi/config.h
deleted file mode 100644
index 60c9dfe..0000000
--- a/base/third_party/libevent/nacl_nonsfi/config.h
+++ /dev/null
@@ -1,273 +0,0 @@
-/* Copied from Linux version and changed the features according the PNaCl
- * toolchain for the Non-SFI binary build, which is close to one under the
- * linux/ directory. The built binary will be running under Linux directly,
- * actually.
- */
-
-/* Define if clock_gettime is available in libc */
-#define DNS_USE_CPU_CLOCK_FOR_ID 1
-
-/* Define is no secure id variant is available */
-/* #undef DNS_USE_GETTIMEOFDAY_FOR_ID */
-
-/* Define to 1 if you have the `clock_gettime' function. */
-#define HAVE_CLOCK_GETTIME 1
-
-/* Define if /dev/poll is available */
-/* #undef HAVE_DEVPOLL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-/* #undef HAVE_DLFCN_H */
-
-/* Define if your system supports the epoll system calls */
-/* #undef HAVE_EPOLL */
-
-/* Define to 1 if you have the `epoll_ctl' function. */
-/* #undef HAVE_EPOLL_CTL */
-
-/* Define if your system supports event ports */
-/* #undef HAVE_EVENT_PORTS */
-
-/* Define to 1 if you have the `fcntl' function. */
-#define HAVE_FCNTL 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H 1
-
-/* Define to 1 if the system has the type `fd_mask'. */
-#define HAVE_FD_MASK 1
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#define HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the `getegid' function. */
-#define HAVE_GETEGID 1
-
-/* Define to 1 if you have the `geteuid' function. */
-#define HAVE_GETEUID 1
-
-/* Define to 1 if you have the `getnameinfo' function. */
-#define HAVE_GETNAMEINFO 1
-
-/* Define to 1 if you have the `gettimeofday' function. */
-#define HAVE_GETTIMEOFDAY 1
-
-/* Define to 1 if you have the `inet_ntop' function. */
-#define HAVE_INET_NTOP 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `issetugid' function. */
-/* #undef HAVE_ISSETUGID */
-
-/* Define to 1 if you have the `kqueue' function. */
-/* #undef HAVE_KQUEUE */
-
-/* Define to 1 if you have the `nsl' library (-lnsl). */
-#define HAVE_LIBNSL 1
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-#define HAVE_LIBRESOLV 1
-
-/* Define to 1 if you have the `rt' library (-lrt). */
-#define HAVE_LIBRT 1
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-/* #undef HAVE_LIBSOCKET */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netinet/in6.h> header file. */
-/* #undef HAVE_NETINET_IN6_H */
-
-/* Define to 1 if you have the `poll' function. */
-#define HAVE_POLL 1
-
-/* Define to 1 if you have the <poll.h> header file. */
-#define HAVE_POLL_H 1
-
-/* Define to 1 if you have the `port_create' function. */
-/* #undef HAVE_PORT_CREATE */
-
-/* Define to 1 if you have the <port.h> header file. */
-/* #undef HAVE_PORT_H */
-
-/* Define to 1 if you have the `select' function. */
-/* #undef HAVE_SELECT */
-
-/* Define if F_SETFD is defined in <fcntl.h> */
-#define HAVE_SETFD 1
-
-/* Note: The PNaCl toolchain prodives linux ABI's sigaction, named
- * linux_sigaction() in native_client/src/nonsfi/linux/linux_sys_private.c,
- * but newlib ABI sigaction() is not provided.
- */
-/* Define to 1 if you have the `sigaction' function. */
-/* #undef HAVE_SIGACTION */
-
-/* Define to 1 if you have the `signal' function. */
-/* #undef HAVE_SIGNAL */
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the <stdarg.h> header file. */
-#define HAVE_STDARG_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-/* #undef HAVE_STRLCPY */
-
-/* Define to 1 if you have the `strsep' function. */
-#define HAVE_STRSEP 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-#define HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the `strtoll' function. */
-#define HAVE_STRTOLL 1
-
-/* Define to 1 if the system has the type `struct in6_addr'. */
-#define HAVE_STRUCT_IN6_ADDR 1
-
-/* Define to 1 if you have the <sys/devpoll.h> header file. */
-/* #undef HAVE_SYS_DEVPOLL_H */
-
-/* Define to 1 if you have the <sys/epoll.h> header file. */
-#define HAVE_SYS_EPOLL_H 1
-
-/* Define to 1 if you have the <sys/event.h> header file. */
-/* #undef HAVE_SYS_EVENT_H */
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-/* #undef HAVE_SYS_IOCTL_H */
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/queue.h> header file. */
-#define HAVE_SYS_QUEUE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-/* #undef HAVE_SYS_SELECT_H */
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
-#define HAVE_TAILQFOREACH 1
-
-/* Define if timeradd is defined in <sys/time.h> */
-/* #undef HAVE_TIMERADD */
-
-/* Define if timerclear is defined in <sys/time.h> */
-/* #undef HAVE_TIMERCLEAR */
-
-/* Define if timercmp is defined in <sys/time.h> */
-/* #undef HAVE_TIMERCMP */
-
-/* Define if timerisset is defined in <sys/time.h> */
-/* #undef HAVE_TIMERISSET */
-
-/* Define to 1 if the system has the type `uint16_t'. */
-#define HAVE_UINT16_T 1
-
-/* Define to 1 if the system has the type `uint32_t'. */
-#define HAVE_UINT32_T 1
-
-/* Define to 1 if the system has the type `uint64_t'. */
-#define HAVE_UINT64_T 1
-
-/* Define to 1 if the system has the type `uint8_t'. */
-#define HAVE_UINT8_T 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `vasprintf' function. */
-/* #undef HAVE_VASPRINTF */
-
-/* Define if kqueue works correctly with pipes */
-/* #undef HAVE_WORKING_KQUEUE */
-
-/* Name of package */
-#define PACKAGE "libevent_nacl"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT ""
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME ""
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING ""
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION ""
-
-/* The size of `int', as computed by sizeof. */
-#define SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define SIZEOF_LONG 8
-
-/* The size of `long long', as computed by sizeof. */
-#define SIZEOF_LONG_LONG 8
-
-/* The size of `short', as computed by sizeof. */
-#define SIZEOF_SHORT 2
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define TIME_WITH_SYS_TIME 1
-
-/* Version number of package */
-#define VERSION "1.4.13-stable"
-
-/* Define to appropriate substitue if compiler doesnt have __func__ */
-/* #undef __func__ */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef const */
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
-   calls it, or to nothing if 'inline' is not supported under any name.  */
-#ifndef __cplusplus
-/* #undef inline */
-#endif
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef pid_t */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-/* Define to unsigned int if you dont have it */
-/* #undef socklen_t */
diff --git a/base/third_party/libevent/nacl_nonsfi/event-config.h b/base/third_party/libevent/nacl_nonsfi/event-config.h
deleted file mode 100644
index fe28043..0000000
--- a/base/third_party/libevent/nacl_nonsfi/event-config.h
+++ /dev/null
@@ -1,290 +0,0 @@
-/* Copied from Linux version and changed the features according the PNaCl
- * toolchain for the Non-SFI binary build, which is close to one under the
- * linux/ directory. The built binary will be running under Linux directly,
- * actually.
- */
-
-#ifndef _EVENT_CONFIG_H_
-#define _EVENT_CONFIG_H_
-
-/* Define if clock_gettime is available in libc */
-#define _EVENT_DNS_USE_CPU_CLOCK_FOR_ID 1
-
-/* Define is no secure id variant is available */
-/* #undef _EVENT_DNS_USE_GETTIMEOFDAY_FOR_ID */
-
-/* Define to 1 if you have the `clock_gettime' function. */
-#define _EVENT_HAVE_CLOCK_GETTIME 1
-
-/* Define if /dev/poll is available */
-/* #undef _EVENT_HAVE_DEVPOLL */
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define _EVENT_HAVE_DLFCN_H 1
-
-/* Define if your system supports the epoll system calls */
-/* #undef _EVENT_HAVE_EPOLL */
-
-/* Define to 1 if you have the `epoll_ctl' function. */
-/* #undef _EVENT_HAVE_EPOLL_CTL */
-
-/* Define if your system supports event ports */
-/* #undef _EVENT_HAVE_EVENT_PORTS */
-
-/* Define to 1 if you have the `fcntl' function. */
-#define _EVENT_HAVE_FCNTL 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define _EVENT_HAVE_FCNTL_H 1
-
-/* Define to 1 if the system has the type `fd_mask'. */
-#define _EVENT_HAVE_FD_MASK 1
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#define _EVENT_HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the `getegid' function. */
-#define _EVENT_HAVE_GETEGID 1
-
-/* Define to 1 if you have the `geteuid' function. */
-#define _EVENT_HAVE_GETEUID 1
-
-/* Define to 1 if you have the `getnameinfo' function. */
-#define _EVENT_HAVE_GETNAMEINFO 1
-
-/* Define to 1 if you have the `gettimeofday' function. */
-#define _EVENT_HAVE_GETTIMEOFDAY 1
-
-/* Define to 1 if you have the `inet_ntop' function. */
-#define _EVENT_HAVE_INET_NTOP 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define _EVENT_HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `issetugid' function. */
-/* #undef _EVENT_HAVE_ISSETUGID */
-
-/* Define to 1 if you have the `kqueue' function. */
-/* #undef _EVENT_HAVE_KQUEUE */
-
-/* Define to 1 if you have the `nsl' library (-lnsl). */
-#define _EVENT_HAVE_LIBNSL 1
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-#define _EVENT_HAVE_LIBRESOLV 1
-
-/* Define to 1 if you have the `rt' library (-lrt). */
-#define _EVENT_HAVE_LIBRT 1
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-/* #undef _EVENT_HAVE_LIBSOCKET */
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define _EVENT_HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netinet/in6.h> header file. */
-/* #undef _EVENT_HAVE_NETINET_IN6_H */
-
-/* Define to 1 if you have the `poll' function. */
-#define _EVENT_HAVE_POLL 1
-
-/* Define to 1 if you have the <poll.h> header file. */
-#define _EVENT_HAVE_POLL_H 1
-
-/* Define to 1 if you have the `port_create' function. */
-/* #undef _EVENT_HAVE_PORT_CREATE */
-
-/* Define to 1 if you have the <port.h> header file. */
-/* #undef _EVENT_HAVE_PORT_H */
-
-/* Define to 1 if you have the `select' function. */
-/* #undef _EVENT_HAVE_SELECT */
-
-/* Define if F_SETFD is defined in <fcntl.h> */
-#define _EVENT_HAVE_SETFD 1
-
-/* Define to 1 if you have the `sigaction' function. */
-/* #undef _EVENT_HAVE_SIGACTION */
-
-/* Define to 1 if you have the `signal' function. */
-#define _EVENT_HAVE_SIGNAL 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define _EVENT_HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the <stdarg.h> header file. */
-#define _EVENT_HAVE_STDARG_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define _EVENT_HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define _EVENT_HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define _EVENT_HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define _EVENT_HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-/* #undef _EVENT_HAVE_STRLCPY */
-
-/* Define to 1 if you have the `strsep' function. */
-#define _EVENT_HAVE_STRSEP 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-#define _EVENT_HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the `strtoll' function. */
-#define _EVENT_HAVE_STRTOLL 1
-
-/* Define to 1 if the system has the type `struct in6_addr'. */
-#define _EVENT_HAVE_STRUCT_IN6_ADDR 1
-
-/* Define to 1 if you have the <sys/devpoll.h> header file. */
-/* #undef _EVENT_HAVE_SYS_DEVPOLL_H */
-
-/* Define to 1 if you have the <sys/epoll.h> header file. */
-/* #undef _EVENT_HAVE_SYS_EPOLL_H */
-
-/* Define to 1 if you have the <sys/event.h> header file. */
-/* #undef _EVENT_HAVE_SYS_EVENT_H */
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-/* #undef _EVENT_HAVE_SYS_IOCTL_H */
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define _EVENT_HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/queue.h> header file. */
-#define _EVENT_HAVE_SYS_QUEUE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#define _EVENT_HAVE_SYS_SELECT_H 1
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define _EVENT_HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define _EVENT_HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define _EVENT_HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define _EVENT_HAVE_SYS_TYPES_H 1
-
-/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
-#define _EVENT_HAVE_TAILQFOREACH 1
-
-/* Define if timeradd is defined in <sys/time.h> */
-/* #undef _EVENT_HAVE_TIMERADD */
-
-/* Define if timerclear is defined in <sys/time.h> */
-/* #undef _EVENT_HAVE_TIMERCLEAR */
-
-/* Define if timercmp is defined in <sys/time.h> */
-/* #undef _EVENT_HAVE_TIMERCMP */
-
-/* Define if timerisset is defined in <sys/time.h> */
-/* #undef _EVENT_HAVE_TIMERISSET */
-
-/* Define to 1 if the system has the type `uint16_t'. */
-#define _EVENT_HAVE_UINT16_T 1
-
-/* Define to 1 if the system has the type `uint32_t'. */
-#define _EVENT_HAVE_UINT32_T 1
-
-/* Define to 1 if the system has the type `uint64_t'. */
-#define _EVENT_HAVE_UINT64_T 1
-
-/* Define to 1 if the system has the type `uint8_t'. */
-#define _EVENT_HAVE_UINT8_T 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define _EVENT_HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `vasprintf' function. */
-#define _EVENT_HAVE_VASPRINTF 1
-
-/* Define if kqueue works correctly with pipes */
-/* #undef _EVENT_HAVE_WORKING_KQUEUE */
-
-/* Define to the sub-directory in which libtool stores uninstalled libraries.
-   */
-#define _EVENT_LT_OBJDIR ".libs/"
-
-/* Numeric representation of the version */
-#define _EVENT_NUMERIC_VERSION 0x01040f00
-
-/* Name of package */
-#define _EVENT_PACKAGE "libevent_nacl"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define _EVENT_PACKAGE_BUGREPORT ""
-
-/* Define to the full name of this package. */
-#define _EVENT_PACKAGE_NAME ""
-
-/* Define to the full name and version of this package. */
-#define _EVENT_PACKAGE_STRING ""
-
-/* Define to the one symbol short name of this package. */
-#define _EVENT_PACKAGE_TARNAME ""
-
-/* Define to the home page for this package. */
-#define _EVENT_PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define _EVENT_PACKAGE_VERSION ""
-
-/* The size of `int', as computed by sizeof. */
-#define _EVENT_SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG 8
-
-/* The size of `long long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG_LONG 8
-
-/* The size of `short', as computed by sizeof. */
-#define _EVENT_SIZEOF_SHORT 2
-
-/* Define to 1 if you have the ANSI C header files. */
-#define _EVENT_STDC_HEADERS 1
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define _EVENT_TIME_WITH_SYS_TIME 1
-
-/* Version number of package */
-#define _EVENT_VERSION "1.4.15"
-
-/* Define to appropriate substitue if compiler doesnt have __func__ */
-/* #undef _EVENT___func__ */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef _EVENT_const */
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
-   calls it, or to nothing if 'inline' is not supported under any name.  */
-#ifndef _EVENT___cplusplus
-/* #undef _EVENT_inline */
-#endif
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef _EVENT_pid_t */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef _EVENT_size_t */
-
-/* Define to unsigned int if you dont have it */
-/* #undef _EVENT_socklen_t */
-
-/* Work around for __native_client_nonsfi__ build. random() is not provided
- * by the newlib-based PNaCl toolchain, so here we declare it. Please see also
- * nacl_nonsfi/random.c for more details.
- */
-long int random();
-
-#endif
diff --git a/base/third_party/libevent/nacl_nonsfi/random.c b/base/third_party/libevent/nacl_nonsfi/random.c
deleted file mode 100644
index 3577dd5..0000000
--- a/base/third_party/libevent/nacl_nonsfi/random.c
+++ /dev/null
@@ -1,13 +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 <stdlib.h>
-
-/* The newlib-based PNaCl toolchain does not provide random(). So, here we
- * define it. It just redirects to the rand(), which is provided by the
- * toolchain. */
-long int random() {
-  return rand();
-}
diff --git a/base/third_party/libevent/nacl_nonsfi/signal_stub.c b/base/third_party/libevent/nacl_nonsfi/signal_stub.c
deleted file mode 100644
index 0399e8c..0000000
--- a/base/third_party/libevent/nacl_nonsfi/signal_stub.c
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright 2015 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.
- */
-
-/*
- * In nacl_helper_nonsfi, socketpair() is unavailable. In libevent, it is used
- * to notify of a signal handler invocation, which is unused in
- * nacl_helper_nonsfi. Unfortunately, there is no macro to disable the feature,
- * so we stub out the signal module entirely.
- */
-
-
-#include <signal.h>
-#include <stdlib.h>
-#include <sys/queue.h>
-
-/* config.h must be included before any other libevent header is included. */
-#include "config.h"
-
-#include "base/third_party/libevent/event-internal.h"
-#include "base/third_party/libevent/event.h"
-#include "base/third_party/libevent/evsignal.h"
-
-
-struct event_base *evsignal_base = 0;
-
-int evsignal_init(struct event_base *base) {
-  /* Do nothing, and return success. */
-  return 0;
-}
-
-void evsignal_process(struct event_base *base) {
-}
-
-int evsignal_add(struct event *event) {
-  /* Do nothing, and return an error. */
-  return -1;
-}
-
-int evsignal_del(struct event *event) {
-  /* Do nothing, and return an error. */
-  return -1;
-}
-
-void evsignal_dealloc(struct event_base *base) {
-}
diff --git a/base/third_party/libevent/poll.c b/base/third_party/libevent/poll.c
deleted file mode 100644
index 2aa245b..0000000
--- a/base/third_party/libevent/poll.c
+++ /dev/null
@@ -1,379 +0,0 @@
-/*	$OpenBSD: poll.c,v 1.2 2002/06/25 15:50:15 mickey Exp $	*/
-
-/*
- * Copyright 2000-2003 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <sys/types.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#else
-#include <sys/_libevent_time.h>
-#endif
-#include <sys/queue.h>
-#include <poll.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <errno.h>
-#ifdef CHECK_INVARIANTS
-#include <assert.h>
-#endif
-
-#include "event.h"
-#include "event-internal.h"
-#include "evsignal.h"
-#include "log.h"
-
-struct pollop {
-	int event_count;		/* Highest number alloc */
-	int nfds;                       /* Size of event_* */
-	int fd_count;                   /* Size of idxplus1_by_fd */
-	struct pollfd *event_set;
-	struct event **event_r_back;
-	struct event **event_w_back;
-	int *idxplus1_by_fd; /* Index into event_set by fd; we add 1 so
-			      * that 0 (which is easy to memset) can mean
-			      * "no entry." */
-};
-
-static void *poll_init	(struct event_base *);
-static int poll_add		(void *, struct event *);
-static int poll_del		(void *, struct event *);
-static int poll_dispatch	(struct event_base *, void *, struct timeval *);
-static void poll_dealloc	(struct event_base *, void *);
-
-const struct eventop pollops = {
-	"poll",
-	poll_init,
-	poll_add,
-	poll_del,
-	poll_dispatch,
-	poll_dealloc,
-    0
-};
-
-static void *
-poll_init(struct event_base *base)
-{
-	struct pollop *pollop;
-
-	/* Disable poll when this environment variable is set */
-	if (evutil_getenv("EVENT_NOPOLL"))
-		return (NULL);
-
-	if (!(pollop = calloc(1, sizeof(struct pollop))))
-		return (NULL);
-
-	evsignal_init(base);
-
-	return (pollop);
-}
-
-#ifdef CHECK_INVARIANTS
-static void
-poll_check_ok(struct pollop *pop)
-{
-	int i, idx;
-	struct event *ev;
-
-	for (i = 0; i < pop->fd_count; ++i) {
-		idx = pop->idxplus1_by_fd[i]-1;
-		if (idx < 0)
-			continue;
-		assert(pop->event_set[idx].fd == i);
-		if (pop->event_set[idx].events & POLLIN) {
-			ev = pop->event_r_back[idx];
-			assert(ev);
-			assert(ev->ev_events & EV_READ);
-			assert(ev->ev_fd == i);
-		}
-		if (pop->event_set[idx].events & POLLOUT) {
-			ev = pop->event_w_back[idx];
-			assert(ev);
-			assert(ev->ev_events & EV_WRITE);
-			assert(ev->ev_fd == i);
-		}
-	}
-	for (i = 0; i < pop->nfds; ++i) {
-		struct pollfd *pfd = &pop->event_set[i];
-		assert(pop->idxplus1_by_fd[pfd->fd] == i+1);
-	}
-}
-#else
-#define poll_check_ok(pop)
-#endif
-
-static int
-poll_dispatch(struct event_base *base, void *arg, struct timeval *tv)
-{
-	int res, i, j, msec = -1, nfds;
-	struct pollop *pop = arg;
-
-	poll_check_ok(pop);
-
-	if (tv != NULL)
-		msec = tv->tv_sec * 1000 + (tv->tv_usec + 999) / 1000;
-
-	nfds = pop->nfds;
-	res = poll(pop->event_set, nfds, msec);
-
-	if (res == -1) {
-		if (errno != EINTR) {
-                        event_warn("poll");
-			return (-1);
-		}
-
-		evsignal_process(base);
-		return (0);
-	} else if (base->sig.evsignal_caught) {
-		evsignal_process(base);
-	}
-
-	event_debug(("%s: poll reports %d", __func__, res));
-
-	if (res == 0 || nfds == 0)
-		return (0);
-
-	i = random() % nfds;
-	for (j = 0; j < nfds; j++) {
-		struct event *r_ev = NULL, *w_ev = NULL;
-		int what;
-		if (++i == nfds)
-			i = 0;
-		what = pop->event_set[i].revents;
-
-		if (!what)
-			continue;
-
-		res = 0;
-
-		/* If the file gets closed notify */
-		if (what & (POLLHUP|POLLERR))
-			what |= POLLIN|POLLOUT;
-		if (what & POLLIN) {
-			res |= EV_READ;
-			r_ev = pop->event_r_back[i];
-		}
-		if (what & POLLOUT) {
-			res |= EV_WRITE;
-			w_ev = pop->event_w_back[i];
-		}
-		if (res == 0)
-			continue;
-
-		if (r_ev && (res & r_ev->ev_events)) {
-			event_active(r_ev, res & r_ev->ev_events, 1);
-		}
-		if (w_ev && w_ev != r_ev && (res & w_ev->ev_events)) {
-			event_active(w_ev, res & w_ev->ev_events, 1);
-		}
-	}
-
-	return (0);
-}
-
-static int
-poll_add(void *arg, struct event *ev)
-{
-	struct pollop *pop = arg;
-	struct pollfd *pfd = NULL;
-	int i;
-
-	if (ev->ev_events & EV_SIGNAL)
-		return (evsignal_add(ev));
-	if (!(ev->ev_events & (EV_READ|EV_WRITE)))
-		return (0);
-
-	poll_check_ok(pop);
-	if (pop->nfds + 1 >= pop->event_count) {
-		struct pollfd *tmp_event_set;
-		struct event **tmp_event_r_back;
-		struct event **tmp_event_w_back;
-		int tmp_event_count;
-
-		if (pop->event_count < 32)
-			tmp_event_count = 32;
-		else
-			tmp_event_count = pop->event_count * 2;
-
-		/* We need more file descriptors */
-		tmp_event_set = realloc(pop->event_set,
-				 tmp_event_count * sizeof(struct pollfd));
-		if (tmp_event_set == NULL) {
-			event_warn("realloc");
-			return (-1);
-		}
-		pop->event_set = tmp_event_set;
-
-		tmp_event_r_back = realloc(pop->event_r_back,
-			    tmp_event_count * sizeof(struct event *));
-		if (tmp_event_r_back == NULL) {
-			/* event_set overallocated; that's okay. */
-			event_warn("realloc");
-			return (-1);
-		}
-		pop->event_r_back = tmp_event_r_back;
-
-		tmp_event_w_back = realloc(pop->event_w_back,
-			    tmp_event_count * sizeof(struct event *));
-		if (tmp_event_w_back == NULL) {
-			/* event_set and event_r_back overallocated; that's
-			 * okay. */
-			event_warn("realloc");
-			return (-1);
-		}
-		pop->event_w_back = tmp_event_w_back;
-
-		pop->event_count = tmp_event_count;
-	}
-	if (ev->ev_fd >= pop->fd_count) {
-		int *tmp_idxplus1_by_fd;
-		int new_count;
-		if (pop->fd_count < 32)
-			new_count = 32;
-		else
-			new_count = pop->fd_count * 2;
-		while (new_count <= ev->ev_fd)
-			new_count *= 2;
-		tmp_idxplus1_by_fd =
-			realloc(pop->idxplus1_by_fd, new_count * sizeof(int));
-		if (tmp_idxplus1_by_fd == NULL) {
-			event_warn("realloc");
-			return (-1);
-		}
-		pop->idxplus1_by_fd = tmp_idxplus1_by_fd;
-		memset(pop->idxplus1_by_fd + pop->fd_count,
-		       0, sizeof(int)*(new_count - pop->fd_count));
-		pop->fd_count = new_count;
-	}
-
-	i = pop->idxplus1_by_fd[ev->ev_fd] - 1;
-	if (i >= 0) {
-		pfd = &pop->event_set[i];
-	} else {
-		i = pop->nfds++;
-		pfd = &pop->event_set[i];
-		pfd->events = 0;
-		pfd->fd = ev->ev_fd;
-		pop->event_w_back[i] = pop->event_r_back[i] = NULL;
-		pop->idxplus1_by_fd[ev->ev_fd] = i + 1;
-	}
-
-	pfd->revents = 0;
-	if (ev->ev_events & EV_WRITE) {
-		pfd->events |= POLLOUT;
-		pop->event_w_back[i] = ev;
-	}
-	if (ev->ev_events & EV_READ) {
-		pfd->events |= POLLIN;
-		pop->event_r_back[i] = ev;
-	}
-	poll_check_ok(pop);
-
-	return (0);
-}
-
-/*
- * Nothing to be done here.
- */
-
-static int
-poll_del(void *arg, struct event *ev)
-{
-	struct pollop *pop = arg;
-	struct pollfd *pfd = NULL;
-	int i;
-
-	if (ev->ev_events & EV_SIGNAL)
-		return (evsignal_del(ev));
-
-	if (!(ev->ev_events & (EV_READ|EV_WRITE)))
-		return (0);
-
-	poll_check_ok(pop);
-	i = pop->idxplus1_by_fd[ev->ev_fd] - 1;
-	if (i < 0)
-		return (-1);
-
-	/* Do we still want to read or write? */
-	pfd = &pop->event_set[i];
-	if (ev->ev_events & EV_READ) {
-		pfd->events &= ~POLLIN;
-		pop->event_r_back[i] = NULL;
-	}
-	if (ev->ev_events & EV_WRITE) {
-		pfd->events &= ~POLLOUT;
-		pop->event_w_back[i] = NULL;
-	}
-	poll_check_ok(pop);
-	if (pfd->events)
-		/* Another event cares about that fd. */
-		return (0);
-
-	/* Okay, so we aren't interested in that fd anymore. */
-	pop->idxplus1_by_fd[ev->ev_fd] = 0;
-
-	--pop->nfds;
-	if (i != pop->nfds) {
-		/* 
-		 * Shift the last pollfd down into the now-unoccupied
-		 * position.
-		 */
-		memcpy(&pop->event_set[i], &pop->event_set[pop->nfds],
-		       sizeof(struct pollfd));
-		pop->event_r_back[i] = pop->event_r_back[pop->nfds];
-		pop->event_w_back[i] = pop->event_w_back[pop->nfds];
-		pop->idxplus1_by_fd[pop->event_set[i].fd] = i + 1;
-	}
-
-	poll_check_ok(pop);
-	return (0);
-}
-
-static void
-poll_dealloc(struct event_base *base, void *arg)
-{
-	struct pollop *pop = arg;
-
-	evsignal_dealloc(base);
-	if (pop->event_set)
-		free(pop->event_set);
-	if (pop->event_r_back)
-		free(pop->event_r_back);
-	if (pop->event_w_back)
-		free(pop->event_w_back);
-	if (pop->idxplus1_by_fd)
-		free(pop->idxplus1_by_fd);
-
-	memset(pop, 0, sizeof(struct pollop));
-	free(pop);
-}
diff --git a/base/third_party/libevent/sample/Makefile.am b/base/third_party/libevent/sample/Makefile.am
deleted file mode 100644
index 2f4e26e..0000000
--- a/base/third_party/libevent/sample/Makefile.am
+++ /dev/null
@@ -1,14 +0,0 @@
-AUTOMAKE_OPTIONS = foreign no-dependencies
-
-LDADD = ../libevent.la
-AM_CFLAGS = -I$(top_srcdir) -I$(top_srcdir)/compat
-
-noinst_PROGRAMS = event-test time-test signal-test
-
-event_test_sources = event-test.c
-time_test_sources = time-test.c
-signal_test_sources = signal-test.c
-
-verify:
-
-DISTCLEANFILES = *~
diff --git a/base/third_party/libevent/sample/event-test.c b/base/third_party/libevent/sample/event-test.c
deleted file mode 100644
index 0a439ce..0000000
--- a/base/third_party/libevent/sample/event-test.c
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Compile with:
- * cc -I/usr/local/include -o event-test event-test.c -L/usr/local/lib -levent
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifndef WIN32
-#include <sys/queue.h>
-#include <unistd.h>
-#include <sys/time.h>
-#else
-#include <windows.h>
-#endif
-#include <fcntl.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-
-#include <event.h>
-
-static void
-fifo_read(int fd, short event, void *arg)
-{
-	char buf[255];
-	int len;
-	struct event *ev = arg;
-#ifdef WIN32
-	DWORD dwBytesRead;
-#endif
-
-	/* Reschedule this event */
-	event_add(ev, NULL);
-
-	fprintf(stderr, "fifo_read called with fd: %d, event: %d, arg: %p\n",
-		fd, event, arg);
-#ifdef WIN32
-	len = ReadFile((HANDLE)fd, buf, sizeof(buf) - 1, &dwBytesRead, NULL);
-
-	// Check for end of file. 
-	if(len && dwBytesRead == 0) {
-		fprintf(stderr, "End Of File");
-		event_del(ev);
-		return;
-	}
-
-	buf[dwBytesRead] = '\0';
-#else
-	len = read(fd, buf, sizeof(buf) - 1);
-
-	if (len == -1) {
-		perror("read");
-		return;
-	} else if (len == 0) {
-		fprintf(stderr, "Connection closed\n");
-		return;
-	}
-
-	buf[len] = '\0';
-#endif
-	fprintf(stdout, "Read: %s\n", buf);
-}
-
-int
-main (int argc, char **argv)
-{
-	struct event evfifo;
-#ifdef WIN32
-	HANDLE socket;
-	// Open a file. 
-	socket = CreateFileA("test.txt",     // open File 
-			GENERIC_READ,                 // open for reading 
-			0,                            // do not share 
-			NULL,                         // no security 
-			OPEN_EXISTING,                // existing file only 
-			FILE_ATTRIBUTE_NORMAL,        // normal file 
-			NULL);                        // no attr. template 
-
-	if(socket == INVALID_HANDLE_VALUE)
-		return 1;
-
-#else
-	struct stat st;
-	const char *fifo = "event.fifo";
-	int socket;
- 
-	if (lstat (fifo, &st) == 0) {
-		if ((st.st_mode & S_IFMT) == S_IFREG) {
-			errno = EEXIST;
-			perror("lstat");
-			exit (1);
-		}
-	}
-
-	unlink (fifo);
-	if (mkfifo (fifo, 0600) == -1) {
-		perror("mkfifo");
-		exit (1);
-	}
-
-	/* Linux pipes are broken, we need O_RDWR instead of O_RDONLY */
-#ifdef __linux
-	socket = open (fifo, O_RDWR | O_NONBLOCK, 0);
-#else
-	socket = open (fifo, O_RDONLY | O_NONBLOCK, 0);
-#endif
-
-	if (socket == -1) {
-		perror("open");
-		exit (1);
-	}
-
-	fprintf(stderr, "Write data to %s\n", fifo);
-#endif
-	/* Initalize the event library */
-	event_init();
-
-	/* Initalize one event */
-#ifdef WIN32
-	event_set(&evfifo, (int)socket, EV_READ, fifo_read, &evfifo);
-#else
-	event_set(&evfifo, socket, EV_READ, fifo_read, &evfifo);
-#endif
-
-	/* Add it to the active events, without a timeout */
-	event_add(&evfifo, NULL);
-	
-	event_dispatch();
-#ifdef WIN32
-	CloseHandle(socket);
-#endif
-	return (0);
-}
-
diff --git a/base/third_party/libevent/sample/signal-test.c b/base/third_party/libevent/sample/signal-test.c
deleted file mode 100644
index 5a5a303..0000000
--- a/base/third_party/libevent/sample/signal-test.c
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Compile with:
- * cc -I/usr/local/include -o signal-test \
- *   signal-test.c -L/usr/local/lib -levent
- */
-
-#include <sys/types.h>
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <sys/stat.h>
-#ifndef WIN32
-#include <sys/queue.h>
-#include <unistd.h>
-#include <sys/time.h>
-#else
-#include <windows.h>
-#endif
-#include <signal.h>
-#include <fcntl.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-
-#include <event.h>
-
-int called = 0;
-
-static void
-signal_cb(int fd, short event, void *arg)
-{
-	struct event *signal = arg;
-
-	printf("%s: got signal %d\n", __func__, EVENT_SIGNAL(signal));
-
-	if (called >= 2)
-		event_del(signal);
-
-	called++;
-}
-
-int
-main (int argc, char **argv)
-{
-	struct event signal_int;
-
-	/* Initalize the event library */
-	struct event_base* base = event_base_new();
-
-	/* Initalize one event */
-	event_set(&signal_int, SIGINT, EV_SIGNAL|EV_PERSIST, signal_cb,
-	    &signal_int);
-	event_base_set(base, &signal_int);
-
-	event_add(&signal_int, NULL);
-
-	event_base_dispatch(base);
-	event_base_free(base);
-
-	return (0);
-}
-
diff --git a/base/third_party/libevent/sample/time-test.c b/base/third_party/libevent/sample/time-test.c
deleted file mode 100644
index 069d4f8..0000000
--- a/base/third_party/libevent/sample/time-test.c
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Compile with:
- * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent
- */
-
-#include <sys/types.h>
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <sys/stat.h>
-#ifndef WIN32
-#include <sys/queue.h>
-#include <unistd.h>
-#endif
-#include <time.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#include <fcntl.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-
-#include <event.h>
-#include <evutil.h>
-
-int lasttime;
-
-static void
-timeout_cb(int fd, short event, void *arg)
-{
-	struct timeval tv;
-	struct event *timeout = arg;
-	int newtime = time(NULL);
-
-	printf("%s: called at %d: %d\n", __func__, newtime,
-	    newtime - lasttime);
-	lasttime = newtime;
-
-	evutil_timerclear(&tv);
-	tv.tv_sec = 2;
-	event_add(timeout, &tv);
-}
-
-int
-main (int argc, char **argv)
-{
-	struct event timeout;
-	struct timeval tv;
- 
-	/* Initalize the event library */
-	event_init();
-
-	/* Initalize one event */
-	evtimer_set(&timeout, timeout_cb, &timeout);
-
-	evutil_timerclear(&tv);
-	tv.tv_sec = 2;
-	event_add(&timeout, &tv);
-
-	lasttime = time(NULL);
-	
-	event_dispatch();
-
-	return (0);
-}
-
diff --git a/base/third_party/libevent/select.c b/base/third_party/libevent/select.c
deleted file mode 100644
index 3f73331..0000000
--- a/base/third_party/libevent/select.c
+++ /dev/null
@@ -1,364 +0,0 @@
-/*	$OpenBSD: select.c,v 1.2 2002/06/25 15:50:15 mickey Exp $	*/
-
-/*
- * Copyright 2000-2002 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <sys/types.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#else
-#include <sys/_libevent_time.h>
-#endif
-#ifdef HAVE_SYS_SELECT_H
-#include <sys/select.h>
-#endif
-#include <sys/queue.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <errno.h>
-#ifdef CHECK_INVARIANTS
-#include <assert.h>
-#endif
-
-#include "event.h"
-#include "evutil.h"
-#include "event-internal.h"
-#include "evsignal.h"
-#include "log.h"
-
-#ifndef howmany
-#define        howmany(x, y)   (((x)+((y)-1))/(y))
-#endif
-
-#ifndef _EVENT_HAVE_FD_MASK
-/* This type is mandatory, but Android doesn't define it. */
-#undef NFDBITS
-#define NFDBITS (sizeof(long)*8)
-typedef unsigned long fd_mask;
-#endif
-
-struct selectop {
-	int event_fds;		/* Highest fd in fd set */
-	int event_fdsz;
-	fd_set *event_readset_in;
-	fd_set *event_writeset_in;
-	fd_set *event_readset_out;
-	fd_set *event_writeset_out;
-	struct event **event_r_by_fd;
-	struct event **event_w_by_fd;
-};
-
-static void *select_init	(struct event_base *);
-static int select_add		(void *, struct event *);
-static int select_del		(void *, struct event *);
-static int select_dispatch	(struct event_base *, void *, struct timeval *);
-static void select_dealloc     (struct event_base *, void *);
-
-const struct eventop selectops = {
-	"select",
-	select_init,
-	select_add,
-	select_del,
-	select_dispatch,
-	select_dealloc,
-	0
-};
-
-static int select_resize(struct selectop *sop, int fdsz);
-
-static void *
-select_init(struct event_base *base)
-{
-	struct selectop *sop;
-
-	/* Disable select when this environment variable is set */
-	if (evutil_getenv("EVENT_NOSELECT"))
-		return (NULL);
-
-	if (!(sop = calloc(1, sizeof(struct selectop))))
-		return (NULL);
-
-	select_resize(sop, howmany(32 + 1, NFDBITS)*sizeof(fd_mask));
-
-	evsignal_init(base);
-
-	return (sop);
-}
-
-#ifdef CHECK_INVARIANTS
-static void
-check_selectop(struct selectop *sop)
-{
-	int i;
-	for (i = 0; i <= sop->event_fds; ++i) {
-		if (FD_ISSET(i, sop->event_readset_in)) {
-			assert(sop->event_r_by_fd[i]);
-			assert(sop->event_r_by_fd[i]->ev_events & EV_READ);
-			assert(sop->event_r_by_fd[i]->ev_fd == i);
-		} else {
-			assert(! sop->event_r_by_fd[i]);
-		}
-		if (FD_ISSET(i, sop->event_writeset_in)) {
-			assert(sop->event_w_by_fd[i]);
-			assert(sop->event_w_by_fd[i]->ev_events & EV_WRITE);
-			assert(sop->event_w_by_fd[i]->ev_fd == i);
-		} else {
-			assert(! sop->event_w_by_fd[i]);
-		}
-	}
-
-}
-#else
-#define check_selectop(sop) do { (void) sop; } while (0)
-#endif
-
-static int
-select_dispatch(struct event_base *base, void *arg, struct timeval *tv)
-{
-	int res, i, j;
-	struct selectop *sop = arg;
-
-	check_selectop(sop);
-
-	memcpy(sop->event_readset_out, sop->event_readset_in,
-	       sop->event_fdsz);
-	memcpy(sop->event_writeset_out, sop->event_writeset_in,
-	       sop->event_fdsz);
-
-	res = select(sop->event_fds + 1, sop->event_readset_out,
-	    sop->event_writeset_out, NULL, tv);
-
-	check_selectop(sop);
-
-	if (res == -1) {
-		if (errno != EINTR) {
-			event_warn("select");
-			return (-1);
-		}
-
-		evsignal_process(base);
-		return (0);
-	} else if (base->sig.evsignal_caught) {
-		evsignal_process(base);
-	}
-
-	event_debug(("%s: select reports %d", __func__, res));
-
-	check_selectop(sop);
-	i = random() % (sop->event_fds+1);
-	for (j = 0; j <= sop->event_fds; ++j) {
-		struct event *r_ev = NULL, *w_ev = NULL;
-		if (++i >= sop->event_fds+1)
-			i = 0;
-
-		res = 0;
-		if (FD_ISSET(i, sop->event_readset_out)) {
-			r_ev = sop->event_r_by_fd[i];
-			res |= EV_READ;
-		}
-		if (FD_ISSET(i, sop->event_writeset_out)) {
-			w_ev = sop->event_w_by_fd[i];
-			res |= EV_WRITE;
-		}
-		if (r_ev && (res & r_ev->ev_events)) {
-			event_active(r_ev, res & r_ev->ev_events, 1);
-		}
-		if (w_ev && w_ev != r_ev && (res & w_ev->ev_events)) {
-			event_active(w_ev, res & w_ev->ev_events, 1);
-		}
-	}
-	check_selectop(sop);
-
-	return (0);
-}
-
-
-static int
-select_resize(struct selectop *sop, int fdsz)
-{
-	int n_events, n_events_old;
-
-	fd_set *readset_in = NULL;
-	fd_set *writeset_in = NULL;
-	fd_set *readset_out = NULL;
-	fd_set *writeset_out = NULL;
-	struct event **r_by_fd = NULL;
-	struct event **w_by_fd = NULL;
-
-	n_events = (fdsz/sizeof(fd_mask)) * NFDBITS;
-	n_events_old = (sop->event_fdsz/sizeof(fd_mask)) * NFDBITS;
-
-	if (sop->event_readset_in)
-		check_selectop(sop);
-
-	if ((readset_in = realloc(sop->event_readset_in, fdsz)) == NULL)
-		goto error;
-	sop->event_readset_in = readset_in;
-	if ((readset_out = realloc(sop->event_readset_out, fdsz)) == NULL)
-		goto error;
-	sop->event_readset_out = readset_out;
-	if ((writeset_in = realloc(sop->event_writeset_in, fdsz)) == NULL)
-		goto error;
-	sop->event_writeset_in = writeset_in;
-	if ((writeset_out = realloc(sop->event_writeset_out, fdsz)) == NULL)
-		goto error;
-	sop->event_writeset_out = writeset_out;
-	if ((r_by_fd = realloc(sop->event_r_by_fd,
-		 n_events*sizeof(struct event*))) == NULL)
-		goto error;
-	sop->event_r_by_fd = r_by_fd;
-	if ((w_by_fd = realloc(sop->event_w_by_fd,
-		 n_events * sizeof(struct event*))) == NULL)
-		goto error;
-	sop->event_w_by_fd = w_by_fd;
-
-	memset((char *)sop->event_readset_in + sop->event_fdsz, 0,
-	    fdsz - sop->event_fdsz);
-	memset((char *)sop->event_writeset_in + sop->event_fdsz, 0,
-	    fdsz - sop->event_fdsz);
-	memset(sop->event_r_by_fd + n_events_old, 0,
-	    (n_events-n_events_old) * sizeof(struct event*));
-	memset(sop->event_w_by_fd + n_events_old, 0,
-	    (n_events-n_events_old) * sizeof(struct event*));
-
-	sop->event_fdsz = fdsz;
-	check_selectop(sop);
-
-	return (0);
-
- error:
-	event_warn("malloc");
-	return (-1);
-}
-
-
-static int
-select_add(void *arg, struct event *ev)
-{
-	struct selectop *sop = arg;
-
-	if (ev->ev_events & EV_SIGNAL)
-		return (evsignal_add(ev));
-
-	check_selectop(sop);
-	/*
-	 * Keep track of the highest fd, so that we can calculate the size
-	 * of the fd_sets for select(2)
-	 */
-	if (sop->event_fds < ev->ev_fd) {
-		int fdsz = sop->event_fdsz;
-
-		if (fdsz < sizeof(fd_mask))
-			fdsz = sizeof(fd_mask);
-
-		while (fdsz <
-		    (howmany(ev->ev_fd + 1, NFDBITS) * sizeof(fd_mask)))
-			fdsz *= 2;
-
-		if (fdsz != sop->event_fdsz) {
-			if (select_resize(sop, fdsz)) {
-				check_selectop(sop);
-				return (-1);
-			}
-		}
-
-		sop->event_fds = ev->ev_fd;
-	}
-
-	if (ev->ev_events & EV_READ) {
-		FD_SET(ev->ev_fd, sop->event_readset_in);
-		sop->event_r_by_fd[ev->ev_fd] = ev;
-	}
-	if (ev->ev_events & EV_WRITE) {
-		FD_SET(ev->ev_fd, sop->event_writeset_in);
-		sop->event_w_by_fd[ev->ev_fd] = ev;
-	}
-	check_selectop(sop);
-
-	return (0);
-}
-
-/*
- * Nothing to be done here.
- */
-
-static int
-select_del(void *arg, struct event *ev)
-{
-	struct selectop *sop = arg;
-
-	check_selectop(sop);
-	if (ev->ev_events & EV_SIGNAL)
-		return (evsignal_del(ev));
-
-	if (sop->event_fds < ev->ev_fd) {
-		check_selectop(sop);
-		return (0);
-	}
-
-	if (ev->ev_events & EV_READ) {
-		FD_CLR(ev->ev_fd, sop->event_readset_in);
-		sop->event_r_by_fd[ev->ev_fd] = NULL;
-	}
-
-	if (ev->ev_events & EV_WRITE) {
-		FD_CLR(ev->ev_fd, sop->event_writeset_in);
-		sop->event_w_by_fd[ev->ev_fd] = NULL;
-	}
-
-	check_selectop(sop);
-	return (0);
-}
-
-static void
-select_dealloc(struct event_base *base, void *arg)
-{
-	struct selectop *sop = arg;
-
-	evsignal_dealloc(base);
-	if (sop->event_readset_in)
-		free(sop->event_readset_in);
-	if (sop->event_writeset_in)
-		free(sop->event_writeset_in);
-	if (sop->event_readset_out)
-		free(sop->event_readset_out);
-	if (sop->event_writeset_out)
-		free(sop->event_writeset_out);
-	if (sop->event_r_by_fd)
-		free(sop->event_r_by_fd);
-	if (sop->event_w_by_fd)
-		free(sop->event_w_by_fd);
-
-	memset(sop, 0, sizeof(struct selectop));
-	free(sop);
-}
diff --git a/base/third_party/libevent/signal.c b/base/third_party/libevent/signal.c
deleted file mode 100644
index b8d51ab..0000000
--- a/base/third_party/libevent/signal.c
+++ /dev/null
@@ -1,377 +0,0 @@
-/*	$OpenBSD: select.c,v 1.2 2002/06/25 15:50:15 mickey Exp $	*/
-
-/*
- * Copyright 2000-2002 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef WIN32
-#define WIN32_LEAN_AND_MEAN
-#include <winsock2.h>
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-#endif
-#include <sys/types.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#include <sys/queue.h>
-#ifdef HAVE_SYS_SOCKET_H
-#include <sys/socket.h>
-#endif
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#include <errno.h>
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif
-#include <assert.h>
-
-#include "event.h"
-#include "event-internal.h"
-#include "evsignal.h"
-#include "evutil.h"
-#include "log.h"
-
-struct event_base *evsignal_base = NULL;
-
-static void evsignal_handler(int sig);
-
-#ifdef WIN32
-#define error_is_eagain(err)			\
-	((err) == EAGAIN || (err) == WSAEWOULDBLOCK)
-#else
-#define error_is_eagain(err) ((err) == EAGAIN)
-#endif
-
-/* Callback for when the signal handler write a byte to our signaling socket */
-static void
-evsignal_cb(int fd, short what, void *arg)
-{
-	static char signals[1];
-#ifdef WIN32
-	SSIZE_T n;
-#else
-	ssize_t n;
-#endif
-
-	n = recv(fd, signals, sizeof(signals), 0);
-	if (n == -1) {
-		int err = EVUTIL_SOCKET_ERROR();
-		if (! error_is_eagain(err))
-			event_err(1, "%s: read", __func__);
-	}
-}
-
-#ifdef HAVE_SETFD
-#define FD_CLOSEONEXEC(x) do { \
-        if (fcntl(x, F_SETFD, 1) == -1) \
-                event_warn("fcntl(%d, F_SETFD)", x); \
-} while (0)
-#else
-#define FD_CLOSEONEXEC(x)
-#endif
-
-int
-evsignal_init(struct event_base *base)
-{
-	int i;
-
-	/* 
-	 * Our signal handler is going to write to one end of the socket
-	 * pair to wake up our event loop.  The event loop then scans for
-	 * signals that got delivered.
-	 */
-	if (evutil_socketpair(
-		    AF_UNIX, SOCK_STREAM, 0, base->sig.ev_signal_pair) == -1) {
-#ifdef WIN32
-		/* Make this nonfatal on win32, where sometimes people
-		   have localhost firewalled. */
-		event_warn("%s: socketpair", __func__);
-#else
-		event_err(1, "%s: socketpair", __func__);
-#endif
-		return -1;
-	}
-
-	FD_CLOSEONEXEC(base->sig.ev_signal_pair[0]);
-	FD_CLOSEONEXEC(base->sig.ev_signal_pair[1]);
-	base->sig.sh_old = NULL;
-	base->sig.sh_old_max = 0;
-	base->sig.evsignal_caught = 0;
-	memset(&base->sig.evsigcaught, 0, sizeof(sig_atomic_t)*NSIG);
-	/* initialize the queues for all events */
-	for (i = 0; i < NSIG; ++i)
-		TAILQ_INIT(&base->sig.evsigevents[i]);
-
-        evutil_make_socket_nonblocking(base->sig.ev_signal_pair[0]);
-        evutil_make_socket_nonblocking(base->sig.ev_signal_pair[1]);
-
-	event_set(&base->sig.ev_signal, base->sig.ev_signal_pair[1],
-		EV_READ | EV_PERSIST, evsignal_cb, &base->sig.ev_signal);
-	base->sig.ev_signal.ev_base = base;
-	base->sig.ev_signal.ev_flags |= EVLIST_INTERNAL;
-
-	return 0;
-}
-
-/* Helper: set the signal handler for evsignal to handler in base, so that
- * we can restore the original handler when we clear the current one. */
-int
-_evsignal_set_handler(struct event_base *base,
-		      int evsignal, void (*handler)(int))
-{
-#ifdef HAVE_SIGACTION
-	struct sigaction sa;
-#else
-	ev_sighandler_t sh;
-#endif
-	struct evsignal_info *sig = &base->sig;
-	void *p;
-
-	/*
-	 * resize saved signal handler array up to the highest signal number.
-	 * a dynamic array is used to keep footprint on the low side.
-	 */
-	if (evsignal >= sig->sh_old_max) {
-		int new_max = evsignal + 1;
-		event_debug(("%s: evsignal (%d) >= sh_old_max (%d), resizing",
-			    __func__, evsignal, sig->sh_old_max));
-		p = realloc(sig->sh_old, new_max * sizeof(*sig->sh_old));
-		if (p == NULL) {
-			event_warn("realloc");
-			return (-1);
-		}
-
-		memset((char *)p + sig->sh_old_max * sizeof(*sig->sh_old),
-		    0, (new_max - sig->sh_old_max) * sizeof(*sig->sh_old));
-
-		sig->sh_old_max = new_max;
-		sig->sh_old = p;
-	}
-
-	/* allocate space for previous handler out of dynamic array */
-	sig->sh_old[evsignal] = malloc(sizeof *sig->sh_old[evsignal]);
-	if (sig->sh_old[evsignal] == NULL) {
-		event_warn("malloc");
-		return (-1);
-	}
-
-	/* save previous handler and setup new handler */
-#ifdef HAVE_SIGACTION
-	memset(&sa, 0, sizeof(sa));
-	sa.sa_handler = handler;
-	sa.sa_flags |= SA_RESTART;
-	sigfillset(&sa.sa_mask);
-
-	if (sigaction(evsignal, &sa, sig->sh_old[evsignal]) == -1) {
-		event_warn("sigaction");
-		free(sig->sh_old[evsignal]);
-		sig->sh_old[evsignal] = NULL;
-		return (-1);
-	}
-#else
-	if ((sh = signal(evsignal, handler)) == SIG_ERR) {
-		event_warn("signal");
-		free(sig->sh_old[evsignal]);
-		sig->sh_old[evsignal] = NULL;
-		return (-1);
-	}
-	*sig->sh_old[evsignal] = sh;
-#endif
-
-	return (0);
-}
-
-int
-evsignal_add(struct event *ev)
-{
-	int evsignal;
-	struct event_base *base = ev->ev_base;
-	struct evsignal_info *sig = &ev->ev_base->sig;
-
-	if (ev->ev_events & (EV_READ|EV_WRITE))
-		event_errx(1, "%s: EV_SIGNAL incompatible use", __func__);
-	evsignal = EVENT_SIGNAL(ev);
-	assert(evsignal >= 0 && evsignal < NSIG);
-	if (TAILQ_EMPTY(&sig->evsigevents[evsignal])) {
-		event_debug(("%s: %p: changing signal handler", __func__, ev));
-		if (_evsignal_set_handler(
-			    base, evsignal, evsignal_handler) == -1)
-			return (-1);
-
-		/* catch signals if they happen quickly */
-		evsignal_base = base;
-
-		if (!sig->ev_signal_added) {
-			if (event_add(&sig->ev_signal, NULL))
-				return (-1);
-			sig->ev_signal_added = 1;
-		}
-	}
-
-	/* multiple events may listen to the same signal */
-	TAILQ_INSERT_TAIL(&sig->evsigevents[evsignal], ev, ev_signal_next);
-
-	return (0);
-}
-
-int
-_evsignal_restore_handler(struct event_base *base, int evsignal)
-{
-	int ret = 0;
-	struct evsignal_info *sig = &base->sig;
-#ifdef HAVE_SIGACTION
-	struct sigaction *sh;
-#else
-	ev_sighandler_t *sh;
-#endif
-
-	/* restore previous handler */
-	sh = sig->sh_old[evsignal];
-	sig->sh_old[evsignal] = NULL;
-#ifdef HAVE_SIGACTION
-	if (sigaction(evsignal, sh, NULL) == -1) {
-		event_warn("sigaction");
-		ret = -1;
-	}
-#else
-	if (signal(evsignal, *sh) == SIG_ERR) {
-		event_warn("signal");
-		ret = -1;
-	}
-#endif
-	free(sh);
-
-	return ret;
-}
-
-int
-evsignal_del(struct event *ev)
-{
-	struct event_base *base = ev->ev_base;
-	struct evsignal_info *sig = &base->sig;
-	int evsignal = EVENT_SIGNAL(ev);
-
-	assert(evsignal >= 0 && evsignal < NSIG);
-
-	/* multiple events may listen to the same signal */
-	TAILQ_REMOVE(&sig->evsigevents[evsignal], ev, ev_signal_next);
-
-	if (!TAILQ_EMPTY(&sig->evsigevents[evsignal]))
-		return (0);
-
-	event_debug(("%s: %p: restoring signal handler", __func__, ev));
-
-	return (_evsignal_restore_handler(ev->ev_base, EVENT_SIGNAL(ev)));
-}
-
-static void
-evsignal_handler(int sig)
-{
-	int save_errno = errno;
-
-	if (evsignal_base == NULL) {
-		event_warn(
-			"%s: received signal %d, but have no base configured",
-			__func__, sig);
-		return;
-	}
-
-	evsignal_base->sig.evsigcaught[sig]++;
-	evsignal_base->sig.evsignal_caught = 1;
-
-#ifndef HAVE_SIGACTION
-	signal(sig, evsignal_handler);
-#endif
-
-	/* Wake up our notification mechanism */
-	send(evsignal_base->sig.ev_signal_pair[0], "a", 1, 0);
-	errno = save_errno;
-}
-
-void
-evsignal_process(struct event_base *base)
-{
-	struct evsignal_info *sig = &base->sig;
-	struct event *ev, *next_ev;
-	sig_atomic_t ncalls;
-	int i;
-	
-	base->sig.evsignal_caught = 0;
-	for (i = 1; i < NSIG; ++i) {
-		ncalls = sig->evsigcaught[i];
-		if (ncalls == 0)
-			continue;
-		sig->evsigcaught[i] -= ncalls;
-
-		for (ev = TAILQ_FIRST(&sig->evsigevents[i]);
-		    ev != NULL; ev = next_ev) {
-			next_ev = TAILQ_NEXT(ev, ev_signal_next);
-			if (!(ev->ev_events & EV_PERSIST))
-				event_del(ev);
-			event_active(ev, EV_SIGNAL, ncalls);
-		}
-
-	}
-}
-
-void
-evsignal_dealloc(struct event_base *base)
-{
-	int i = 0;
-	if (base->sig.ev_signal_added) {
-		event_del(&base->sig.ev_signal);
-		base->sig.ev_signal_added = 0;
-	}
-	for (i = 0; i < NSIG; ++i) {
-		if (i < base->sig.sh_old_max && base->sig.sh_old[i] != NULL)
-			_evsignal_restore_handler(base, i);
-	}
-
-	if (base->sig.ev_signal_pair[0] != -1) {
-		EVUTIL_CLOSESOCKET(base->sig.ev_signal_pair[0]);
-		base->sig.ev_signal_pair[0] = -1;
-	}
-	if (base->sig.ev_signal_pair[1] != -1) {
-		EVUTIL_CLOSESOCKET(base->sig.ev_signal_pair[1]);
-		base->sig.ev_signal_pair[1] = -1;
-	}
-	base->sig.sh_old_max = 0;
-
-	/* per index frees are handled in evsig_del() */
-	if (base->sig.sh_old) {
-		free(base->sig.sh_old);
-		base->sig.sh_old = NULL;
-	}
-}
diff --git a/base/third_party/libevent/solaris/config.h b/base/third_party/libevent/solaris/config.h
deleted file mode 100644
index 4dd40eb..0000000
--- a/base/third_party/libevent/solaris/config.h
+++ /dev/null
@@ -1,266 +0,0 @@
-/* config.h.  Generated from config.h.in by configure.  */
-/* config.h.in.  Generated from configure.in by autoheader.  */
-
-/* Define if clock_gettime is available in libc */
-#define DNS_USE_CPU_CLOCK_FOR_ID 1
-
-/* Define is no secure id variant is available */
-/* #undef DNS_USE_GETTIMEOFDAY_FOR_ID */
-
-/* Define to 1 if you have the `clock_gettime' function. */
-#define HAVE_CLOCK_GETTIME 1
-
-/* Define if /dev/poll is available */
-#define HAVE_DEVPOLL 1
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define if your system supports the epoll system calls */
-/* #undef HAVE_EPOLL */
-
-/* Define to 1 if you have the `epoll_ctl' function. */
-/* #undef HAVE_EPOLL_CTL */
-
-/* Define if your system supports event ports */
-#define HAVE_EVENT_PORTS 1
-
-/* Define to 1 if you have the `fcntl' function. */
-#define HAVE_FCNTL 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define HAVE_FCNTL_H 1
-
-/* Define to 1 if the system has the type `fd_mask'. */
-#define HAVE_FD_MASK 1
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#define HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the `getegid' function. */
-#define HAVE_GETEGID 1
-
-/* Define to 1 if you have the `geteuid' function. */
-#define HAVE_GETEUID 1
-
-/* Define to 1 if you have the `getnameinfo' function. */
-#define HAVE_GETNAMEINFO 1
-
-/* Define to 1 if you have the `gettimeofday' function. */
-#define HAVE_GETTIMEOFDAY 1
-
-/* Define to 1 if you have the `inet_ntop' function. */
-#define HAVE_INET_NTOP 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `issetugid' function. */
-#define HAVE_ISSETUGID 1
-
-/* Define to 1 if you have the `kqueue' function. */
-/* #undef HAVE_KQUEUE */
-
-/* Define to 1 if you have the `nsl' library (-lnsl). */
-#define HAVE_LIBNSL 1
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-#define HAVE_LIBRESOLV 1
-
-/* Define to 1 if you have the `rt' library (-lrt). */
-#define HAVE_LIBRT 1
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-#define HAVE_LIBSOCKET 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netinet/in6.h> header file. */
-/* #undef HAVE_NETINET_IN6_H */
-
-/* Define to 1 if you have the `poll' function. */
-#define HAVE_POLL 1
-
-/* Define to 1 if you have the <poll.h> header file. */
-#define HAVE_POLL_H 1
-
-/* Define to 1 if you have the `port_create' function. */
-#define HAVE_PORT_CREATE 1
-
-/* Define to 1 if you have the <port.h> header file. */
-#define HAVE_PORT_H 1
-
-/* Define to 1 if you have the `select' function. */
-#define HAVE_SELECT 1
-
-/* Define if F_SETFD is defined in <fcntl.h> */
-#define HAVE_SETFD 1
-
-/* Define to 1 if you have the `sigaction' function. */
-#define HAVE_SIGACTION 1
-
-/* Define to 1 if you have the `signal' function. */
-#define HAVE_SIGNAL 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the <stdarg.h> header file. */
-#define HAVE_STDARG_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-#define HAVE_STRLCPY 1
-
-/* Define to 1 if you have the `strsep' function. */
-#define HAVE_STRSEP 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-#define HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the `strtoll' function. */
-#define HAVE_STRTOLL 1
-
-/* Define to 1 if the system has the type `struct in6_addr'. */
-#define HAVE_STRUCT_IN6_ADDR 1
-
-/* Define to 1 if you have the <sys/devpoll.h> header file. */
-#define HAVE_SYS_DEVPOLL_H 1
-
-/* Define to 1 if you have the <sys/epoll.h> header file. */
-/* #undef HAVE_SYS_EPOLL_H */
-
-/* Define to 1 if you have the <sys/event.h> header file. */
-/* #undef HAVE_SYS_EVENT_H */
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-#define HAVE_SYS_IOCTL_H 1
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/queue.h> header file. */
-#define HAVE_SYS_QUEUE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#define HAVE_SYS_SELECT_H 1
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
-#define HAVE_TAILQFOREACH 1
-
-/* Define if timeradd is defined in <sys/time.h> */
-#define HAVE_TIMERADD 1
-
-/* Define if timerclear is defined in <sys/time.h> */
-#define HAVE_TIMERCLEAR 1
-
-/* Define if timercmp is defined in <sys/time.h> */
-#define HAVE_TIMERCMP 1
-
-/* Define if timerisset is defined in <sys/time.h> */
-#define HAVE_TIMERISSET 1
-
-/* Define to 1 if the system has the type `uint16_t'. */
-#define HAVE_UINT16_T 1
-
-/* Define to 1 if the system has the type `uint32_t'. */
-#define HAVE_UINT32_T 1
-
-/* Define to 1 if the system has the type `uint64_t'. */
-#define HAVE_UINT64_T 1
-
-/* Define to 1 if the system has the type `uint8_t'. */
-#define HAVE_UINT8_T 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `vasprintf' function. */
-#define HAVE_VASPRINTF 1
-
-/* Define if kqueue works correctly with pipes */
-/* #undef HAVE_WORKING_KQUEUE */
-
-/* Name of package */
-#define PACKAGE "libevent"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT ""
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME ""
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING ""
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME ""
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION ""
-
-/* The size of `int', as computed by sizeof. */
-#define SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define SIZEOF_LONG 4
-
-/* The size of `long long', as computed by sizeof. */
-#define SIZEOF_LONG_LONG 8
-
-/* The size of `short', as computed by sizeof. */
-#define SIZEOF_SHORT 2
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define TIME_WITH_SYS_TIME 1
-
-/* Version number of package */
-#define VERSION "1.4.13-stable"
-
-/* Define to appropriate substitue if compiler doesnt have __func__ */
-/* #undef __func__ */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef const */
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
-   calls it, or to nothing if 'inline' is not supported under any name.  */
-#ifndef __cplusplus
-/* #undef inline */
-#endif
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef pid_t */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef size_t */
-
-/* Define to unsigned int if you dont have it */
-/* #undef socklen_t */
diff --git a/base/third_party/libevent/solaris/event-config.h b/base/third_party/libevent/solaris/event-config.h
deleted file mode 100644
index afabe2f..0000000
--- a/base/third_party/libevent/solaris/event-config.h
+++ /dev/null
@@ -1,284 +0,0 @@
-/* event-config.h
- * Generated by autoconf; post-processed by libevent.
- * Do not edit this file.
- * Do not rely on macros in this file existing in later versions.
- */
-#ifndef _EVENT_CONFIG_H_
-#define _EVENT_CONFIG_H_
-/* config.h.  Generated from config.h.in by configure.  */
-/* config.h.in.  Generated from configure.in by autoheader.  */
-
-/* Define if clock_gettime is available in libc */
-#define _EVENT_DNS_USE_CPU_CLOCK_FOR_ID 1
-
-/* Define is no secure id variant is available */
-/* #undef _EVENT_DNS_USE_GETTIMEOFDAY_FOR_ID */
-
-/* Define to 1 if you have the `clock_gettime' function. */
-#define _EVENT_HAVE_CLOCK_GETTIME 1
-
-/* Define if /dev/poll is available */
-#define _EVENT_HAVE_DEVPOLL 1
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define _EVENT_HAVE_DLFCN_H 1
-
-/* Define if your system supports the epoll system calls */
-/* #undef _EVENT_HAVE_EPOLL */
-
-/* Define to 1 if you have the `epoll_ctl' function. */
-/* #undef _EVENT_HAVE_EPOLL_CTL */
-
-/* Define if your system supports event ports */
-#define _EVENT_HAVE_EVENT_PORTS 1
-
-/* Define to 1 if you have the `fcntl' function. */
-#define _EVENT_HAVE_FCNTL 1
-
-/* Define to 1 if you have the <fcntl.h> header file. */
-#define _EVENT_HAVE_FCNTL_H 1
-
-/* Define to 1 if the system has the type `fd_mask'. */
-#define _EVENT_HAVE_FD_MASK 1
-
-/* Define to 1 if you have the `getaddrinfo' function. */
-#define _EVENT_HAVE_GETADDRINFO 1
-
-/* Define to 1 if you have the `getegid' function. */
-#define _EVENT_HAVE_GETEGID 1
-
-/* Define to 1 if you have the `geteuid' function. */
-#define _EVENT_HAVE_GETEUID 1
-
-/* Define to 1 if you have the `getnameinfo' function. */
-#define _EVENT_HAVE_GETNAMEINFO 1
-
-/* Define to 1 if you have the `gettimeofday' function. */
-#define _EVENT_HAVE_GETTIMEOFDAY 1
-
-/* Define to 1 if you have the `inet_ntop' function. */
-#define _EVENT_HAVE_INET_NTOP 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define _EVENT_HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `issetugid' function. */
-#define _EVENT_HAVE_ISSETUGID 1
-
-/* Define to 1 if you have the `kqueue' function. */
-/* #undef _EVENT_HAVE_KQUEUE */
-
-/* Define to 1 if you have the `nsl' library (-lnsl). */
-#define _EVENT_HAVE_LIBNSL 1
-
-/* Define to 1 if you have the `resolv' library (-lresolv). */
-#define _EVENT_HAVE_LIBRESOLV 1
-
-/* Define to 1 if you have the `rt' library (-lrt). */
-#define _EVENT_HAVE_LIBRT 1
-
-/* Define to 1 if you have the `socket' library (-lsocket). */
-#define _EVENT_HAVE_LIBSOCKET 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define _EVENT_HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the <netinet/in6.h> header file. */
-/* #undef _EVENT_HAVE_NETINET_IN6_H */
-
-/* Define to 1 if you have the `poll' function. */
-#define _EVENT_HAVE_POLL 1
-
-/* Define to 1 if you have the <poll.h> header file. */
-#define _EVENT_HAVE_POLL_H 1
-
-/* Define to 1 if you have the `port_create' function. */
-#define _EVENT_HAVE_PORT_CREATE 1
-
-/* Define to 1 if you have the <port.h> header file. */
-#define _EVENT_HAVE_PORT_H 1
-
-/* Define to 1 if you have the `select' function. */
-#define _EVENT_HAVE_SELECT 1
-
-/* Define if F_SETFD is defined in <fcntl.h> */
-#define _EVENT_HAVE_SETFD 1
-
-/* Define to 1 if you have the `sigaction' function. */
-#define _EVENT_HAVE_SIGACTION 1
-
-/* Define to 1 if you have the `signal' function. */
-#define _EVENT_HAVE_SIGNAL 1
-
-/* Define to 1 if you have the <signal.h> header file. */
-#define _EVENT_HAVE_SIGNAL_H 1
-
-/* Define to 1 if you have the <stdarg.h> header file. */
-#define _EVENT_HAVE_STDARG_H 1
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define _EVENT_HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define _EVENT_HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define _EVENT_HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define _EVENT_HAVE_STRING_H 1
-
-/* Define to 1 if you have the `strlcpy' function. */
-#define _EVENT_HAVE_STRLCPY 1
-
-/* Define to 1 if you have the `strsep' function. */
-#define _EVENT_HAVE_STRSEP 1
-
-/* Define to 1 if you have the `strtok_r' function. */
-#define _EVENT_HAVE_STRTOK_R 1
-
-/* Define to 1 if you have the `strtoll' function. */
-#define _EVENT_HAVE_STRTOLL 1
-
-/* Define to 1 if the system has the type `struct in6_addr'. */
-#define _EVENT_HAVE_STRUCT_IN6_ADDR 1
-
-/* Define to 1 if you have the <sys/devpoll.h> header file. */
-#define _EVENT_HAVE_SYS_DEVPOLL_H 1
-
-/* Define to 1 if you have the <sys/epoll.h> header file. */
-/* #undef _EVENT_HAVE_SYS_EPOLL_H */
-
-/* Define to 1 if you have the <sys/event.h> header file. */
-/* #undef _EVENT_HAVE_SYS_EVENT_H */
-
-/* Define to 1 if you have the <sys/ioctl.h> header file. */
-#define _EVENT_HAVE_SYS_IOCTL_H 1
-
-/* Define to 1 if you have the <sys/param.h> header file. */
-#define _EVENT_HAVE_SYS_PARAM_H 1
-
-/* Define to 1 if you have the <sys/queue.h> header file. */
-#define _EVENT_HAVE_SYS_QUEUE_H 1
-
-/* Define to 1 if you have the <sys/select.h> header file. */
-#define _EVENT_HAVE_SYS_SELECT_H 1
-
-/* Define to 1 if you have the <sys/socket.h> header file. */
-#define _EVENT_HAVE_SYS_SOCKET_H 1
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define _EVENT_HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/time.h> header file. */
-#define _EVENT_HAVE_SYS_TIME_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define _EVENT_HAVE_SYS_TYPES_H 1
-
-/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
-#define _EVENT_HAVE_TAILQFOREACH 1
-
-/* Define if timeradd is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERADD 1
-
-/* Define if timerclear is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERCLEAR 1
-
-/* Define if timercmp is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERCMP 1
-
-/* Define if timerisset is defined in <sys/time.h> */
-#define _EVENT_HAVE_TIMERISSET 1
-
-/* Define to 1 if the system has the type `uint16_t'. */
-#define _EVENT_HAVE_UINT16_T 1
-
-/* Define to 1 if the system has the type `uint32_t'. */
-#define _EVENT_HAVE_UINT32_T 1
-
-/* Define to 1 if the system has the type `uint64_t'. */
-#define _EVENT_HAVE_UINT64_T 1
-
-/* Define to 1 if the system has the type `uint8_t'. */
-#define _EVENT_HAVE_UINT8_T 1
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define _EVENT_HAVE_UNISTD_H 1
-
-/* Define to 1 if you have the `vasprintf' function. */
-#define _EVENT_HAVE_VASPRINTF 1
-
-/* Define if kqueue works correctly with pipes */
-/* #undef _EVENT_HAVE_WORKING_KQUEUE */
-
-/* Define to the sub-directory in which libtool stores uninstalled libraries.
-   */
-#define _EVENT_LT_OBJDIR ".libs/"
-
-/* Numeric representation of the version */
-#define _EVENT_NUMERIC_VERSION 0x01040f00
-
-/* Name of package */
-#define _EVENT_PACKAGE "libevent"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define _EVENT_PACKAGE_BUGREPORT ""
-
-/* Define to the full name of this package. */
-#define _EVENT_PACKAGE_NAME ""
-
-/* Define to the full name and version of this package. */
-#define _EVENT_PACKAGE_STRING ""
-
-/* Define to the one symbol short name of this package. */
-#define _EVENT_PACKAGE_TARNAME ""
-
-/* Define to the home page for this package. */
-#define _EVENT_PACKAGE_URL ""
-
-/* Define to the version of this package. */
-#define _EVENT_PACKAGE_VERSION ""
-
-/* The size of `int', as computed by sizeof. */
-#define _EVENT_SIZEOF_INT 4
-
-/* The size of `long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG 4
-
-/* The size of `long long', as computed by sizeof. */
-#define _EVENT_SIZEOF_LONG_LONG 8
-
-/* The size of `short', as computed by sizeof. */
-#define _EVENT_SIZEOF_SHORT 2
-
-/* Define to 1 if you have the ANSI C header files. */
-#define _EVENT_STDC_HEADERS 1
-
-/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
-#define _EVENT_TIME_WITH_SYS_TIME 1
-
-/* Version number of package */
-#define _EVENT_VERSION "1.4.15"
-
-/* Define to appropriate substitue if compiler doesnt have __func__ */
-/* #undef _EVENT___func__ */
-
-/* Define to empty if `const' does not conform to ANSI C. */
-/* #undef _EVENT_const */
-
-/* Define to `__inline__' or `__inline' if that's what the C compiler
-   calls it, or to nothing if 'inline' is not supported under any name.  */
-#ifndef _EVENT___cplusplus
-/* #undef _EVENT_inline */
-#endif
-
-/* Define to `int' if <sys/types.h> does not define. */
-/* #undef _EVENT_pid_t */
-
-/* Define to `unsigned int' if <sys/types.h> does not define. */
-/* #undef _EVENT_size_t */
-
-/* Define to unsigned int if you dont have it */
-/* #undef _EVENT_socklen_t */
-#endif
diff --git a/base/third_party/libevent/stamp-h.in b/base/third_party/libevent/stamp-h.in
deleted file mode 100644
index 9788f70..0000000
--- a/base/third_party/libevent/stamp-h.in
+++ /dev/null
@@ -1 +0,0 @@
-timestamp
diff --git a/base/third_party/libevent/strlcpy-internal.h b/base/third_party/libevent/strlcpy-internal.h
deleted file mode 100644
index 22b5f61..0000000
--- a/base/third_party/libevent/strlcpy-internal.h
+++ /dev/null
@@ -1,23 +0,0 @@
-#ifndef _STRLCPY_INTERNAL_H_
-#define _STRLCPY_INTERNAL_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#ifndef HAVE_STRLCPY
-#include <string.h>
-size_t _event_strlcpy(char *dst, const char *src, size_t siz);
-#define strlcpy _event_strlcpy
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
diff --git a/base/third_party/libevent/strlcpy.c b/base/third_party/libevent/strlcpy.c
deleted file mode 100644
index 5d19452..0000000
--- a/base/third_party/libevent/strlcpy.c
+++ /dev/null
@@ -1,76 +0,0 @@
-/*	$OpenBSD: strlcpy.c,v 1.5 2001/05/13 15:40:16 deraadt Exp $	*/
-
-/*
- * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
- * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char *rcsid = "$OpenBSD: strlcpy.c,v 1.5 2001/05/13 15:40:16 deraadt Exp $";
-#endif /* LIBC_SCCS and not lint */
-
-#include <sys/types.h>
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif /* HAVE_CONFIG_H */
-
-#ifndef HAVE_STRLCPY
-#include "strlcpy-internal.h"
-
-/*
- * Copy src to string dst of size siz.  At most siz-1 characters
- * will be copied.  Always NUL terminates (unless siz == 0).
- * Returns strlen(src); if retval >= siz, truncation occurred.
- */
-size_t
-_event_strlcpy(dst, src, siz)
-	char *dst;
-	const char *src;
-	size_t siz;
-{
-	register char *d = dst;
-	register const char *s = src;
-	register size_t n = siz;
-
-	/* Copy as many bytes as will fit */
-	if (n != 0 && --n != 0) {
-		do {
-			if ((*d++ = *s++) == 0)
-				break;
-		} while (--n != 0);
-	}
-
-	/* Not enough room in dst, add NUL and traverse rest of src */
-	if (n == 0) {
-		if (siz != 0)
-			*d = '\0';		/* NUL-terminate dst */
-		while (*s++)
-			;
-	}
-
-	return(s - src - 1);	/* count does not include NUL */
-}
-#endif
diff --git a/base/third_party/libevent/test/Makefile.am b/base/third_party/libevent/test/Makefile.am
deleted file mode 100644
index 3558d02..0000000
--- a/base/third_party/libevent/test/Makefile.am
+++ /dev/null
@@ -1,35 +0,0 @@
-AUTOMAKE_OPTIONS = foreign no-dependencies
-
-AM_CFLAGS = -I$(top_srcdir) -I$(top_srcdir)/compat
-
-EXTRA_DIST = regress.rpc regress.gen.h regress.gen.c
-
-noinst_PROGRAMS = test-init test-eof test-weof test-time regress bench
-
-BUILT_SOURCES = regress.gen.c regress.gen.h
-test_init_SOURCES = test-init.c
-test_init_LDADD = ../libevent_core.la
-test_eof_SOURCES = test-eof.c
-test_eof_LDADD = ../libevent_core.la
-test_weof_SOURCES = test-weof.c
-test_weof_LDADD = ../libevent_core.la
-test_time_SOURCES = test-time.c
-test_time_LDADD = ../libevent_core.la
-regress_SOURCES = regress.c regress.h regress_http.c regress_dns.c \
-	regress_rpc.c \
-	regress.gen.c regress.gen.h
-regress_LDADD = ../libevent.la
-bench_SOURCES = bench.c
-bench_LDADD = ../libevent.la
-
-regress.gen.c regress.gen.h: regress.rpc $(top_srcdir)/event_rpcgen.py
-	$(top_srcdir)/event_rpcgen.py $(srcdir)/regress.rpc || echo "No Python installed"
-
-DISTCLEANFILES = *~
-
-test: test-init test-eof test-weof test-time regress
-
-verify: test
-	@$(srcdir)/test.sh
-
-bench test-init test-eof test-weof test-time: ../libevent.la
diff --git a/base/third_party/libevent/test/Makefile.nmake b/base/third_party/libevent/test/Makefile.nmake
deleted file mode 100644
index 320abe7..0000000
--- a/base/third_party/libevent/test/Makefile.nmake
+++ /dev/null
@@ -1,47 +0,0 @@
-
-CFLAGS=/I.. /I../include /I../WIN32-Code /I../compat /DWIN32 /DHAVE_CONFIG_H
-
-CFLAGS=$(CFLAGS) /Ox /W3 /wd4996 /nologo
-
-REGRESS_OBJS=regress.obj regress_http.obj regress_dns.obj \
-        regress_rpc.obj regress.gen.obj \
-
-OTHER_OBJS=test-init.obj test-eof.obj test-weof.obj test-time.obj \
-	bench.obj bench_cascade.obj bench_http.obj bench_httpclient.obj
-
-PROGRAMS=regress.exe \
-	test-init.exe test-eof.exe test-weof.exe test-time.exe
-
-# Disabled for now:
-#	bench.exe bench_cascade.exe bench_http.exe bench_httpclient.exe
-
-
-LIBS=..\libevent.lib ws2_32.lib advapi32.lib
-
-all: $(PROGRAMS)
-
-regress.exe: $(REGRESS_OBJS)
-	$(CC) $(CFLAGS) $(LIBS) $(REGRESS_OBJS)
-
-test-init.exe: test-init.obj
-	$(CC) $(CFLAGS) $(LIBS) test-init.obj
-test-eof.exe: test-eof.obj
-	$(CC) $(CFLAGS) $(LIBS) test-eof.obj
-test-weof.exe: test-weof.obj
-	$(CC) $(CFLAGS) $(LIBS) test-weof.obj
-test-time.exe: test-time.obj
-	$(CC) $(CFLAGS) $(LIBS) test-time.obj
-
-bench.exe: bench.obj
-	$(CC) $(CFLAGS) $(LIBS) bench.obj
-bench_cascade.exe: bench_cascade.obj
-	$(CC) $(CFLAGS) $(LIBS) bench_cascade.obj
-bench_http.exe: bench_http.obj
-	$(CC) $(CFLAGS) $(LIBS) bench_http.obj
-bench_httpclient.exe: bench_httpclient.obj
-	$(CC) $(CFLAGS) $(LIBS) bench_httpclient.obj
-
-clean:
-	-del $(REGRESS_OBJS)
-	-del $(OTHER_OBJS)
-	-del regress.exe
diff --git a/base/third_party/libevent/test/bench.c b/base/third_party/libevent/test/bench.c
deleted file mode 100644
index c976932..0000000
--- a/base/third_party/libevent/test/bench.c
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Copyright 2003 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 4. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- *
- * Mon 03/10/2003 - Modified by Davide Libenzi <davidel@xmailserver.org>
- *
- *     Added chain event propagation to improve the sensitivity of
- *     the measure respect to the event loop efficency.
- *
- *
- */
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#ifdef WIN32
-#include <windows.h>
-#else
-#include <sys/socket.h>
-#include <signal.h>
-#include <sys/resource.h>
-#endif
-#include <fcntl.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-#include <errno.h>
-
-#include <event.h>
-#include <evutil.h>
-
-
-static int count, writes, fired;
-static int *pipes;
-static int num_pipes, num_active, num_writes;
-static struct event *events;
-
-static void
-read_cb(int fd, short which, void *arg)
-{
-	long idx = (long) arg, widx = idx + 1;
-	u_char ch;
-
-	count += read(fd, &ch, sizeof(ch));
-	if (writes) {
-		if (widx >= num_pipes)
-			widx -= num_pipes;
-		write(pipes[2 * widx + 1], "e", 1);
-		writes--;
-		fired++;
-	}
-}
-
-static struct timeval *
-run_once(void)
-{
-	int *cp, space;
-	long i;
-	static struct timeval ts, te;
-
-	for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
-		event_del(&events[i]);
-		event_set(&events[i], cp[0], EV_READ | EV_PERSIST, read_cb, (void *) i);
-		event_add(&events[i], NULL);
-	}
-
-	event_loop(EVLOOP_ONCE | EVLOOP_NONBLOCK);
-
-	fired = 0;
-	space = num_pipes / num_active;
-	space = space * 2;
-	for (i = 0; i < num_active; i++, fired++)
-		write(pipes[i * space + 1], "e", 1);
-
-	count = 0;
-	writes = num_writes;
-	{ int xcount = 0;
-	gettimeofday(&ts, NULL);
-	do {
-		event_loop(EVLOOP_ONCE | EVLOOP_NONBLOCK);
-		xcount++;
-	} while (count != fired);
-	gettimeofday(&te, NULL);
-
-	if (xcount != count) fprintf(stderr, "Xcount: %d, Rcount: %d\n", xcount, count);
-	}
-
-	evutil_timersub(&te, &ts, &te);
-
-	return (&te);
-}
-
-int
-main (int argc, char **argv)
-{
-#ifndef WIN32
-	struct rlimit rl;
-#endif
-	int i, c;
-	struct timeval *tv;
-	int *cp;
-
-	num_pipes = 100;
-	num_active = 1;
-	num_writes = num_pipes;
-	while ((c = getopt(argc, argv, "n:a:w:")) != -1) {
-		switch (c) {
-		case 'n':
-			num_pipes = atoi(optarg);
-			break;
-		case 'a':
-			num_active = atoi(optarg);
-			break;
-		case 'w':
-			num_writes = atoi(optarg);
-			break;
-		default:
-			fprintf(stderr, "Illegal argument \"%c\"\n", c);
-			exit(1);
-		}
-	}
-
-#ifndef WIN32
-	rl.rlim_cur = rl.rlim_max = num_pipes * 2 + 50;
-	if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
-		perror("setrlimit");
-		exit(1);
-	}
-#endif
-
-	events = calloc(num_pipes, sizeof(struct event));
-	pipes = calloc(num_pipes * 2, sizeof(int));
-	if (events == NULL || pipes == NULL) {
-		perror("malloc");
-		exit(1);
-	}
-
-	event_init();
-
-	for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
-#ifdef USE_PIPES
-		if (pipe(cp) == -1) {
-#else
-		if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, cp) == -1) {
-#endif
-			perror("pipe");
-			exit(1);
-		}
-	}
-
-	for (i = 0; i < 25; i++) {
-		tv = run_once();
-		if (tv == NULL)
-			exit(1);
-		fprintf(stdout, "%ld\n",
-			tv->tv_sec * 1000000L + tv->tv_usec);
-	}
-
-	exit(0);
-}
diff --git a/base/third_party/libevent/test/regress.c b/base/third_party/libevent/test/regress.c
deleted file mode 100644
index cce7d7d..0000000
--- a/base/third_party/libevent/test/regress.c
+++ /dev/null
@@ -1,1903 +0,0 @@
-/*
- * Copyright (c) 2003, 2004 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef WIN32
-#include <winsock2.h>
-#include <windows.h>
-#endif
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#include <sys/queue.h>
-#ifndef WIN32
-#include <sys/socket.h>
-#include <sys/wait.h>
-#include <signal.h>
-#include <unistd.h>
-#include <netdb.h>
-#endif
-#include <assert.h>
-#include <fcntl.h>
-#include <signal.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-
-#include "event.h"
-#include "evutil.h"
-#include "event-internal.h"
-#include "log.h"
-
-#include "regress.h"
-#ifndef WIN32
-#include "regress.gen.h"
-#endif
-
-int pair[2];
-int test_ok;
-static int called;
-static char wbuf[4096];
-static char rbuf[4096];
-static int woff;
-static int roff;
-static int usepersist;
-static struct timeval tset;
-static struct timeval tcalled;
-static struct event_base *global_base;
-
-#define TEST1	"this is a test"
-#define SECONDS	1
-
-#ifndef SHUT_WR
-#define SHUT_WR 1
-#endif
-
-#ifdef WIN32
-#define write(fd,buf,len) send((fd),(buf),(len),0)
-#define read(fd,buf,len) recv((fd),(buf),(len),0)
-#endif
-
-static void
-simple_read_cb(int fd, short event, void *arg)
-{
-	char buf[256];
-	int len;
-
-	if (arg == NULL)
-		return;
-
-	len = read(fd, buf, sizeof(buf));
-
-	if (len) {
-		if (!called) {
-			if (event_add(arg, NULL) == -1)
-				exit(1);
-		}
-	} else if (called == 1)
-		test_ok = 1;
-
-	called++;
-}
-
-static void
-simple_write_cb(int fd, short event, void *arg)
-{
-	int len;
-
-	if (arg == NULL)
-		return;
-
-	len = write(fd, TEST1, strlen(TEST1) + 1);
-	if (len == -1)
-		test_ok = 0;
-	else
-		test_ok = 1;
-}
-
-static void
-multiple_write_cb(int fd, short event, void *arg)
-{
-	struct event *ev = arg;
-	int len;
-
-	len = 128;
-	if (woff + len >= sizeof(wbuf))
-		len = sizeof(wbuf) - woff;
-
-	len = write(fd, wbuf + woff, len);
-	if (len == -1) {
-		fprintf(stderr, "%s: write\n", __func__);
-		if (usepersist)
-			event_del(ev);
-		return;
-	}
-
-	woff += len;
-
-	if (woff >= sizeof(wbuf)) {
-		shutdown(fd, SHUT_WR);
-		if (usepersist)
-			event_del(ev);
-		return;
-	}
-
-	if (!usepersist) {
-		if (event_add(ev, NULL) == -1)
-			exit(1);
-	}
-}
-
-static void
-multiple_read_cb(int fd, short event, void *arg)
-{
-	struct event *ev = arg;
-	int len;
-
-	len = read(fd, rbuf + roff, sizeof(rbuf) - roff);
-	if (len == -1)
-		fprintf(stderr, "%s: read\n", __func__);
-	if (len <= 0) {
-		if (usepersist)
-			event_del(ev);
-		return;
-	}
-
-	roff += len;
-	if (!usepersist) {
-		if (event_add(ev, NULL) == -1) 
-			exit(1);
-	}
-}
-
-static void
-timeout_cb(int fd, short event, void *arg)
-{
-	struct timeval tv;
-	int diff;
-
-	evutil_gettimeofday(&tcalled, NULL);
-	if (evutil_timercmp(&tcalled, &tset, >))
-		evutil_timersub(&tcalled, &tset, &tv);
-	else
-		evutil_timersub(&tset, &tcalled, &tv);
-
-	diff = tv.tv_sec*1000 + tv.tv_usec/1000 - SECONDS * 1000;
-	if (diff < 0)
-		diff = -diff;
-
-	if (diff < 100)
-		test_ok = 1;
-}
-
-#ifndef WIN32
-static void
-signal_cb_sa(int sig)
-{
-	test_ok = 2;
-}
-
-static void
-signal_cb(int fd, short event, void *arg)
-{
-	struct event *ev = arg;
-
-	signal_del(ev);
-	test_ok = 1;
-}
-#endif
-
-struct both {
-	struct event ev;
-	int nread;
-};
-
-static void
-combined_read_cb(int fd, short event, void *arg)
-{
-	struct both *both = arg;
-	char buf[128];
-	int len;
-
-	len = read(fd, buf, sizeof(buf));
-	if (len == -1)
-		fprintf(stderr, "%s: read\n", __func__);
-	if (len <= 0)
-		return;
-
-	both->nread += len;
-	if (event_add(&both->ev, NULL) == -1)
-		exit(1);
-}
-
-static void
-combined_write_cb(int fd, short event, void *arg)
-{
-	struct both *both = arg;
-	char buf[128];
-	int len;
-
-	len = sizeof(buf);
-	if (len > both->nread)
-		len = both->nread;
-
-	len = write(fd, buf, len);
-	if (len == -1)
-		fprintf(stderr, "%s: write\n", __func__);
-	if (len <= 0) {
-		shutdown(fd, SHUT_WR);
-		return;
-	}
-
-	both->nread -= len;
-	if (event_add(&both->ev, NULL) == -1)
-		exit(1);
-}
-
-/* Test infrastructure */
-
-static int
-setup_test(const char *name)
-{
-
-	fprintf(stdout, "%s", name);
-
-	if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) {
-		fprintf(stderr, "%s: socketpair\n", __func__);
-		exit(1);
-	}
-
-#ifdef HAVE_FCNTL
-        if (fcntl(pair[0], F_SETFL, O_NONBLOCK) == -1)
-		fprintf(stderr, "fcntl(O_NONBLOCK)");
-
-        if (fcntl(pair[1], F_SETFL, O_NONBLOCK) == -1)
-		fprintf(stderr, "fcntl(O_NONBLOCK)");
-#endif
-
-	test_ok = 0;
-	called = 0;
-	return (0);
-}
-
-static int
-cleanup_test(void)
-{
-#ifndef WIN32
-	close(pair[0]);
-	close(pair[1]);
-#else
-	CloseHandle((HANDLE)pair[0]);
-	CloseHandle((HANDLE)pair[1]);
-#endif
-	if (test_ok)
-		fprintf(stdout, "OK\n");
-	else {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-        test_ok = 0;
-	return (0);
-}
-
-static void
-test_registerfds(void)
-{
-	int i, j;
-	int pair[2];
-	struct event read_evs[512];
-	struct event write_evs[512];
-
-	struct event_base *base = event_base_new();
-
-	fprintf(stdout, "Testing register fds: ");
-
-	for (i = 0; i < 512; ++i) {
-		if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) {
-			/* run up to the limit of file descriptors */
-			break;
-		}
-		event_set(&read_evs[i], pair[0],
-		    EV_READ|EV_PERSIST, simple_read_cb, NULL);
-		event_base_set(base, &read_evs[i]);
-		event_add(&read_evs[i], NULL);
-		event_set(&write_evs[i], pair[1],
-		    EV_WRITE|EV_PERSIST, simple_write_cb, NULL);
-		event_base_set(base, &write_evs[i]);
-		event_add(&write_evs[i], NULL);
-
-		/* just loop once */
-		event_base_loop(base, EVLOOP_ONCE);
-	}
-
-	/* now delete everything */
-	for (j = 0; j < i; ++j) {
-		event_del(&read_evs[j]);
-		event_del(&write_evs[j]);
-#ifndef WIN32
-		close(read_evs[j].ev_fd);
-		close(write_evs[j].ev_fd);
-#else
-		CloseHandle((HANDLE)read_evs[j].ev_fd);
-		CloseHandle((HANDLE)write_evs[j].ev_fd);
-#endif
-
-		/* just loop once */
-		event_base_loop(base, EVLOOP_ONCE);
-	}
-
-	event_base_free(base);
-
-	fprintf(stdout, "OK\n");
-}
-
-static void
-test_simpleread(void)
-{
-	struct event ev;
-
-	/* Very simple read test */
-	setup_test("Simple read: ");
-	
-	write(pair[0], TEST1, strlen(TEST1)+1);
-	shutdown(pair[0], SHUT_WR);
-
-	event_set(&ev, pair[1], EV_READ, simple_read_cb, &ev);
-	if (event_add(&ev, NULL) == -1)
-		exit(1);
-	event_dispatch();
-
-	cleanup_test();
-}
-
-static void
-test_simplewrite(void)
-{
-	struct event ev;
-
-	/* Very simple write test */
-	setup_test("Simple write: ");
-	
-	event_set(&ev, pair[0], EV_WRITE, simple_write_cb, &ev);
-	if (event_add(&ev, NULL) == -1)
-		exit(1);
-	event_dispatch();
-
-	cleanup_test();
-}
-
-static void
-test_multiple(void)
-{
-	struct event ev, ev2;
-	int i;
-
-	/* Multiple read and write test */
-	setup_test("Multiple read/write: ");
-	memset(rbuf, 0, sizeof(rbuf));
-	for (i = 0; i < sizeof(wbuf); i++)
-		wbuf[i] = i;
-
-	roff = woff = 0;
-	usepersist = 0;
-
-	event_set(&ev, pair[0], EV_WRITE, multiple_write_cb, &ev);
-	if (event_add(&ev, NULL) == -1)
-		exit(1);
-	event_set(&ev2, pair[1], EV_READ, multiple_read_cb, &ev2);
-	if (event_add(&ev2, NULL) == -1)
-		exit(1);
-	event_dispatch();
-
-	if (roff == woff)
-		test_ok = memcmp(rbuf, wbuf, sizeof(wbuf)) == 0;
-
-	cleanup_test();
-}
-
-static void
-test_persistent(void)
-{
-	struct event ev, ev2;
-	int i;
-
-	/* Multiple read and write test with persist */
-	setup_test("Persist read/write: ");
-	memset(rbuf, 0, sizeof(rbuf));
-	for (i = 0; i < sizeof(wbuf); i++)
-		wbuf[i] = i;
-
-	roff = woff = 0;
-	usepersist = 1;
-
-	event_set(&ev, pair[0], EV_WRITE|EV_PERSIST, multiple_write_cb, &ev);
-	if (event_add(&ev, NULL) == -1)
-		exit(1);
-	event_set(&ev2, pair[1], EV_READ|EV_PERSIST, multiple_read_cb, &ev2);
-	if (event_add(&ev2, NULL) == -1)
-		exit(1);
-	event_dispatch();
-
-	if (roff == woff)
-		test_ok = memcmp(rbuf, wbuf, sizeof(wbuf)) == 0;
-
-	cleanup_test();
-}
-
-static void
-test_combined(void)
-{
-	struct both r1, r2, w1, w2;
-
-	setup_test("Combined read/write: ");
-	memset(&r1, 0, sizeof(r1));
-	memset(&r2, 0, sizeof(r2));
-	memset(&w1, 0, sizeof(w1));
-	memset(&w2, 0, sizeof(w2));
-
-	w1.nread = 4096;
-	w2.nread = 8192;
-
-	event_set(&r1.ev, pair[0], EV_READ, combined_read_cb, &r1);
-	event_set(&w1.ev, pair[0], EV_WRITE, combined_write_cb, &w1);
-	event_set(&r2.ev, pair[1], EV_READ, combined_read_cb, &r2);
-	event_set(&w2.ev, pair[1], EV_WRITE, combined_write_cb, &w2);
-	if (event_add(&r1.ev, NULL) == -1)
-		exit(1);
-	if (event_add(&w1.ev, NULL))
-		exit(1);
-	if (event_add(&r2.ev, NULL))
-		exit(1);
-	if (event_add(&w2.ev, NULL))
-		exit(1);
-
-	event_dispatch();
-
-	if (r1.nread == 8192 && r2.nread == 4096)
-		test_ok = 1;
-
-	cleanup_test();
-}
-
-static void
-test_simpletimeout(void)
-{
-	struct timeval tv;
-	struct event ev;
-
-	setup_test("Simple timeout: ");
-
-	tv.tv_usec = 0;
-	tv.tv_sec = SECONDS;
-	evtimer_set(&ev, timeout_cb, NULL);
-	evtimer_add(&ev, &tv);
-
-	evutil_gettimeofday(&tset, NULL);
-	event_dispatch();
-
-	cleanup_test();
-}
-
-#ifndef WIN32
-extern struct event_base *current_base;
-
-static void
-child_signal_cb(int fd, short event, void *arg)
-{
-	struct timeval tv;
-	int *pint = arg;
-
-	*pint = 1;
-
-	tv.tv_usec = 500000;
-	tv.tv_sec = 0;
-	event_loopexit(&tv);
-}
-
-static void
-test_fork(void)
-{
-	int status, got_sigchld = 0;
-	struct event ev, sig_ev;
-	pid_t pid;
-
-	setup_test("After fork: ");
-
-	write(pair[0], TEST1, strlen(TEST1)+1);
-
-	event_set(&ev, pair[1], EV_READ, simple_read_cb, &ev);
-	if (event_add(&ev, NULL) == -1)
-		exit(1);
-
-	signal_set(&sig_ev, SIGCHLD, child_signal_cb, &got_sigchld);
-	signal_add(&sig_ev, NULL);
-
-	if ((pid = fork()) == 0) {
-		/* in the child */
-		if (event_reinit(current_base) == -1) {
-			fprintf(stderr, "FAILED (reinit)\n");
-			exit(1);
-		}
-
-		signal_del(&sig_ev);
-
-		called = 0;
-
-		event_dispatch();
-
-		/* we do not send an EOF; simple_read_cb requires an EOF 
-		 * to set test_ok.  we just verify that the callback was
-		 * called. */
-		exit(test_ok != 0 || called != 2 ? -2 : 76);
-	}
-
-	/* wait for the child to read the data */
-	sleep(1);
-
-	write(pair[0], TEST1, strlen(TEST1)+1);
-
-	if (waitpid(pid, &status, 0) == -1) {
-		fprintf(stderr, "FAILED (fork)\n");
-		exit(1);
-	}
-	
-	if (WEXITSTATUS(status) != 76) {
-		fprintf(stderr, "FAILED (exit): %d\n", WEXITSTATUS(status));
-		exit(1);
-	}
-
-	/* test that the current event loop still works */
-	write(pair[0], TEST1, strlen(TEST1)+1);
-	shutdown(pair[0], SHUT_WR);
-
-	event_dispatch();
-
-	if (!got_sigchld) {
-		fprintf(stdout, "FAILED (sigchld)\n");
-		exit(1);
-	}
-
-	signal_del(&sig_ev);
-
-	cleanup_test();
-}
-
-static void
-test_simplesignal(void)
-{
-	struct event ev;
-	struct itimerval itv;
-
-	setup_test("Simple signal: ");
-	signal_set(&ev, SIGALRM, signal_cb, &ev);
-	signal_add(&ev, NULL);
-	/* find bugs in which operations are re-ordered */
-	signal_del(&ev);
-	signal_add(&ev, NULL);
-
-	memset(&itv, 0, sizeof(itv));
-	itv.it_value.tv_sec = 1;
-	if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
-		goto skip_simplesignal;
-
-	event_dispatch();
- skip_simplesignal:
-	if (signal_del(&ev) == -1)
-		test_ok = 0;
-
-	cleanup_test();
-}
-
-static void
-test_multiplesignal(void)
-{
-	struct event ev_one, ev_two;
-	struct itimerval itv;
-
-	setup_test("Multiple signal: ");
-
-	signal_set(&ev_one, SIGALRM, signal_cb, &ev_one);
-	signal_add(&ev_one, NULL);
-
-	signal_set(&ev_two, SIGALRM, signal_cb, &ev_two);
-	signal_add(&ev_two, NULL);
-
-	memset(&itv, 0, sizeof(itv));
-	itv.it_value.tv_sec = 1;
-	if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
-		goto skip_simplesignal;
-
-	event_dispatch();
-
- skip_simplesignal:
-	if (signal_del(&ev_one) == -1)
-		test_ok = 0;
-	if (signal_del(&ev_two) == -1)
-		test_ok = 0;
-
-	cleanup_test();
-}
-
-static void
-test_immediatesignal(void)
-{
-	struct event ev;
-
-	test_ok = 0;
-	printf("Immediate signal: ");
-	signal_set(&ev, SIGUSR1, signal_cb, &ev);
-	signal_add(&ev, NULL);
-	raise(SIGUSR1);
-	event_loop(EVLOOP_NONBLOCK);
-	signal_del(&ev);
-	cleanup_test();
-}
-
-static void
-test_signal_dealloc(void)
-{
-	/* make sure that signal_event is event_del'ed and pipe closed */
-	struct event ev;
-	struct event_base *base = event_init();
-	printf("Signal dealloc: ");
-	signal_set(&ev, SIGUSR1, signal_cb, &ev);
-	signal_add(&ev, NULL);
-	signal_del(&ev);
-	event_base_free(base);
-        /* If we got here without asserting, we're fine. */
-        test_ok = 1;
-	cleanup_test();
-}
-
-static void
-test_signal_pipeloss(void)
-{
-	/* make sure that the base1 pipe is closed correctly. */
-	struct event_base *base1, *base2;
-	int pipe1;
-	test_ok = 0;
-	printf("Signal pipeloss: ");
-	base1 = event_init();
-	pipe1 = base1->sig.ev_signal_pair[0];
-	base2 = event_init();
-	event_base_free(base2);
-	event_base_free(base1);
-	if (close(pipe1) != -1 || errno!=EBADF) {
-		/* fd must be closed, so second close gives -1, EBADF */
-		printf("signal pipe not closed. ");
-		test_ok = 0;
-	} else {
-		test_ok = 1;
-	}
-	cleanup_test();
-}
-
-/*
- * make two bases to catch signals, use both of them.  this only works
- * for event mechanisms that use our signal pipe trick.  kqueue handles
- * signals internally, and all interested kqueues get all the signals.
- */
-static void
-test_signal_switchbase(void)
-{
-	struct event ev1, ev2;
-	struct event_base *base1, *base2;
-        int is_kqueue;
-	test_ok = 0;
-	printf("Signal switchbase: ");
-	base1 = event_init();
-	base2 = event_init();
-        is_kqueue = !strcmp(event_get_method(),"kqueue");
-	signal_set(&ev1, SIGUSR1, signal_cb, &ev1);
-	signal_set(&ev2, SIGUSR1, signal_cb, &ev2);
-	if (event_base_set(base1, &ev1) ||
-	    event_base_set(base2, &ev2) ||
-	    event_add(&ev1, NULL) ||
-	    event_add(&ev2, NULL)) {
-		fprintf(stderr, "%s: cannot set base, add\n", __func__);
-		exit(1);
-	}
-
-	test_ok = 0;
-	/* can handle signal before loop is called */
-	raise(SIGUSR1);
-	event_base_loop(base2, EVLOOP_NONBLOCK);
-        if (is_kqueue) {
-                if (!test_ok)
-                        goto done;
-                test_ok = 0;
-        }
-	event_base_loop(base1, EVLOOP_NONBLOCK);
-	if (test_ok && !is_kqueue) {
-		test_ok = 0;
-
-		/* set base1 to handle signals */
-		event_base_loop(base1, EVLOOP_NONBLOCK);
-		raise(SIGUSR1);
-		event_base_loop(base1, EVLOOP_NONBLOCK);
-		event_base_loop(base2, EVLOOP_NONBLOCK);
-	}
- done:
-	event_base_free(base1);
-	event_base_free(base2);
-	cleanup_test();
-}
-
-/*
- * assert that a signal event removed from the event queue really is
- * removed - with no possibility of it's parent handler being fired.
- */
-static void
-test_signal_assert(void)
-{
-	struct event ev;
-	struct event_base *base = event_init();
-	test_ok = 0;
-	printf("Signal handler assert: ");
-	/* use SIGCONT so we don't kill ourselves when we signal to nowhere */
-	signal_set(&ev, SIGCONT, signal_cb, &ev);
-	signal_add(&ev, NULL);
-	/*
-	 * if signal_del() fails to reset the handler, it's current handler
-	 * will still point to evsignal_handler().
-	 */
-	signal_del(&ev);
-
-	raise(SIGCONT);
-	/* only way to verify we were in evsignal_handler() */
-	if (base->sig.evsignal_caught)
-		test_ok = 0;
-	else
-		test_ok = 1;
-
-	event_base_free(base);
-	cleanup_test();
-	return;
-}
-
-/*
- * assert that we restore our previous signal handler properly.
- */
-static void
-test_signal_restore(void)
-{
-	struct event ev;
-	struct event_base *base = event_init();
-#ifdef HAVE_SIGACTION
-	struct sigaction sa;
-#endif
-
-	test_ok = 0;
-	printf("Signal handler restore: ");
-#ifdef HAVE_SIGACTION
-	sa.sa_handler = signal_cb_sa;
-	sa.sa_flags = 0x0;
-	sigemptyset(&sa.sa_mask);
-	if (sigaction(SIGUSR1, &sa, NULL) == -1)
-		goto out;
-#else
-	if (signal(SIGUSR1, signal_cb_sa) == SIG_ERR)
-		goto out;
-#endif
-	signal_set(&ev, SIGUSR1, signal_cb, &ev);
-	signal_add(&ev, NULL);
-	signal_del(&ev);
-
-	raise(SIGUSR1);
-	/* 1 == signal_cb, 2 == signal_cb_sa, we want our previous handler */
-	if (test_ok != 2)
-		test_ok = 0;
-out:
-	event_base_free(base);
-	cleanup_test();
-	return;
-}
-
-static void
-signal_cb_swp(int sig, short event, void *arg)
-{
-	called++;
-	if (called < 5)
-		raise(sig);
-	else
-		event_loopexit(NULL);
-}
-static void
-timeout_cb_swp(int fd, short event, void *arg)
-{
-	if (called == -1) {
-		struct timeval tv = {5, 0};
-
-		called = 0;
-		evtimer_add((struct event *)arg, &tv);
-		raise(SIGUSR1);
-		return;
-	}
-	test_ok = 0;
-	event_loopexit(NULL);
-}
-
-static void
-test_signal_while_processing(void)
-{
-	struct event_base *base = event_init();
-	struct event ev, ev_timer;
-	struct timeval tv = {0, 0};
-
-	setup_test("Receiving a signal while processing other signal: ");
-
-	called = -1;
-	test_ok = 1;
-	signal_set(&ev, SIGUSR1, signal_cb_swp, NULL);
-	signal_add(&ev, NULL);
-	evtimer_set(&ev_timer, timeout_cb_swp, &ev_timer);
-	evtimer_add(&ev_timer, &tv);
-	event_dispatch();
-
-	event_base_free(base);
-	cleanup_test();
-	return;
-}
-#endif
-
-static void
-test_free_active_base(void)
-{
-	struct event_base *base1;
-	struct event ev1;
-	setup_test("Free active base: ");
-	base1 = event_init();
-	event_set(&ev1, pair[1], EV_READ, simple_read_cb, &ev1);
-	event_base_set(base1, &ev1);
-	event_add(&ev1, NULL);
-	/* event_del(&ev1); */
-	event_base_free(base1);
-	test_ok = 1;
-	cleanup_test();
-}
-
-static void
-test_event_base_new(void)
-{
-	struct event_base *base;
-	struct event ev1;
-	setup_test("Event base new: ");
-
-	write(pair[0], TEST1, strlen(TEST1)+1);
-	shutdown(pair[0], SHUT_WR);
-
-	base = event_base_new();
-	event_set(&ev1, pair[1], EV_READ, simple_read_cb, &ev1);
-	event_base_set(base, &ev1);
-	event_add(&ev1, NULL);
-
-	event_base_dispatch(base);
-
-	event_base_free(base);
-	test_ok = 1;
-	cleanup_test();
-}
-
-static void
-test_loopexit(void)
-{
-	struct timeval tv, tv_start, tv_end;
-	struct event ev;
-
-	setup_test("Loop exit: ");
-
-	tv.tv_usec = 0;
-	tv.tv_sec = 60*60*24;
-	evtimer_set(&ev, timeout_cb, NULL);
-	evtimer_add(&ev, &tv);
-
-	tv.tv_usec = 0;
-	tv.tv_sec = 1;
-	event_loopexit(&tv);
-
-	evutil_gettimeofday(&tv_start, NULL);
-	event_dispatch();
-	evutil_gettimeofday(&tv_end, NULL);
-	evutil_timersub(&tv_end, &tv_start, &tv_end);
-
-	evtimer_del(&ev);
-
-	if (tv.tv_sec < 2)
-		test_ok = 1;
-
-	cleanup_test();
-}
-
-static void
-test_loopexit_multiple(void)
-{
-	struct timeval tv;
-	struct event_base *base;
-
-	setup_test("Loop Multiple exit: ");
-
-	base = event_base_new();
-	
-	tv.tv_usec = 0;
-	tv.tv_sec = 1;
-	event_base_loopexit(base, &tv);
-
-	tv.tv_usec = 0;
-	tv.tv_sec = 2;
-	event_base_loopexit(base, &tv);
-
-	event_base_dispatch(base);
-
-	event_base_free(base);
-	
-	test_ok = 1;
-
-	cleanup_test();
-}
-
-static void
-break_cb(int fd, short events, void *arg)
-{
-	test_ok = 1;
-	event_loopbreak();
-}
-
-static void
-fail_cb(int fd, short events, void *arg)
-{
-	test_ok = 0;
-}
-
-static void
-test_loopbreak(void)
-{
-	struct event ev1, ev2;
-	struct timeval tv;
-
-	setup_test("Loop break: ");
-
-	tv.tv_sec = 0;
-	tv.tv_usec = 0;
-	evtimer_set(&ev1, break_cb, NULL);
-	evtimer_add(&ev1, &tv);
-	evtimer_set(&ev2, fail_cb, NULL);
-	evtimer_add(&ev2, &tv);
-
-	event_dispatch();
-
-	evtimer_del(&ev1);
-	evtimer_del(&ev2);
-
-	cleanup_test();
-}
-
-static void
-test_evbuffer(void) {
-
-	struct evbuffer *evb = evbuffer_new();
-	setup_test("Testing Evbuffer: ");
-
-	evbuffer_add_printf(evb, "%s/%d", "hello", 1);
-
-	if (EVBUFFER_LENGTH(evb) == 7 &&
-	    strcmp((char*)EVBUFFER_DATA(evb), "hello/1") == 0)
-	    test_ok = 1;
-	
-	evbuffer_free(evb);
-
-	cleanup_test();
-}
-
-static void
-test_evbuffer_readln(void)
-{
-	struct evbuffer *evb = evbuffer_new();
-	struct evbuffer *evb_tmp = evbuffer_new();
-	const char *s;
-	char *cp = NULL;
-	size_t sz;
-
-#define tt_line_eq(content)						\
-	if (!cp || sz != strlen(content) || strcmp(cp, content)) {	\
-		fprintf(stdout, "FAILED\n");				\
-		exit(1);						\
-	}
-#define tt_assert(expression)						\
-	if (!(expression)) {						\
-		fprintf(stdout, "FAILED\n");				\
-		exit(1);						\
-	}								\
-
-	/* Test EOL_ANY. */
-	fprintf(stdout, "Testing evbuffer_readln EOL_ANY: ");
-
-	s = "complex silly newline\r\n\n\r\n\n\rmore\0\n";
-	evbuffer_add(evb, s, strlen(s)+2);
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_ANY);
-	tt_line_eq("complex silly newline");
-	free(cp);
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_ANY);
-	if (!cp || sz != 5 || memcmp(cp, "more\0\0", 6)) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-	if (evb->totallen == 0) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-	s = "\nno newline";
-	evbuffer_add(evb, s, strlen(s));
-	free(cp);
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_ANY);
-	tt_line_eq("");
-	free(cp);
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_ANY);
-        tt_assert(!cp);
-	evbuffer_drain(evb, EVBUFFER_LENGTH(evb));
-        tt_assert(EVBUFFER_LENGTH(evb) == 0);
-
-	fprintf(stdout, "OK\n");
-
-	/* Test EOL_CRLF */
-	fprintf(stdout, "Testing evbuffer_readln EOL_CRLF: ");
-
-	s = "Line with\rin the middle\nLine with good crlf\r\n\nfinal\n";
-	evbuffer_add(evb, s, strlen(s));
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
-	tt_line_eq("Line with\rin the middle");
-	free(cp);
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
-	tt_line_eq("Line with good crlf");
-	free(cp);
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
-	tt_line_eq("");
-	free(cp);
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
-	tt_line_eq("final");
-	s = "x";
-	evbuffer_add(evb, s, 1);
-	free(cp);
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
-        tt_assert(!cp);
-
-	fprintf(stdout, "OK\n");
-
-	/* Test CRLF_STRICT */
-	fprintf(stdout, "Testing evbuffer_readln CRLF_STRICT: ");
-
-	s = " and a bad crlf\nand a good one\r\n\r\nMore\r";
-	evbuffer_add(evb, s, strlen(s));
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
-	tt_line_eq("x and a bad crlf\nand a good one");
-	free(cp);
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
-	tt_line_eq("");
-	free(cp);
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
-        tt_assert(!cp);
-	evbuffer_add(evb, "\n", 1);
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
-	tt_line_eq("More");
-	free(cp);
-	tt_assert(EVBUFFER_LENGTH(evb) == 0);
-
-	s = "An internal CR\r is not an eol\r\nNor is a lack of one";
-	evbuffer_add(evb, s, strlen(s));
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
-	tt_line_eq("An internal CR\r is not an eol");
-	free(cp);
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
-	tt_assert(!cp);
-
-	evbuffer_add(evb, "\r\n", 2);
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
-	tt_line_eq("Nor is a lack of one");
-	free(cp);
-	tt_assert(EVBUFFER_LENGTH(evb) == 0);
-
-	fprintf(stdout, "OK\n");
-
-	/* Test LF */
-	fprintf(stdout, "Testing evbuffer_readln LF: ");
-
-	s = "An\rand a nl\n\nText";
-	evbuffer_add(evb, s, strlen(s));
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
-	tt_line_eq("An\rand a nl");
-	free(cp);
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
-	tt_line_eq("");
-	free(cp);
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
-	tt_assert(!cp);
-	free(cp);
-	evbuffer_add(evb, "\n", 1);
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
-	tt_line_eq("Text");
-	free(cp);
-
-	fprintf(stdout, "OK\n");
-
-	/* Test CRLF_STRICT - across boundaries */
-	fprintf(stdout,
-	    "Testing evbuffer_readln CRLF_STRICT across boundaries: ");
-
-	s = " and a bad crlf\nand a good one\r";
-	evbuffer_add(evb_tmp, s, strlen(s));
-	evbuffer_add_buffer(evb, evb_tmp);
-	s = "\n\r";
-	evbuffer_add(evb_tmp, s, strlen(s));
-	evbuffer_add_buffer(evb, evb_tmp);
-	s = "\nMore\r";
-	evbuffer_add(evb_tmp, s, strlen(s));
-	evbuffer_add_buffer(evb, evb_tmp);
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
-	tt_line_eq(" and a bad crlf\nand a good one");
-	free(cp);
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
-	tt_line_eq("");
-	free(cp);
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
-	tt_assert(!cp);
-	free(cp);
-	evbuffer_add(evb, "\n", 1);
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
-	tt_line_eq("More");
-	free(cp); cp = NULL;
-	if (EVBUFFER_LENGTH(evb) != 0) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	fprintf(stdout, "OK\n");
-
-	/* Test memory problem */
-	fprintf(stdout, "Testing evbuffer_readln memory problem: ");
-
-	s = "one line\ntwo line\nblue line";
-	evbuffer_add(evb_tmp, s, strlen(s));
-	evbuffer_add_buffer(evb, evb_tmp);
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
-	tt_line_eq("one line");
-	free(cp); cp = NULL;
-
-	cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
-	tt_line_eq("two line");
-	free(cp); cp = NULL;
-
-	fprintf(stdout, "OK\n");
-
-	test_ok = 1;
-	evbuffer_free(evb);
-	evbuffer_free(evb_tmp);
-	if (cp) free(cp);
-}
-
-static void
-test_evbuffer_find(void)
-{
-	u_char* p;
-	const char* test1 = "1234567890\r\n";
-	const char* test2 = "1234567890\r";
-#define EVBUFFER_INITIAL_LENGTH 256
-	char test3[EVBUFFER_INITIAL_LENGTH];
-	unsigned int i;
-	struct evbuffer * buf = evbuffer_new();
-
-	/* make sure evbuffer_find doesn't match past the end of the buffer */
-	fprintf(stdout, "Testing evbuffer_find 1: ");
-	evbuffer_add(buf, (u_char*)test1, strlen(test1));
-	evbuffer_drain(buf, strlen(test1));	  
-	evbuffer_add(buf, (u_char*)test2, strlen(test2));
-	p = evbuffer_find(buf, (u_char*)"\r\n", 2);
-	if (p == NULL) {
-		fprintf(stdout, "OK\n");
-	} else {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/*
-	 * drain the buffer and do another find; in r309 this would
-	 * read past the allocated buffer causing a valgrind error.
-	 */
-	fprintf(stdout, "Testing evbuffer_find 2: ");
-	evbuffer_drain(buf, strlen(test2));
-	for (i = 0; i < EVBUFFER_INITIAL_LENGTH; ++i)
-		test3[i] = 'a';
-	test3[EVBUFFER_INITIAL_LENGTH - 1] = 'x';
-	evbuffer_add(buf, (u_char *)test3, EVBUFFER_INITIAL_LENGTH);
-	p = evbuffer_find(buf, (u_char *)"xy", 2);
-	if (p == NULL) {
-		printf("OK\n");
-	} else {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/* simple test for match at end of allocated buffer */
-	fprintf(stdout, "Testing evbuffer_find 3: ");
-	p = evbuffer_find(buf, (u_char *)"ax", 2);
-	if (p != NULL && strncmp((char*)p, "ax", 2) == 0) {
-		printf("OK\n");
-	} else {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	evbuffer_free(buf);
-}
-
-/*
- * simple bufferevent test
- */
-
-static void
-readcb(struct bufferevent *bev, void *arg)
-{
-	if (EVBUFFER_LENGTH(bev->input) == 8333) {
-		bufferevent_disable(bev, EV_READ);
-		test_ok++;
-	}
-}
-
-static void
-writecb(struct bufferevent *bev, void *arg)
-{
-	if (EVBUFFER_LENGTH(bev->output) == 0)
-		test_ok++;
-}
-
-static void
-errorcb(struct bufferevent *bev, short what, void *arg)
-{
-	test_ok = -2;
-}
-
-static void
-test_bufferevent(void)
-{
-	struct bufferevent *bev1, *bev2;
-	char buffer[8333];
-	int i;
-
-	setup_test("Bufferevent: ");
-
-	bev1 = bufferevent_new(pair[0], readcb, writecb, errorcb, NULL);
-	bev2 = bufferevent_new(pair[1], readcb, writecb, errorcb, NULL);
-
-	bufferevent_disable(bev1, EV_READ);
-	bufferevent_enable(bev2, EV_READ);
-
-	for (i = 0; i < sizeof(buffer); i++)
-		buffer[i] = i;
-
-	bufferevent_write(bev1, buffer, sizeof(buffer));
-
-	event_dispatch();
-
-	bufferevent_free(bev1);
-	bufferevent_free(bev2);
-
-	if (test_ok != 2)
-		test_ok = 0;
-
-	cleanup_test();
-}
-
-/*
- * test watermarks and bufferevent
- */
-
-static void
-wm_readcb(struct bufferevent *bev, void *arg)
-{
-	int len = EVBUFFER_LENGTH(bev->input);
-	static int nread;
-
-	assert(len >= 10 && len <= 20);
-
-	evbuffer_drain(bev->input, len);
-
-	nread += len;
-	if (nread == 65000) {
-		bufferevent_disable(bev, EV_READ);
-		test_ok++;
-	}
-}
-
-static void
-wm_writecb(struct bufferevent *bev, void *arg)
-{
-	if (EVBUFFER_LENGTH(bev->output) == 0)
-		test_ok++;
-}
-
-static void
-wm_errorcb(struct bufferevent *bev, short what, void *arg)
-{
-	test_ok = -2;
-}
-
-static void
-test_bufferevent_watermarks(void)
-{
-	struct bufferevent *bev1, *bev2;
-	char buffer[65000];
-	int i;
-
-	setup_test("Bufferevent Watermarks: ");
-
-	bev1 = bufferevent_new(pair[0], NULL, wm_writecb, wm_errorcb, NULL);
-	bev2 = bufferevent_new(pair[1], wm_readcb, NULL, wm_errorcb, NULL);
-
-	bufferevent_disable(bev1, EV_READ);
-	bufferevent_enable(bev2, EV_READ);
-
-	for (i = 0; i < sizeof(buffer); i++)
-		buffer[i] = i;
-
-	bufferevent_write(bev1, buffer, sizeof(buffer));
-
-	/* limit the reading on the receiving bufferevent */
-	bufferevent_setwatermark(bev2, EV_READ, 10, 20);
-
-	event_dispatch();
-
-	bufferevent_free(bev1);
-	bufferevent_free(bev2);
-
-	if (test_ok != 2)
-		test_ok = 0;
-
-	cleanup_test();
-}
-
-struct test_pri_event {
-	struct event ev;
-	int count;
-};
-
-static void
-test_priorities_cb(int fd, short what, void *arg)
-{
-	struct test_pri_event *pri = arg;
-	struct timeval tv;
-
-	if (pri->count == 3) {
-		event_loopexit(NULL);
-		return;
-	}
-
-	pri->count++;
-
-	evutil_timerclear(&tv);
-	event_add(&pri->ev, &tv);
-}
-
-static void
-test_priorities(int npriorities)
-{
-	char buf[32];
-	struct test_pri_event one, two;
-	struct timeval tv;
-
-	evutil_snprintf(buf, sizeof(buf), "Testing Priorities %d: ", npriorities);
-	setup_test(buf);
-
-	event_base_priority_init(global_base, npriorities);
-
-	memset(&one, 0, sizeof(one));
-	memset(&two, 0, sizeof(two));
-
-	timeout_set(&one.ev, test_priorities_cb, &one);
-	if (event_priority_set(&one.ev, 0) == -1) {
-		fprintf(stderr, "%s: failed to set priority", __func__);
-		exit(1);
-	}
-
-	timeout_set(&two.ev, test_priorities_cb, &two);
-	if (event_priority_set(&two.ev, npriorities - 1) == -1) {
-		fprintf(stderr, "%s: failed to set priority", __func__);
-		exit(1);
-	}
-
-	evutil_timerclear(&tv);
-
-	if (event_add(&one.ev, &tv) == -1)
-		exit(1);
-	if (event_add(&two.ev, &tv) == -1)
-		exit(1);
-
-	event_dispatch();
-
-	event_del(&one.ev);
-	event_del(&two.ev);
-
-	if (npriorities == 1) {
-		if (one.count == 3 && two.count == 3)
-			test_ok = 1;
-	} else if (npriorities == 2) {
-		/* Two is called once because event_loopexit is priority 1 */
-		if (one.count == 3 && two.count == 1)
-			test_ok = 1;
-	} else {
-		if (one.count == 3 && two.count == 0)
-			test_ok = 1;
-	}
-
-	cleanup_test();
-}
-
-static void
-test_multiple_cb(int fd, short event, void *arg)
-{
-	if (event & EV_READ)
-		test_ok |= 1;
-	else if (event & EV_WRITE)
-		test_ok |= 2;
-}
-
-static void
-test_multiple_events_for_same_fd(void)
-{
-   struct event e1, e2;
-
-   setup_test("Multiple events for same fd: ");
-
-   event_set(&e1, pair[0], EV_READ, test_multiple_cb, NULL);
-   event_add(&e1, NULL);
-   event_set(&e2, pair[0], EV_WRITE, test_multiple_cb, NULL);
-   event_add(&e2, NULL);
-   event_loop(EVLOOP_ONCE);
-   event_del(&e2);
-   write(pair[1], TEST1, strlen(TEST1)+1);
-   event_loop(EVLOOP_ONCE);
-   event_del(&e1);
-   
-   if (test_ok != 3)
-	   test_ok = 0;
-
-   cleanup_test();
-}
-
-int evtag_decode_int(uint32_t *pnumber, struct evbuffer *evbuf);
-int evtag_encode_tag(struct evbuffer *evbuf, uint32_t number);
-int evtag_decode_tag(uint32_t *pnumber, struct evbuffer *evbuf);
-
-static void
-read_once_cb(int fd, short event, void *arg)
-{
-	char buf[256];
-	int len;
-
-	len = read(fd, buf, sizeof(buf));
-
-	if (called) {
-		test_ok = 0;
-	} else if (len) {
-		/* Assumes global pair[0] can be used for writing */
-		write(pair[0], TEST1, strlen(TEST1)+1);
-		test_ok = 1;
-	}
-
-	called++;
-}
-
-static void
-test_want_only_once(void)
-{
-	struct event ev;
-	struct timeval tv;
-
-	/* Very simple read test */
-	setup_test("Want read only once: ");
-	
-	write(pair[0], TEST1, strlen(TEST1)+1);
-
-	/* Setup the loop termination */
-	evutil_timerclear(&tv);
-	tv.tv_sec = 1;
-	event_loopexit(&tv);
-	
-	event_set(&ev, pair[1], EV_READ, read_once_cb, &ev);
-	if (event_add(&ev, NULL) == -1)
-		exit(1);
-	event_dispatch();
-
-	cleanup_test();
-}
-
-#define TEST_MAX_INT	6
-
-static void
-evtag_int_test(void)
-{
-	struct evbuffer *tmp = evbuffer_new();
-	uint32_t integers[TEST_MAX_INT] = {
-		0xaf0, 0x1000, 0x1, 0xdeadbeef, 0x00, 0xbef000
-	};
-	uint32_t integer;
-	int i;
-
-	for (i = 0; i < TEST_MAX_INT; i++) {
-		int oldlen, newlen;
-		oldlen = EVBUFFER_LENGTH(tmp);
-		encode_int(tmp, integers[i]);
-		newlen = EVBUFFER_LENGTH(tmp);
-		fprintf(stdout, "\t\tencoded 0x%08x with %d bytes\n",
-		    integers[i], newlen - oldlen);
-	}
-
-	for (i = 0; i < TEST_MAX_INT; i++) {
-		if (evtag_decode_int(&integer, tmp) == -1) {
-			fprintf(stderr, "decode %d failed", i);
-			exit(1);
-		}
-		if (integer != integers[i]) {
-			fprintf(stderr, "got %x, wanted %x",
-			    integer, integers[i]);
-			exit(1);
-		}
-	}
-
-	if (EVBUFFER_LENGTH(tmp) != 0) {
-		fprintf(stderr, "trailing data");
-		exit(1);
-	}
-	evbuffer_free(tmp);
-
-	fprintf(stdout, "\t%s: OK\n", __func__);
-}
-
-static void
-evtag_fuzz(void)
-{
-	u_char buffer[4096];
-	struct evbuffer *tmp = evbuffer_new();
-	struct timeval tv;
-	int i, j;
-
-	int not_failed = 0;
-	for (j = 0; j < 100; j++) {
-		for (i = 0; i < sizeof(buffer); i++)
-			buffer[i] = rand();
-		evbuffer_drain(tmp, -1);
-		evbuffer_add(tmp, buffer, sizeof(buffer));
-
-		if (evtag_unmarshal_timeval(tmp, 0, &tv) != -1)
-			not_failed++;
-	}
-
-	/* The majority of decodes should fail */
-	if (not_failed >= 10) {
-		fprintf(stderr, "evtag_unmarshal should have failed");
-		exit(1);
-	}
-
-	/* Now insert some corruption into the tag length field */
-	evbuffer_drain(tmp, -1);
-	evutil_timerclear(&tv);
-	tv.tv_sec = 1;
-	evtag_marshal_timeval(tmp, 0, &tv);
-	evbuffer_add(tmp, buffer, sizeof(buffer));
-
-	EVBUFFER_DATA(tmp)[1] = 0xff;
-	if (evtag_unmarshal_timeval(tmp, 0, &tv) != -1) {
-		fprintf(stderr, "evtag_unmarshal_timeval should have failed");
-		exit(1);
-	}
-
-	evbuffer_free(tmp);
-
-	fprintf(stdout, "\t%s: OK\n", __func__);
-}
-
-static void
-evtag_tag_encoding(void)
-{
-	struct evbuffer *tmp = evbuffer_new();
-	uint32_t integers[TEST_MAX_INT] = {
-		0xaf0, 0x1000, 0x1, 0xdeadbeef, 0x00, 0xbef000
-	};
-	uint32_t integer;
-	int i;
-
-	for (i = 0; i < TEST_MAX_INT; i++) {
-		int oldlen, newlen;
-		oldlen = EVBUFFER_LENGTH(tmp);
-		evtag_encode_tag(tmp, integers[i]);
-		newlen = EVBUFFER_LENGTH(tmp);
-		fprintf(stdout, "\t\tencoded 0x%08x with %d bytes\n",
-		    integers[i], newlen - oldlen);
-	}
-
-	for (i = 0; i < TEST_MAX_INT; i++) {
-		if (evtag_decode_tag(&integer, tmp) == -1) {
-			fprintf(stderr, "decode %d failed", i);
-			exit(1);
-		}
-		if (integer != integers[i]) {
-			fprintf(stderr, "got %x, wanted %x",
-			    integer, integers[i]);
-			exit(1);
-		}
-	}
-
-	if (EVBUFFER_LENGTH(tmp) != 0) {
-		fprintf(stderr, "trailing data");
-		exit(1);
-	}
-	evbuffer_free(tmp);
-
-	fprintf(stdout, "\t%s: OK\n", __func__);
-}
-
-static void
-evtag_test(void)
-{
-	fprintf(stdout, "Testing Tagging:\n");
-
-	evtag_init();
-	evtag_int_test();
-	evtag_fuzz();
-
-	evtag_tag_encoding();
-
-	fprintf(stdout, "OK\n");
-}
-
-#ifndef WIN32
-static void
-rpc_test(void)
-{
-	struct msg *msg, *msg2;
-	struct kill *attack;
-	struct run *run;
-	struct evbuffer *tmp = evbuffer_new();
-	struct timeval tv_start, tv_end;
-	uint32_t tag;
-	int i;
-
-	fprintf(stdout, "Testing RPC: ");
-
-	msg = msg_new();
-	EVTAG_ASSIGN(msg, from_name, "niels");
-	EVTAG_ASSIGN(msg, to_name, "phoenix");
-
-	if (EVTAG_GET(msg, attack, &attack) == -1) {
-		fprintf(stderr, "Failed to set kill message.\n");
-		exit(1);
-	}
-
-	EVTAG_ASSIGN(attack, weapon, "feather");
-	EVTAG_ASSIGN(attack, action, "tickle");
-
-	evutil_gettimeofday(&tv_start, NULL);
-	for (i = 0; i < 1000; ++i) {
-		run = EVTAG_ADD(msg, run);
-		if (run == NULL) {
-			fprintf(stderr, "Failed to add run message.\n");
-			exit(1);
-		}
-		EVTAG_ASSIGN(run, how, "very fast but with some data in it");
-		EVTAG_ASSIGN(run, fixed_bytes,
-		    (unsigned char*)"012345678901234567890123");
-	}
-
-	if (msg_complete(msg) == -1) {
-		fprintf(stderr, "Failed to make complete message.\n");
-		exit(1);
-	}
-
-	evtag_marshal_msg(tmp, 0xdeaf, msg);
-
-	if (evtag_peek(tmp, &tag) == -1) {
-		fprintf(stderr, "Failed to peak tag.\n");
-		exit (1);
-	}
-
-	if (tag != 0xdeaf) {
-		fprintf(stderr, "Got incorrect tag: %0x.\n", tag);
-		exit (1);
-	}
-
-	msg2 = msg_new();
-	if (evtag_unmarshal_msg(tmp, 0xdeaf, msg2) == -1) {
-		fprintf(stderr, "Failed to unmarshal message.\n");
-		exit(1);
-	}
-
-	evutil_gettimeofday(&tv_end, NULL);
-	evutil_timersub(&tv_end, &tv_start, &tv_end);
-	fprintf(stderr, "(%.1f us/add) ",
-	    (float)tv_end.tv_sec/(float)i * 1000000.0 +
-	    tv_end.tv_usec / (float)i);
-
-	if (!EVTAG_HAS(msg2, from_name) ||
-	    !EVTAG_HAS(msg2, to_name) ||
-	    !EVTAG_HAS(msg2, attack)) {
-		fprintf(stderr, "Missing data structures.\n");
-		exit(1);
-	}
-
-	if (EVTAG_LEN(msg2, run) != i) {
-		fprintf(stderr, "Wrong number of run messages.\n");
-		exit(1);
-	}
-
-	msg_free(msg);
-	msg_free(msg2);
-
-	evbuffer_free(tmp);
-
-	fprintf(stdout, "OK\n");
-}
-#endif
-
-static void
-test_evutil_strtoll(void)
-{
-        const char *s;
-        char *endptr;
-        setup_test("evutil_stroll: ");
-        test_ok = 0;
-
-        if (evutil_strtoll("5000000000", NULL, 10) != ((ev_int64_t)5000000)*1000)
-                goto err;
-        if (evutil_strtoll("-5000000000", NULL, 10) != ((ev_int64_t)5000000)*-1000)
-                goto err;
-        s = " 99999stuff";
-        if (evutil_strtoll(s, &endptr, 10) != (ev_int64_t)99999)
-                goto err;
-        if (endptr != s+6)
-                goto err;
-        if (evutil_strtoll("foo", NULL, 10) != 0)
-                goto err;
-
-        test_ok = 1;
- err:
-        cleanup_test();
-}
-
-
-int
-main (int argc, char **argv)
-{
-#ifdef WIN32
-	WORD wVersionRequested;
-	WSADATA wsaData;
-	int	err;
-
-	wVersionRequested = MAKEWORD( 2, 2 );
-
-	err = WSAStartup( wVersionRequested, &wsaData );
-#endif
-
-#ifndef WIN32
-	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
-		return (1);
-#endif
-	setvbuf(stdout, NULL, _IONBF, 0);
-
-	/* Initalize the event library */
-	global_base = event_init();
-
-	test_registerfds();
-
-        test_evutil_strtoll();
-
-	/* use the global event base and need to be called first */
-	test_priorities(1);
-	test_priorities(2);
-	test_priorities(3);
-
-	test_evbuffer();
-	test_evbuffer_find();
-	test_evbuffer_readln();
-	
-	test_bufferevent();
-	test_bufferevent_watermarks();
-
-	test_free_active_base();
-
-	test_event_base_new();
-
-	http_suite();
-
-#ifndef WIN32
-	rpc_suite();
-#endif
-
-	dns_suite();
-	
-#ifndef WIN32
-	test_fork();
-#endif
-
-	test_simpleread();
-
-	test_simplewrite();
-
-	test_multiple();
-
-	test_persistent();
-
-	test_combined();
-
-	test_simpletimeout();
-#ifndef WIN32
-	test_simplesignal();
-	test_multiplesignal();
-	test_immediatesignal();
-#endif
-	test_loopexit();
-	test_loopbreak();
-
-	test_loopexit_multiple();
-	
-	test_multiple_events_for_same_fd();
-
-	test_want_only_once();
-
-	evtag_test();
-
-#ifndef WIN32
-	rpc_test();
-
-	test_signal_dealloc();
-	test_signal_pipeloss();
-	test_signal_switchbase();
-	test_signal_restore();
-	test_signal_assert();
-	test_signal_while_processing();
-#endif
-	
-	return (0);
-}
-
diff --git a/base/third_party/libevent/test/regress.h b/base/third_party/libevent/test/regress.h
deleted file mode 100644
index 4060ff5..0000000
--- a/base/third_party/libevent/test/regress.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2000-2004 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef _REGRESS_H_
-#define _REGRESS_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-void http_suite(void);
-void http_basic_test(void);
-
-void rpc_suite(void);
-
-void dns_suite(void);
-	
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _REGRESS_H_ */
diff --git a/base/third_party/libevent/test/regress.rpc b/base/third_party/libevent/test/regress.rpc
deleted file mode 100644
index 65ca95d..0000000
--- a/base/third_party/libevent/test/regress.rpc
+++ /dev/null
@@ -1,20 +0,0 @@
-/* tests data packing and unpacking */
-
-struct msg {
-	string from_name = 1;
-	string to_name = 2;
-	optional struct[kill] attack = 3;
-	array struct[run] run = 4;
-}
-
-struct kill {
-	string weapon = 0x10121;
-	string action = 2;
-	optional int how_often = 3;
-}
-
-struct run {
-	string how = 1;
-	optional bytes some_bytes = 2;
-	bytes fixed_bytes[24] = 3;
-}
diff --git a/base/third_party/libevent/test/regress_dns.c b/base/third_party/libevent/test/regress_dns.c
deleted file mode 100644
index 129cdad..0000000
--- a/base/third_party/libevent/test/regress_dns.c
+++ /dev/null
@@ -1,376 +0,0 @@
-/*
- * Copyright (c) 2003-2006 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef WIN32
-#include <winsock2.h>
-#include <windows.h>
-#endif
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#include <sys/queue.h>
-#ifndef WIN32
-#include <sys/socket.h>
-#include <signal.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <unistd.h>
-#endif
-#ifdef HAVE_NETINET_IN6_H
-#include <netinet/in6.h>
-#endif
-#ifdef HAVE_NETDB_H
-#include <netdb.h>
-#endif
-#include <fcntl.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-
-#include "event.h"
-#include "evdns.h"
-#include "log.h"
-
-static int dns_ok = 0;
-static int dns_err = 0;
-
-void dns_suite(void);
-
-static void
-dns_gethostbyname_cb(int result, char type, int count, int ttl,
-    void *addresses, void *arg)
-{
-	dns_ok = dns_err = 0;
-
-	if (result == DNS_ERR_TIMEOUT) {
-		fprintf(stdout, "[Timed out] ");
-		dns_err = result;
-		goto out;
-	}
-
-	if (result != DNS_ERR_NONE) {
-		fprintf(stdout, "[Error code %d] ", result);
-		goto out;
-	}
-
-	fprintf(stderr, "type: %d, count: %d, ttl: %d: ", type, count, ttl);
-
-	switch (type) {
-	case DNS_IPv6_AAAA: {
-#if defined(HAVE_STRUCT_IN6_ADDR) && defined(HAVE_INET_NTOP) && defined(INET6_ADDRSTRLEN)
-		struct in6_addr *in6_addrs = addresses;
-		char buf[INET6_ADDRSTRLEN+1];
-		int i;
-		/* a resolution that's not valid does not help */
-		if (ttl < 0)
-			goto out;
-		for (i = 0; i < count; ++i) {
-			const char *b = inet_ntop(AF_INET6, &in6_addrs[i], buf,sizeof(buf));
-			if (b)
-				fprintf(stderr, "%s ", b);
-			else
-				fprintf(stderr, "%s ", strerror(errno));
-		}
-#endif
-		break;
-	}
-	case DNS_IPv4_A: {
-		struct in_addr *in_addrs = addresses;
-		int i;
-		/* a resolution that's not valid does not help */
-		if (ttl < 0)
-			goto out;
-		for (i = 0; i < count; ++i)
-			fprintf(stderr, "%s ", inet_ntoa(in_addrs[i]));
-		break;
-	}
-	case DNS_PTR:
-		/* may get at most one PTR */
-		if (count != 1)
-			goto out;
-
-		fprintf(stderr, "%s ", *(char **)addresses);
-		break;
-	default:
-		goto out;
-	}
-
-	dns_ok = type;
-
-out:
-	event_loopexit(NULL);
-}
-
-static void
-dns_gethostbyname(void)
-{
-	fprintf(stdout, "Simple DNS resolve: ");
-	dns_ok = 0;
-	evdns_resolve_ipv4("www.monkey.org", 0, dns_gethostbyname_cb, NULL);
-	event_dispatch();
-
-	if (dns_ok == DNS_IPv4_A) {
-		fprintf(stdout, "OK\n");
-	} else {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-}
-
-static void
-dns_gethostbyname6(void)
-{
-	fprintf(stdout, "IPv6 DNS resolve: ");
-	dns_ok = 0;
-	evdns_resolve_ipv6("www.ietf.org", 0, dns_gethostbyname_cb, NULL);
-	event_dispatch();
-
-	if (dns_ok == DNS_IPv6_AAAA) {
-		fprintf(stdout, "OK\n");
-	} else if (!dns_ok && dns_err == DNS_ERR_TIMEOUT) {
-		fprintf(stdout, "SKIPPED\n");
-	} else {
-		fprintf(stdout, "FAILED (%d)\n", dns_ok);
-		exit(1);
-	}
-}
-
-static void
-dns_gethostbyaddr(void)
-{
-	struct in_addr in;
-	in.s_addr = htonl(0x7f000001ul); /* 127.0.0.1 */
-	fprintf(stdout, "Simple reverse DNS resolve: ");
-	dns_ok = 0;
-	evdns_resolve_reverse(&in, 0, dns_gethostbyname_cb, NULL);
-	event_dispatch();
-
-	if (dns_ok == DNS_PTR) {
-		fprintf(stdout, "OK\n");
-	} else {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-}
-
-static int n_server_responses = 0;
-
-static void
-dns_server_request_cb(struct evdns_server_request *req, void *data)
-{
-	int i, r;
-	const char TEST_ARPA[] = "11.11.168.192.in-addr.arpa";
-	for (i = 0; i < req->nquestions; ++i) {
-		struct in_addr ans;
-		ans.s_addr = htonl(0xc0a80b0bUL); /* 192.168.11.11 */
-		if (req->questions[i]->type == EVDNS_TYPE_A &&
-			req->questions[i]->dns_question_class == EVDNS_CLASS_INET &&
-			!strcmp(req->questions[i]->name, "zz.example.com")) {
-			r = evdns_server_request_add_a_reply(req, "zz.example.com",
-												 1, &ans.s_addr, 12345);
-			if (r<0)
-				dns_ok = 0;
-		} else if (req->questions[i]->type == EVDNS_TYPE_AAAA &&
-				   req->questions[i]->dns_question_class == EVDNS_CLASS_INET &&
-				   !strcmp(req->questions[i]->name, "zz.example.com")) {
-			char addr6[17] = "abcdefghijklmnop";
-			r = evdns_server_request_add_aaaa_reply(req, "zz.example.com",
-												 1, addr6, 123);
-			if (r<0)
-				dns_ok = 0;
-		} else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
-				   req->questions[i]->dns_question_class == EVDNS_CLASS_INET &&
-				   !strcmp(req->questions[i]->name, TEST_ARPA)) {
-			r = evdns_server_request_add_ptr_reply(req, NULL, TEST_ARPA,
-					   "ZZ.EXAMPLE.COM", 54321);
-			if (r<0)
-				dns_ok = 0;
-		} else {
-			fprintf(stdout, "Unexpected question %d %d \"%s\" ",
-					req->questions[i]->type,
-					req->questions[i]->dns_question_class,
-					req->questions[i]->name);
-			dns_ok = 0;
-		}
-	}
-	r = evdns_server_request_respond(req, 0);
-	if (r<0) {
-		fprintf(stdout, "Couldn't send reply. ");
-		dns_ok = 0;
-	}
-}
-
-static void
-dns_server_gethostbyname_cb(int result, char type, int count, int ttl,
-							void *addresses, void *arg)
-{
-	if (result != DNS_ERR_NONE) {
-		fprintf(stdout, "Unexpected result %d. ", result);
-		dns_ok = 0;
-		goto out;
-	}
-	if (count != 1) {
-		fprintf(stdout, "Unexpected answer count %d. ", count);
-		dns_ok = 0;
-		goto out;
-	}
-	switch (type) {
-	case DNS_IPv4_A: {
-		struct in_addr *in_addrs = addresses;
-		if (in_addrs[0].s_addr != htonl(0xc0a80b0bUL) || ttl != 12345) {
-			fprintf(stdout, "Bad IPv4 response \"%s\" %d. ",
-					inet_ntoa(in_addrs[0]), ttl);
-			dns_ok = 0;
-			goto out;
-		}
-		break;
-	}
-	case DNS_IPv6_AAAA: {
-#if defined (HAVE_STRUCT_IN6_ADDR) && defined(HAVE_INET_NTOP) && defined(INET6_ADDRSTRLEN)
-		struct in6_addr *in6_addrs = addresses;
-		char buf[INET6_ADDRSTRLEN+1];
-		if (memcmp(&in6_addrs[0].s6_addr, "abcdefghijklmnop", 16)
-			|| ttl != 123) {
-			const char *b = inet_ntop(AF_INET6, &in6_addrs[0],buf,sizeof(buf));
-			fprintf(stdout, "Bad IPv6 response \"%s\" %d. ", b, ttl);
-			dns_ok = 0;
-			goto out;
-		}
-#endif
-		break;
-	}
-	case DNS_PTR: {
-		char **addrs = addresses;
-		if (strcmp(addrs[0], "ZZ.EXAMPLE.COM") || ttl != 54321) {
-			fprintf(stdout, "Bad PTR response \"%s\" %d. ",
-					addrs[0], ttl);
-			dns_ok = 0;
-			goto out;
-		}
-		break;
-	}
-	default:
-		fprintf(stdout, "Bad response type %d. ", type);
-		dns_ok = 0;
-	}
-
- out:
-	if (++n_server_responses == 3) {
-		event_loopexit(NULL);
-	}
-}
-
-static void
-dns_server(void)
-{
-	int sock;
-	struct sockaddr_in my_addr;
-	struct evdns_server_port *port;
-	struct in_addr resolve_addr;
-
-	dns_ok = 1;
-	fprintf(stdout, "DNS server support: ");
-
-	/* Add ourself as the only nameserver, and make sure we really are
-	 * the only nameserver. */
-	evdns_nameserver_ip_add("127.0.0.1:35353");
-	if (evdns_count_nameservers() != 1) {
-		fprintf(stdout, "Couldn't set up.\n");
-		exit(1);
-	}
-
-	/* Now configure a nameserver port. */
-	sock = socket(AF_INET, SOCK_DGRAM, 0);
-	if (sock == -1) {
-		perror("socket");
-		exit(1);
-	}
-#ifdef WIN32
-	{
-		u_long nonblocking = 1;
-		ioctlsocket(sock, FIONBIO, &nonblocking);
-	}
-#else
-	fcntl(sock, F_SETFL, O_NONBLOCK);
-#endif
-	memset(&my_addr, 0, sizeof(my_addr));
-	my_addr.sin_family = AF_INET;
-	my_addr.sin_port = htons(35353);
-	my_addr.sin_addr.s_addr = htonl(0x7f000001UL);
-	if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr)) < 0) {
-		perror("bind");
-		exit (1);
-	}
-	port = evdns_add_server_port(sock, 0, dns_server_request_cb, NULL);
-
-	/* Send two queries. */
-	evdns_resolve_ipv4("zz.example.com", DNS_QUERY_NO_SEARCH,
-					   dns_server_gethostbyname_cb, NULL);
-	evdns_resolve_ipv6("zz.example.com", DNS_QUERY_NO_SEARCH,
-					   dns_server_gethostbyname_cb, NULL);
-	resolve_addr.s_addr = htonl(0xc0a80b0bUL); /* 192.168.11.11 */
-	evdns_resolve_reverse(&resolve_addr, 0,
-						  dns_server_gethostbyname_cb, NULL);
-
-	event_dispatch();
-
-	if (dns_ok) {
-		fprintf(stdout, "OK\n");
-	} else {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	evdns_close_server_port(port);
-	evdns_shutdown(0); /* remove ourself as nameserver. */
-#ifdef WIN32
-	closesocket(sock);
-#else
-	close(sock);
-#endif
-}
-
-void
-dns_suite(void)
-{
-	dns_server(); /* Do this before we call evdns_init. */
-
-	evdns_init();
-	dns_gethostbyname();
-	dns_gethostbyname6();
-	dns_gethostbyaddr();
-
-	evdns_shutdown(0);
-}
diff --git a/base/third_party/libevent/test/regress_http.c b/base/third_party/libevent/test/regress_http.c
deleted file mode 100644
index 943b29d..0000000
--- a/base/third_party/libevent/test/regress_http.c
+++ /dev/null
@@ -1,1744 +0,0 @@
-/*
- * Copyright (c) 2003-2006 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef WIN32
-#include <winsock2.h>
-#include <windows.h>
-#endif
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#include <sys/queue.h>
-#ifndef WIN32
-#include <sys/socket.h>
-#include <signal.h>
-#include <unistd.h>
-#include <netdb.h>
-#endif
-#include <fcntl.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-
-#include "event.h"
-#include "evhttp.h"
-#include "log.h"
-#include "http-internal.h"
-
-extern int pair[];
-extern int test_ok;
-
-static struct evhttp *http;
-/* set if a test needs to call loopexit on a base */
-static struct event_base *base;
-
-void http_suite(void);
-
-void http_basic_cb(struct evhttp_request *req, void *arg);
-static void http_chunked_cb(struct evhttp_request *req, void *arg);
-void http_post_cb(struct evhttp_request *req, void *arg);
-void http_dispatcher_cb(struct evhttp_request *req, void *arg);
-static void http_large_delay_cb(struct evhttp_request *req, void *arg);
-static void http_badreq_cb(struct evhttp_request *req, void *arg);
-
-static struct evhttp *
-http_setup(short *pport, struct event_base *base)
-{
-	int i;
-	struct evhttp *myhttp;
-	short port = -1;
-
-	/* Try a few different ports */
-	myhttp = evhttp_new(base);
-	for (i = 0; i < 50; ++i) {
-		if (evhttp_bind_socket(myhttp, "127.0.0.1", 8080 + i) != -1) {
-			port = 8080 + i;
-			break;
-		}
-	}
-
-	if (port == -1)
-		event_errx(1, "Could not start web server");
-
-	/* Register a callback for certain types of requests */
-	evhttp_set_cb(myhttp, "/test", http_basic_cb, NULL);
-	evhttp_set_cb(myhttp, "/chunked", http_chunked_cb, NULL);
-	evhttp_set_cb(myhttp, "/postit", http_post_cb, NULL);
-	evhttp_set_cb(myhttp, "/largedelay", http_large_delay_cb, NULL);
-	evhttp_set_cb(myhttp, "/badrequest", http_badreq_cb, NULL);
-	evhttp_set_cb(myhttp, "/", http_dispatcher_cb, NULL);
-
-	*pport = port;
-	return (myhttp);
-}
-
-#ifndef NI_MAXSERV
-#define NI_MAXSERV 1024
-#endif
-
-static int
-http_connect(const char *address, u_short port)
-{
-	/* Stupid code for connecting */
-#ifdef WIN32
-	struct hostent *he;
-	struct sockaddr_in sin;
-#else
-	struct addrinfo ai, *aitop;
-	char strport[NI_MAXSERV];
-#endif
-	struct sockaddr *sa;
-	int slen;
-	int fd;
-	
-#ifdef WIN32
-	if (!(he = gethostbyname(address))) {
-		event_warn("gethostbyname");
-	}
-	memcpy(&sin.sin_addr, he->h_addr_list[0], he->h_length);
-	sin.sin_family = AF_INET;
-	sin.sin_port = htons(port);
-	slen = sizeof(struct sockaddr_in);
-	sa = (struct sockaddr*)&sin;
-#else
-	memset(&ai, 0, sizeof (ai));
-	ai.ai_family = AF_INET;
-	ai.ai_socktype = SOCK_STREAM;
-	snprintf(strport, sizeof (strport), "%d", port);
-	if (getaddrinfo(address, strport, &ai, &aitop) != 0) {
-		event_warn("getaddrinfo");
-		return (-1);
-	}
-	sa = aitop->ai_addr;
-	slen = aitop->ai_addrlen;
-#endif
-        
-	fd = socket(AF_INET, SOCK_STREAM, 0);
-	if (fd == -1)
-		event_err(1, "socket failed");
-
-	if (connect(fd, sa, slen) == -1)
-		event_err(1, "connect failed");
-
-#ifndef WIN32
-	freeaddrinfo(aitop);
-#endif
-
-	return (fd);
-}
-
-static void
-http_readcb(struct bufferevent *bev, void *arg)
-{
-	const char *what = "This is funny";
-
- 	event_debug(("%s: %s\n", __func__, EVBUFFER_DATA(bev->input)));
-	
-	if (evbuffer_find(bev->input,
-		(const unsigned char*) what, strlen(what)) != NULL) {
-		struct evhttp_request *req = evhttp_request_new(NULL, NULL);
-		enum message_read_status done;
-
-		req->kind = EVHTTP_RESPONSE;
-		done = evhttp_parse_firstline(req, bev->input);
-		if (done != ALL_DATA_READ)
-			goto out;
-
-		done = evhttp_parse_headers(req, bev->input);
-		if (done != ALL_DATA_READ)
-			goto out;
-
-		if (done == 1 &&
-		    evhttp_find_header(req->input_headers,
-			"Content-Type") != NULL)
-			test_ok++;
-
-	out:
-		evhttp_request_free(req);
-		bufferevent_disable(bev, EV_READ);
-		if (base)
-			event_base_loopexit(base, NULL);
-		else
-			event_loopexit(NULL);
-	}
-}
-
-static void
-http_writecb(struct bufferevent *bev, void *arg)
-{
-	if (EVBUFFER_LENGTH(bev->output) == 0) {
-		/* enable reading of the reply */
-		bufferevent_enable(bev, EV_READ);
-		test_ok++;
-	}
-}
-
-static void
-http_errorcb(struct bufferevent *bev, short what, void *arg)
-{
-	test_ok = -2;
-	event_loopexit(NULL);
-}
-
-void
-http_basic_cb(struct evhttp_request *req, void *arg)
-{
-	struct evbuffer *evb = evbuffer_new();
-	int empty = evhttp_find_header(req->input_headers, "Empty") != NULL;
-	event_debug(("%s: called\n", __func__));
-	evbuffer_add_printf(evb, "This is funny");
-	
-	/* For multi-line headers test */
-	{
-		const char *multi =
-		    evhttp_find_header(req->input_headers,"X-multi");
-		if (multi) {
-			if (strcmp("END", multi + strlen(multi) - 3) == 0)
-				test_ok++;
-			if (evhttp_find_header(req->input_headers, "X-Last"))
-				test_ok++;
-		}
-	}
-
-	/* injecting a bad content-length */
-	if (evhttp_find_header(req->input_headers, "X-Negative"))
-		evhttp_add_header(req->output_headers,
-		    "Content-Length", "-100");
-
-	/* allow sending of an empty reply */
-	evhttp_send_reply(req, HTTP_OK, "Everything is fine",
-	    !empty ? evb : NULL);
-
-	evbuffer_free(evb);
-}
-
-static char const* const CHUNKS[] = {
-	"This is funny",
-	"but not hilarious.",
-	"bwv 1052"
-};
-
-struct chunk_req_state {
-	struct evhttp_request *req;
-	int i;
-};
-
-static void
-http_chunked_trickle_cb(int fd, short events, void *arg)
-{
-	struct evbuffer *evb = evbuffer_new();
-	struct chunk_req_state *state = arg;
-	struct timeval when = { 0, 0 };
-
-	evbuffer_add_printf(evb, "%s", CHUNKS[state->i]);
-	evhttp_send_reply_chunk(state->req, evb);
-	evbuffer_free(evb);
-
-	if (++state->i < sizeof(CHUNKS)/sizeof(CHUNKS[0])) {
-		event_once(-1, EV_TIMEOUT,
-		    http_chunked_trickle_cb, state, &when);
-	} else {
-		evhttp_send_reply_end(state->req);
-		free(state);
-	}
-}
-
-static void
-http_chunked_cb(struct evhttp_request *req, void *arg)
-{
-	struct timeval when = { 0, 0 };
-	struct chunk_req_state *state = malloc(sizeof(struct chunk_req_state));
-	event_debug(("%s: called\n", __func__));
-
-	memset(state, 0, sizeof(struct chunk_req_state));
-	state->req = req;
-
-	/* generate a chunked reply */
-	evhttp_send_reply_start(req, HTTP_OK, "Everything is fine");
-
-	/* but trickle it across several iterations to ensure we're not
-	 * assuming it comes all at once */
-	event_once(-1, EV_TIMEOUT, http_chunked_trickle_cb, state, &when);
-}
-
-static void
-http_complete_write(int fd, short what, void *arg)
-{
-	struct bufferevent *bev = arg;
-	const char *http_request = "host\r\n"
-	    "Connection: close\r\n"
-	    "\r\n";
-	bufferevent_write(bev, http_request, strlen(http_request));
-}
-
-static void
-http_basic_test(void)
-{
-	struct timeval tv;
-	struct bufferevent *bev;
-	int fd;
-	const char *http_request;
-	short port = -1;
-
-	test_ok = 0;
-	fprintf(stdout, "Testing Basic HTTP Server: ");
-
-	http = http_setup(&port, NULL);
-
-	/* bind to a second socket */
-	if (evhttp_bind_socket(http, "127.0.0.1", port + 1) == -1) {
-		fprintf(stdout, "FAILED (bind)\n");
-		exit(1);
-	}
-	
-	fd = http_connect("127.0.0.1", port);
-
-	/* Stupid thing to send a request */
-	bev = bufferevent_new(fd, http_readcb, http_writecb,
-	    http_errorcb, NULL);
-
-	/* first half of the http request */
-	http_request =
-	    "GET /test HTTP/1.1\r\n"
-	    "Host: some";
-
-	bufferevent_write(bev, http_request, strlen(http_request));
-	timerclear(&tv);
-	tv.tv_usec = 10000;
-	event_once(-1, EV_TIMEOUT, http_complete_write, bev, &tv);
-	
-	event_dispatch();
-
-	if (test_ok != 3) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/* connect to the second port */
-	bufferevent_free(bev);
-	EVUTIL_CLOSESOCKET(fd);
-
-	fd = http_connect("127.0.0.1", port + 1);
-
-	/* Stupid thing to send a request */
-	bev = bufferevent_new(fd, http_readcb, http_writecb,
-	    http_errorcb, NULL);
-
-	http_request =
-	    "GET /test HTTP/1.1\r\n"
-	    "Host: somehost\r\n"
-	    "Connection: close\r\n"
-	    "\r\n";
-
-	bufferevent_write(bev, http_request, strlen(http_request));
-	
-	event_dispatch();
-
-	bufferevent_free(bev);
-	EVUTIL_CLOSESOCKET(fd);
-
-	evhttp_free(http);
-	
-	if (test_ok != 5) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	fprintf(stdout, "OK\n");
-}
-
-static void
-http_badreq_cb(struct evhttp_request *req, void *arg)
-{
-	struct evbuffer *buf = evbuffer_new();
-
-	evhttp_add_header(req->output_headers, "Content-Type", "text/xml; charset=UTF-8");
-	evbuffer_add_printf(buf, "Hello, %s!", "127.0.0.1");
-
-	evhttp_send_reply(req, HTTP_OK, "OK", buf);
-	evbuffer_free(buf);
-}
-
-static void
-http_badreq_errorcb(struct bufferevent *bev, short what, void *arg)
-{
-	event_debug(("%s: called (what=%04x, arg=%p)", __func__, what, arg));
-	/* ignore */
-}
-
-static void
-http_badreq_readcb(struct bufferevent *bev, void *arg)
-{
-	const char *what = "Hello, 127.0.0.1";
-	const char *bad_request = "400 Bad Request";
-
-	event_debug(("%s: %s\n", __func__, EVBUFFER_DATA(bev->input)));
-
-	if (evbuffer_find(bev->input,
-		(const unsigned char *) bad_request, strlen(bad_request)) != NULL) {
-		event_debug(("%s: bad request detected", __func__));
-		test_ok = -10;
-		bufferevent_disable(bev, EV_READ);
-		event_loopexit(NULL);
-		return;
-	}
-
-	if (evbuffer_find(bev->input,
-		(const unsigned char*) what, strlen(what)) != NULL) {
-		struct evhttp_request *req = evhttp_request_new(NULL, NULL);
-		enum message_read_status done;
-
-		req->kind = EVHTTP_RESPONSE;
-		done = evhttp_parse_firstline(req, bev->input);
-		if (done != ALL_DATA_READ)
-			goto out;
-
-		done = evhttp_parse_headers(req, bev->input);
-		if (done != ALL_DATA_READ)
-			goto out;
-
-		if (done == 1 &&
-		    evhttp_find_header(req->input_headers,
-			"Content-Type") != NULL)
-			test_ok++;
-
-	out:
-		evhttp_request_free(req);
-		evbuffer_drain(bev->input, EVBUFFER_LENGTH(bev->input));
-	}
-
-	shutdown(bev->ev_read.ev_fd, SHUT_WR);
-}
-
-static void
-http_badreq_successcb(int fd, short what, void *arg)
-{
-	event_debug(("%s: called (what=%04x, arg=%p)", __func__, what, arg));
-	event_loopexit(NULL);
-}
-
-static void
-http_bad_request(void)
-{
-	struct timeval tv;
-	struct bufferevent *bev;
-	int fd;
-	const char *http_request;
-	short port = -1;
-
-	test_ok = 0;
-	fprintf(stdout, "Testing \"Bad Request\" on connection close: ");
-
-	http = http_setup(&port, NULL);
-
-	/* bind to a second socket */
-	if (evhttp_bind_socket(http, "127.0.0.1", port + 1) == -1) {
-		fprintf(stdout, "FAILED (bind)\n");
-		exit(1);
-	}
-
-	/* NULL request test */
-	fd = http_connect("127.0.0.1", port);
-
-	/* Stupid thing to send a request */
-	bev = bufferevent_new(fd, http_badreq_readcb, http_writecb,
-	    http_badreq_errorcb, NULL);
-	bufferevent_enable(bev, EV_READ);
-
-	/* real NULL request */
-	http_request = "";
-
-	shutdown(fd, SHUT_WR);
-	timerclear(&tv);
-	tv.tv_usec = 10000;
-	event_once(-1, EV_TIMEOUT, http_badreq_successcb, bev, &tv);
-
-	event_dispatch();
-
-	bufferevent_free(bev);
-	EVUTIL_CLOSESOCKET(fd);
-
-	if (test_ok != 0) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/* Second answer (BAD REQUEST) on connection close */
-
-	/* connect to the second port */
-	fd = http_connect("127.0.0.1", port + 1);
-
-	/* Stupid thing to send a request */
-	bev = bufferevent_new(fd, http_badreq_readcb, http_writecb,
-	    http_badreq_errorcb, NULL);
-	bufferevent_enable(bev, EV_READ);
-
-	/* first half of the http request */
-	http_request =
-		"GET /badrequest HTTP/1.0\r\n"	\
-		"Connection: Keep-Alive\r\n"	\
-		"\r\n";
-
-	bufferevent_write(bev, http_request, strlen(http_request));
-
-	timerclear(&tv);
-	tv.tv_usec = 10000;
-	event_once(-1, EV_TIMEOUT, http_badreq_successcb, bev, &tv);
-
-	event_dispatch();
-
-	evhttp_free(http);
-
-	if (test_ok != 2) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	fprintf(stdout, "OK\n");
-}
-static struct evhttp_connection *delayed_client;
-
-static void
-http_delay_reply(int fd, short what, void *arg)
-{
-	struct evhttp_request *req = arg;
-
-	evhttp_send_reply(req, HTTP_OK, "Everything is fine", NULL);
-
-	++test_ok;
-}
-
-static void
-http_large_delay_cb(struct evhttp_request *req, void *arg)
-{
-	struct timeval tv;
-	timerclear(&tv);
-	tv.tv_sec = 3;
-
-	event_once(-1, EV_TIMEOUT, http_delay_reply, req, &tv);
-
-	/* here we close the client connection which will cause an EOF */
-	evhttp_connection_fail(delayed_client, EVCON_HTTP_EOF);
-}
-
-void http_request_done(struct evhttp_request *, void *);
-void http_request_empty_done(struct evhttp_request *, void *);
-
-static void
-http_connection_test(int persistent)
-{
-	short port = -1;
-	struct evhttp_connection *evcon = NULL;
-	struct evhttp_request *req = NULL;
-	
-	test_ok = 0;
-	fprintf(stdout, "Testing Request Connection Pipeline %s: ",
-	    persistent ? "(persistent)" : "");
-
-	http = http_setup(&port, NULL);
-
-	evcon = evhttp_connection_new("127.0.0.1", port);
-	if (evcon == NULL) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/*
-	 * At this point, we want to schedule a request to the HTTP
-	 * server using our make request method.
-	 */
-
-	req = evhttp_request_new(http_request_done, NULL);
-
-	/* Add the information that we care about */
-	evhttp_add_header(req->output_headers, "Host", "somehost");
-
-	/* We give ownership of the request to the connection */
-	if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	event_dispatch();
-
-	if (test_ok != 1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/* try to make another request over the same connection */
-	test_ok = 0;
-	
-	req = evhttp_request_new(http_request_done, NULL);
-
-	/* Add the information that we care about */
-	evhttp_add_header(req->output_headers, "Host", "somehost");
-
-	/* 
-	 * if our connections are not supposed to be persistent; request
-	 * a close from the server.
-	 */
-	if (!persistent)
-		evhttp_add_header(req->output_headers, "Connection", "close");
-
-	/* We give ownership of the request to the connection */
-	if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	event_dispatch();
-
-	/* make another request: request empty reply */
-	test_ok = 0;
-	
-	req = evhttp_request_new(http_request_empty_done, NULL);
-
-	/* Add the information that we care about */
-	evhttp_add_header(req->output_headers, "Empty", "itis");
-
-	/* We give ownership of the request to the connection */
-	if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	event_dispatch();
-
-	if (test_ok != 1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	evhttp_connection_free(evcon);
-	evhttp_free(http);
-	
-	fprintf(stdout, "OK\n");
-}
-
-void
-http_request_done(struct evhttp_request *req, void *arg)
-{
-	const char *what = "This is funny";
-
-	if (req->response_code != HTTP_OK) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	if (evhttp_find_header(req->input_headers, "Content-Type") == NULL) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	if (EVBUFFER_LENGTH(req->input_buffer) != strlen(what)) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-	
-	if (memcmp(EVBUFFER_DATA(req->input_buffer), what, strlen(what)) != 0) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	test_ok = 1;
-	event_loopexit(NULL);
-}
-
-/* test date header and content length */
-
-void
-http_request_empty_done(struct evhttp_request *req, void *arg)
-{
-	if (req->response_code != HTTP_OK) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	if (evhttp_find_header(req->input_headers, "Date") == NULL) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	
-	if (evhttp_find_header(req->input_headers, "Content-Length") == NULL) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	if (strcmp(evhttp_find_header(req->input_headers, "Content-Length"),
-		"0")) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	if (EVBUFFER_LENGTH(req->input_buffer) != 0) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	test_ok = 1;
-	event_loopexit(NULL);
-}
-
-/*
- * HTTP DISPATCHER test
- */
-
-void
-http_dispatcher_cb(struct evhttp_request *req, void *arg)
-{
-
-	struct evbuffer *evb = evbuffer_new();
-	event_debug(("%s: called\n", __func__));
-	evbuffer_add_printf(evb, "DISPATCHER_TEST");
-
-	evhttp_send_reply(req, HTTP_OK, "Everything is fine", evb);
-
-	evbuffer_free(evb);
-}
-
-static void
-http_dispatcher_test_done(struct evhttp_request *req, void *arg)
-{
-	const char *what = "DISPATCHER_TEST";
-
-	if (req->response_code != HTTP_OK) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	if (evhttp_find_header(req->input_headers, "Content-Type") == NULL) {
-		fprintf(stderr, "FAILED (content type)\n");
-		exit(1);
-	}
-
-	if (EVBUFFER_LENGTH(req->input_buffer) != strlen(what)) {
-		fprintf(stderr, "FAILED (length %zu vs %zu)\n",
-		    EVBUFFER_LENGTH(req->input_buffer), strlen(what));
-		exit(1);
-	}
-	
-	if (memcmp(EVBUFFER_DATA(req->input_buffer), what, strlen(what)) != 0) {
-		fprintf(stderr, "FAILED (data)\n");
-		exit(1);
-	}
-
-	test_ok = 1;
-	event_loopexit(NULL);
-}
-
-static void
-http_dispatcher_test(void)
-{
-	short port = -1;
-	struct evhttp_connection *evcon = NULL;
-	struct evhttp_request *req = NULL;
-
-	test_ok = 0;
-	fprintf(stdout, "Testing HTTP Dispatcher: ");
-
-	http = http_setup(&port, NULL);
-
-	evcon = evhttp_connection_new("127.0.0.1", port);
-	if (evcon == NULL) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/* also bind to local host */
-	evhttp_connection_set_local_address(evcon, "127.0.0.1");
-
-	/*
-	 * At this point, we want to schedule an HTTP GET request
-	 * server using our make request method.
-	 */
-
-	req = evhttp_request_new(http_dispatcher_test_done, NULL);
-	if (req == NULL) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/* Add the information that we care about */
-	evhttp_add_header(req->output_headers, "Host", "somehost");
-	
-	if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/?arg=val") == -1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	event_dispatch();
-
-	evhttp_connection_free(evcon);
-	evhttp_free(http);
-	
-	if (test_ok != 1) {
-		fprintf(stdout, "FAILED: %d\n", test_ok);
-		exit(1);
-	}
-	
-	fprintf(stdout, "OK\n");
-}
-
-/*
- * HTTP POST test.
- */
-
-void http_postrequest_done(struct evhttp_request *, void *);
-
-#define POST_DATA "Okay.  Not really printf"
-
-static void
-http_post_test(void)
-{
-	short port = -1;
-	struct evhttp_connection *evcon = NULL;
-	struct evhttp_request *req = NULL;
-
-	test_ok = 0;
-	fprintf(stdout, "Testing HTTP POST Request: ");
-
-	http = http_setup(&port, NULL);
-
-	evcon = evhttp_connection_new("127.0.0.1", port);
-	if (evcon == NULL) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/*
-	 * At this point, we want to schedule an HTTP POST request
-	 * server using our make request method.
-	 */
-
-	req = evhttp_request_new(http_postrequest_done, NULL);
-	if (req == NULL) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/* Add the information that we care about */
-	evhttp_add_header(req->output_headers, "Host", "somehost");
-	evbuffer_add_printf(req->output_buffer, POST_DATA);
-	
-	if (evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/postit") == -1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	event_dispatch();
-
-	evhttp_connection_free(evcon);
-	evhttp_free(http);
-	
-	if (test_ok != 1) {
-		fprintf(stdout, "FAILED: %d\n", test_ok);
-		exit(1);
-	}
-	
-	fprintf(stdout, "OK\n");
-}
-
-void
-http_post_cb(struct evhttp_request *req, void *arg)
-{
-	struct evbuffer *evb;
-	event_debug(("%s: called\n", __func__));
-
-	/* Yes, we are expecting a post request */
-	if (req->type != EVHTTP_REQ_POST) {
-		fprintf(stdout, "FAILED (post type)\n");
-		exit(1);
-	}
-
-	if (EVBUFFER_LENGTH(req->input_buffer) != strlen(POST_DATA)) {
-		fprintf(stdout, "FAILED (length: %zu vs %zu)\n",
-		    EVBUFFER_LENGTH(req->input_buffer), strlen(POST_DATA));
-		exit(1);
-	}
-
-	if (memcmp(EVBUFFER_DATA(req->input_buffer), POST_DATA,
-		strlen(POST_DATA))) {
-		fprintf(stdout, "FAILED (data)\n");
-		fprintf(stdout, "Got :%s\n", EVBUFFER_DATA(req->input_buffer));
-		fprintf(stdout, "Want:%s\n", POST_DATA);
-		exit(1);
-	}
-	
-	evb = evbuffer_new();
-	evbuffer_add_printf(evb, "This is funny");
-
-	evhttp_send_reply(req, HTTP_OK, "Everything is fine", evb);
-
-	evbuffer_free(evb);
-}
-
-void
-http_postrequest_done(struct evhttp_request *req, void *arg)
-{
-	const char *what = "This is funny";
-
-	if (req == NULL) {
-		fprintf(stderr, "FAILED (timeout)\n");
-		exit(1);
-	}
-
-	if (req->response_code != HTTP_OK) {
-	
-		fprintf(stderr, "FAILED (response code)\n");
-		exit(1);
-	}
-
-	if (evhttp_find_header(req->input_headers, "Content-Type") == NULL) {
-		fprintf(stderr, "FAILED (content type)\n");
-		exit(1);
-	}
-
-	if (EVBUFFER_LENGTH(req->input_buffer) != strlen(what)) {
-		fprintf(stderr, "FAILED (length %zu vs %zu)\n",
-		    EVBUFFER_LENGTH(req->input_buffer), strlen(what));
-		exit(1);
-	}
-	
-	if (memcmp(EVBUFFER_DATA(req->input_buffer), what, strlen(what)) != 0) {
-		fprintf(stderr, "FAILED (data)\n");
-		exit(1);
-	}
-
-	test_ok = 1;
-	event_loopexit(NULL);
-}
-
-static void
-http_failure_readcb(struct bufferevent *bev, void *arg)
-{
-	const char *what = "400 Bad Request";
-	if (evbuffer_find(bev->input, (const unsigned char*) what, strlen(what)) != NULL) {
-		test_ok = 2;
-		bufferevent_disable(bev, EV_READ);
-		event_loopexit(NULL);
-	}
-}
-
-/*
- * Testing that the HTTP server can deal with a malformed request.
- */
-static void
-http_failure_test(void)
-{
-	struct bufferevent *bev;
-	int fd;
-	const char *http_request;
-	short port = -1;
-
-	test_ok = 0;
-	fprintf(stdout, "Testing Bad HTTP Request: ");
-
-	http = http_setup(&port, NULL);
-	
-	fd = http_connect("127.0.0.1", port);
-
-	/* Stupid thing to send a request */
-	bev = bufferevent_new(fd, http_failure_readcb, http_writecb,
-	    http_errorcb, NULL);
-
-	http_request = "illegal request\r\n";
-
-	bufferevent_write(bev, http_request, strlen(http_request));
-	
-	event_dispatch();
-
-	bufferevent_free(bev);
-	EVUTIL_CLOSESOCKET(fd);
-
-	evhttp_free(http);
-	
-	if (test_ok != 2) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-	
-	fprintf(stdout, "OK\n");
-}
-
-static void
-close_detect_done(struct evhttp_request *req, void *arg)
-{
-	struct timeval tv;
-	if (req == NULL || req->response_code != HTTP_OK) {
-	
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	test_ok = 1;
-
-	timerclear(&tv);
-	tv.tv_sec = 3;   /* longer than the http time out */
-
-	event_loopexit(&tv);
-}
-
-static void
-close_detect_launch(int fd, short what, void *arg)
-{
-	struct evhttp_connection *evcon = arg;
-	struct evhttp_request *req;
-
-	req = evhttp_request_new(close_detect_done, NULL);
-
-	/* Add the information that we care about */
-	evhttp_add_header(req->output_headers, "Host", "somehost");
-
-	/* We give ownership of the request to the connection */
-	if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-}
-
-static void
-close_detect_cb(struct evhttp_request *req, void *arg)
-{
-	struct evhttp_connection *evcon = arg;
-	struct timeval tv;
-
-	if (req != NULL && req->response_code != HTTP_OK) {
-	
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	timerclear(&tv);
-	tv.tv_sec = 3;   /* longer than the http time out */
-
-	/* launch a new request on the persistent connection in 6 seconds */
-	event_once(-1, EV_TIMEOUT, close_detect_launch, evcon, &tv);
-}
-
-
-static void
-http_close_detection(int with_delay)
-{
-	short port = -1;
-	struct evhttp_connection *evcon = NULL;
-	struct evhttp_request *req = NULL;
-	
-	test_ok = 0;
-	fprintf(stdout, "Testing Connection Close Detection%s: ",
-		with_delay ? " (with delay)" : "");
-
-	http = http_setup(&port, NULL);
-
-	/* 2 second timeout */
-	evhttp_set_timeout(http, 2);
-
-	evcon = evhttp_connection_new("127.0.0.1", port);
-	if (evcon == NULL) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	delayed_client = evcon;
-
-	/*
-	 * At this point, we want to schedule a request to the HTTP
-	 * server using our make request method.
-	 */
-
-	req = evhttp_request_new(close_detect_cb, evcon);
-
-	/* Add the information that we care about */
-	evhttp_add_header(req->output_headers, "Host", "somehost");
-
-	/* We give ownership of the request to the connection */
-	if (evhttp_make_request(evcon,
-	    req, EVHTTP_REQ_GET, with_delay ? "/largedelay" : "/test") == -1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	event_dispatch();
-
-	if (test_ok != 1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/* at this point, the http server should have no connection */
-	if (TAILQ_FIRST(&http->connections) != NULL) {
-		fprintf(stdout, "FAILED (left connections)\n");
-		exit(1);
-	}
-
-	evhttp_connection_free(evcon);
-	evhttp_free(http);
-	
-	fprintf(stdout, "OK\n");
-}
-
-static void
-http_highport_test(void)
-{
-	int i = -1;
-	struct evhttp *myhttp = NULL;
- 
-	fprintf(stdout, "Testing HTTP Server with high port: ");
-
-	/* Try a few different ports */
-	for (i = 0; i < 50; ++i) {
-		myhttp = evhttp_start("127.0.0.1", 65535 - i);
-		if (myhttp != NULL) {
-			fprintf(stdout, "OK\n");
-			evhttp_free(myhttp);
-			return;
-		}
-	}
-
-	fprintf(stdout, "FAILED\n");
-	exit(1);
-}
-
-static void
-http_bad_header_test(void)
-{
-	struct evkeyvalq headers;
-
-	fprintf(stdout, "Testing HTTP Header filtering: ");
-
-	TAILQ_INIT(&headers);
-
-	if (evhttp_add_header(&headers, "One", "Two") != 0)
-		goto fail;
-	
-	if (evhttp_add_header(&headers, "One\r", "Two") != -1)
-		goto fail;
-	if (evhttp_add_header(&headers, "One", "Two") != 0)
-		goto fail;
-	if (evhttp_add_header(&headers, "One", "Two\r\n Three") != 0)
-		goto fail;
-	if (evhttp_add_header(&headers, "One\r", "Two") != -1)
-		goto fail;
-	if (evhttp_add_header(&headers, "One\n", "Two") != -1)
-		goto fail;
-	if (evhttp_add_header(&headers, "One", "Two\r") != -1)
-		goto fail;
-	if (evhttp_add_header(&headers, "One", "Two\n") != -1)
-		goto fail;
-
-	evhttp_clear_headers(&headers);
-
-	fprintf(stdout, "OK\n");
-	return;
-fail:
-	fprintf(stdout, "FAILED\n");
-	exit(1);
-}
-
-static int validate_header(
-	const struct evkeyvalq* headers,
-	const char *key, const char *value) 
-{
-	const char *real_val = evhttp_find_header(headers, key);
-	if (real_val == NULL)
-		return (-1);
-	if (strcmp(real_val, value) != 0)
-		return (-1);
-	return (0);
-}
-
-static void
-http_parse_query_test(void)
-{
-	struct evkeyvalq headers;
-
-	fprintf(stdout, "Testing HTTP query parsing: ");
-
-	TAILQ_INIT(&headers);
-	
-	evhttp_parse_query("http://www.test.com/?q=test", &headers);
-	if (validate_header(&headers, "q", "test") != 0)
-		goto fail;
-	evhttp_clear_headers(&headers);
-
-	evhttp_parse_query("http://www.test.com/?q=test&foo=bar", &headers);
-	if (validate_header(&headers, "q", "test") != 0)
-		goto fail;
-	if (validate_header(&headers, "foo", "bar") != 0)
-		goto fail;
-	evhttp_clear_headers(&headers);
-
-	evhttp_parse_query("http://www.test.com/?q=test+foo", &headers);
-	if (validate_header(&headers, "q", "test foo") != 0)
-		goto fail;
-	evhttp_clear_headers(&headers);
-
-	evhttp_parse_query("http://www.test.com/?q=test%0Afoo", &headers);
-	if (validate_header(&headers, "q", "test\nfoo") != 0)
-		goto fail;
-	evhttp_clear_headers(&headers);
-
-	evhttp_parse_query("http://www.test.com/?q=test%0Dfoo", &headers);
-	if (validate_header(&headers, "q", "test\rfoo") != 0)
-		goto fail;
-	evhttp_clear_headers(&headers);
-
-	fprintf(stdout, "OK\n");
-	return;
-fail:
-	fprintf(stdout, "FAILED\n");
-	exit(1);
-}
-
-static void
-http_base_test(void)
-{
-	struct bufferevent *bev;
-	int fd;
-	const char *http_request;
-	short port = -1;
-
-	test_ok = 0;
-	fprintf(stdout, "Testing HTTP Server Event Base: ");
-
-	base = event_init();
-
-	/* 
-	 * create another bogus base - which is being used by all subsequen
-	 * tests - yuck!
-	 */
-	event_init();
-
-	http = http_setup(&port, base);
-	
-	fd = http_connect("127.0.0.1", port);
-
-	/* Stupid thing to send a request */
-	bev = bufferevent_new(fd, http_readcb, http_writecb,
-	    http_errorcb, NULL);
-	bufferevent_base_set(base, bev);
-
-	http_request =
-	    "GET /test HTTP/1.1\r\n"
-	    "Host: somehost\r\n"
-	    "Connection: close\r\n"
-	    "\r\n";
-
-	bufferevent_write(bev, http_request, strlen(http_request));
-	
-	event_base_dispatch(base);
-
-	bufferevent_free(bev);
-	EVUTIL_CLOSESOCKET(fd);
-
-	evhttp_free(http);
-
-	event_base_free(base);
-	base = NULL;
-	
-	if (test_ok != 2) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-	
-	fprintf(stdout, "OK\n");
-}
-
-/*
- * the server is going to reply with chunked data.
- */
-
-static void
-http_chunked_readcb(struct bufferevent *bev, void *arg)
-{
-	/* nothing here */
-}
-
-static void
-http_chunked_errorcb(struct bufferevent *bev, short what, void *arg)
-{
-	if (!test_ok)
-		goto out;
-
-	test_ok = -1;
-
-	if ((what & EVBUFFER_EOF) != 0) {
-		struct evhttp_request *req = evhttp_request_new(NULL, NULL);
-		const char *header;
-		enum message_read_status done;
-		
-		req->kind = EVHTTP_RESPONSE;
-		done = evhttp_parse_firstline(req, EVBUFFER_INPUT(bev));
-		if (done != ALL_DATA_READ)
-			goto out;
-
-		done = evhttp_parse_headers(req, EVBUFFER_INPUT(bev));
-		if (done != ALL_DATA_READ)
-			goto out;
-
-		header = evhttp_find_header(req->input_headers, "Transfer-Encoding");
-		if (header == NULL || strcmp(header, "chunked"))
-			goto out;
-
-		header = evhttp_find_header(req->input_headers, "Connection");
-		if (header == NULL || strcmp(header, "close"))
-			goto out;
-
-		header = evbuffer_readline(EVBUFFER_INPUT(bev));
-		if (header == NULL)
-			goto out;
-		/* 13 chars */
-		if (strcmp(header, "d"))
-			goto out;
-		free((char*)header);
-
-		if (strncmp((char *)EVBUFFER_DATA(EVBUFFER_INPUT(bev)),
-			"This is funny", 13))
-			goto out;
-
-		evbuffer_drain(EVBUFFER_INPUT(bev), 13 + 2);
-
-		header = evbuffer_readline(EVBUFFER_INPUT(bev));
-		if (header == NULL)
-			goto out;
-		/* 18 chars */
-		if (strcmp(header, "12"))
-			goto out;
-		free((char *)header);
-
-		if (strncmp((char *)EVBUFFER_DATA(EVBUFFER_INPUT(bev)),
-			"but not hilarious.", 18))
-			goto out;
-
-		evbuffer_drain(EVBUFFER_INPUT(bev), 18 + 2);
-
-		header = evbuffer_readline(EVBUFFER_INPUT(bev));
-		if (header == NULL)
-			goto out;
-		/* 8 chars */
-		if (strcmp(header, "8"))
-			goto out;
-		free((char *)header);
-
-		if (strncmp((char *)EVBUFFER_DATA(EVBUFFER_INPUT(bev)),
-			"bwv 1052.", 8))
-			goto out;
-
-		evbuffer_drain(EVBUFFER_INPUT(bev), 8 + 2);
-
-		header = evbuffer_readline(EVBUFFER_INPUT(bev));
-		if (header == NULL)
-			goto out;
-		/* 0 chars */
-		if (strcmp(header, "0"))
-			goto out;
-		free((char *)header);
-
-		test_ok = 2;
-	}
-
-out:
-	event_loopexit(NULL);
-}
-
-static void
-http_chunked_writecb(struct bufferevent *bev, void *arg)
-{
-	if (EVBUFFER_LENGTH(EVBUFFER_OUTPUT(bev)) == 0) {
-		/* enable reading of the reply */
-		bufferevent_enable(bev, EV_READ);
-		test_ok++;
-	}
-}
-
-static void
-http_chunked_request_done(struct evhttp_request *req, void *arg)
-{
-	if (req->response_code != HTTP_OK) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	if (evhttp_find_header(req->input_headers,
-		"Transfer-Encoding") == NULL) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	if (EVBUFFER_LENGTH(req->input_buffer) != 13 + 18 + 8) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	if (strncmp((char *)EVBUFFER_DATA(req->input_buffer),
-		"This is funnybut not hilarious.bwv 1052",
-		13 + 18 + 8)) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-	
-	test_ok = 1;
-	event_loopexit(NULL);
-}
-
-static void
-http_chunked_test(void)
-{
-	struct bufferevent *bev;
-	int fd;
-	const char *http_request;
-	short port = -1;
-	struct timeval tv_start, tv_end;
-	struct evhttp_connection *evcon = NULL;
-	struct evhttp_request *req = NULL;
-	int i;
-
-	test_ok = 0;
-	fprintf(stdout, "Testing Chunked HTTP Reply: ");
-
-	http = http_setup(&port, NULL);
-
-	fd = http_connect("127.0.0.1", port);
-
-	/* Stupid thing to send a request */
-	bev = bufferevent_new(fd, 
-	    http_chunked_readcb, http_chunked_writecb,
-	    http_chunked_errorcb, NULL);
-
-	http_request =
-	    "GET /chunked HTTP/1.1\r\n"
-	    "Host: somehost\r\n"
-	    "Connection: close\r\n"
-	    "\r\n";
-
-	bufferevent_write(bev, http_request, strlen(http_request));
-
-	evutil_gettimeofday(&tv_start, NULL);
-	
-	event_dispatch();
-
-	evutil_gettimeofday(&tv_end, NULL);
-	evutil_timersub(&tv_end, &tv_start, &tv_end);
-
-	if (tv_end.tv_sec >= 1) {
-		fprintf(stdout, "FAILED (time)\n");
-		exit (1);
-	}
-
-
-	if (test_ok != 2) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/* now try again with the regular connection object */
-	evcon = evhttp_connection_new("127.0.0.1", port);
-	if (evcon == NULL) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/* make two requests to check the keepalive behavior */
-	for (i = 0; i < 2; i++) {
-		test_ok = 0;
-		req = evhttp_request_new(http_chunked_request_done, NULL);
-
-		/* Add the information that we care about */
-		evhttp_add_header(req->output_headers, "Host", "somehost");
-
-		/* We give ownership of the request to the connection */
-		if (evhttp_make_request(evcon, req,
-			EVHTTP_REQ_GET, "/chunked") == -1) {
-			fprintf(stdout, "FAILED\n");
-			exit(1);
-		}
-
-		event_dispatch();
-
-		if (test_ok != 1) {
-			fprintf(stdout, "FAILED\n");
-			exit(1);
-		}
-	}
-
-	evhttp_connection_free(evcon);
-	evhttp_free(http);
-	
-	fprintf(stdout, "OK\n");
-}
-
-static void
-http_multi_line_header_test(void)
-{
-	struct bufferevent *bev;
-	int fd;
-	const char *http_start_request;
-	short port = -1;
-	
-	test_ok = 0;
-	fprintf(stdout, "Testing HTTP Server with multi line: ");
-
-	http = http_setup(&port, NULL);
-	
-	fd = http_connect("127.0.0.1", port);
-
-	/* Stupid thing to send a request */
-	bev = bufferevent_new(fd, http_readcb, http_writecb,
-	    http_errorcb, NULL);
-
-	http_start_request =
-	    "GET /test HTTP/1.1\r\n"
-	    "Host: somehost\r\n"
-	    "Connection: close\r\n"
-	    "X-Multi:  aaaaaaaa\r\n"
-	    " a\r\n"
-	    "\tEND\r\n"
-	    "X-Last: last\r\n"
-	    "\r\n";
-		
-	bufferevent_write(bev, http_start_request, strlen(http_start_request));
-
-	event_dispatch();
-	
-	bufferevent_free(bev);
-	EVUTIL_CLOSESOCKET(fd);
-
-	evhttp_free(http);
-
-	if (test_ok != 4) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-	
-	fprintf(stdout, "OK\n");
-}
-
-static void
-http_request_bad(struct evhttp_request *req, void *arg)
-{
-	if (req != NULL) {
-		fprintf(stderr, "FAILED\n");
-		exit(1);
-	}
-
-	test_ok = 1;
-	event_loopexit(NULL);
-}
-
-static void
-http_negative_content_length_test(void)
-{
-	short port = -1;
-	struct evhttp_connection *evcon = NULL;
-	struct evhttp_request *req = NULL;
-	
-	test_ok = 0;
-	fprintf(stdout, "Testing HTTP Negative Content Length: ");
-
-	http = http_setup(&port, NULL);
-
-	evcon = evhttp_connection_new("127.0.0.1", port);
-	if (evcon == NULL) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/*
-	 * At this point, we want to schedule a request to the HTTP
-	 * server using our make request method.
-	 */
-
-	req = evhttp_request_new(http_request_bad, NULL);
-
-	/* Cause the response to have a negative content-length */
-	evhttp_add_header(req->output_headers, "X-Negative", "makeitso");
-
-	/* We give ownership of the request to the connection */
-	if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	event_dispatch();
-
-	evhttp_free(http);
-
-	if (test_ok != 1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	fprintf(stdout, "OK\n");
-}
-
-/*
- * Testing client reset of server chunked connections
- */
-
-struct terminate_state {
-	struct evhttp_request *req;
-	struct bufferevent *bev;
-	int fd;
-} terminate_state;
-
-static void
-terminate_chunked_trickle_cb(int fd, short events, void *arg)
-{
-	struct terminate_state *state = arg;
-	struct evbuffer *evb = evbuffer_new();
-	struct timeval tv;
-
-	if (evhttp_request_get_connection(state->req) == NULL) {
-		test_ok = 1;
-		evhttp_request_free(state->req);
-		event_loopexit(NULL);
-		return;
-	}
-
-	evbuffer_add_printf(evb, "%p", evb);
-	evhttp_send_reply_chunk(state->req, evb);
-	evbuffer_free(evb);
-
-	tv.tv_sec = 0;
-	tv.tv_usec = 3000;
-	event_once(-1, EV_TIMEOUT, terminate_chunked_trickle_cb, arg, &tv);
-}
-
-static void
-terminate_chunked_cb(struct evhttp_request *req, void *arg)
-{
-	struct terminate_state *state = arg;
-	struct timeval tv;
-
-	state->req = req;
-
-	evhttp_send_reply_start(req, HTTP_OK, "OK");
-
-	tv.tv_sec = 0;
-	tv.tv_usec = 3000;
-	event_once(-1, EV_TIMEOUT, terminate_chunked_trickle_cb, arg, &tv);
-}
-
-static void
-terminate_chunked_client(int fd, short event, void *arg)
-{
-	struct terminate_state *state = arg;
-	bufferevent_free(state->bev);
-	EVUTIL_CLOSESOCKET(state->fd);
-}
-
-static void
-terminate_readcb(struct bufferevent *bev, void *arg)
-{
-	/* just drop the data */
-	evbuffer_drain(bev->output, -1);
-}
-
-
-static void
-http_terminate_chunked_test(void)
-{
-	struct bufferevent *bev = NULL;
-	struct timeval tv;
-	const char *http_request;
-	short port = -1;
-	int fd = -1;
-
-	test_ok = 0;
-	fprintf(stdout, "Testing Terminated Chunked Connection: ");
-
-	http = http_setup(&port, NULL);
-	evhttp_del_cb(http, "/test");
-	evhttp_set_cb(http, "/test", terminate_chunked_cb, &terminate_state);
-
-	fd = http_connect("127.0.0.1", port);
-
-	/* Stupid thing to send a request */
-	bev = bufferevent_new(fd, terminate_readcb, http_writecb,
-	    http_errorcb, NULL);
-
-	terminate_state.fd = fd;
-	terminate_state.bev = bev;
-
-	/* first half of the http request */
-	http_request =
-	    "GET /test HTTP/1.1\r\n"
-	    "Host: some\r\n\r\n";
-
-	bufferevent_write(bev, http_request, strlen(http_request));
-	evutil_timerclear(&tv);
-	tv.tv_usec = 10000;
-	event_once(-1, EV_TIMEOUT, terminate_chunked_client, &terminate_state,
-	    &tv);
-
-	event_dispatch();
-
-	if (test_ok != 1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	fprintf(stdout, "OK\n");
-
-	if (fd >= 0)
-		EVUTIL_CLOSESOCKET(fd);
-	if (http)
-		evhttp_free(http);
-}
-
-void
-http_suite(void)
-{
-	http_base_test();
-	http_bad_header_test();
-	http_parse_query_test();
-	http_basic_test();
-	http_connection_test(0 /* not-persistent */);
-	http_connection_test(1 /* persistent */);
-	http_close_detection(0 /* without delay */);
-	http_close_detection(1 /* with delay */);
-	http_bad_request();
-	http_post_test();
-	http_failure_test();
-	http_highport_test();
-	http_dispatcher_test();
-
-	http_multi_line_header_test();
-	http_negative_content_length_test();
-
-	http_chunked_test();
-	http_terminate_chunked_test();
-}
diff --git a/base/third_party/libevent/test/regress_rpc.c b/base/third_party/libevent/test/regress_rpc.c
deleted file mode 100644
index 7609347..0000000
--- a/base/third_party/libevent/test/regress_rpc.c
+++ /dev/null
@@ -1,631 +0,0 @@
-/*
- * Copyright (c) 2003-2006 Niels Provos <provos@citi.umich.edu>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- *    derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifdef WIN32
-#include <winsock2.h>
-#include <windows.h>
-#endif
-
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#include <sys/queue.h>
-#ifndef WIN32
-#include <sys/socket.h>
-#include <signal.h>
-#include <unistd.h>
-#include <netdb.h>
-#endif
-#include <fcntl.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-#include <assert.h>
-
-#include "event.h"
-#include "evhttp.h"
-#include "log.h"
-#include "evrpc.h"
-
-#include "regress.gen.h"
-
-void rpc_suite(void);
-
-extern int test_ok;
-
-static struct evhttp *
-http_setup(short *pport)
-{
-	int i;
-	struct evhttp *myhttp;
-	short port = -1;
-
-	/* Try a few different ports */
-	for (i = 0; i < 50; ++i) {
-		myhttp = evhttp_start("127.0.0.1", 8080 + i);
-		if (myhttp != NULL) {
-			port = 8080 + i;
-			break;
-		}
-	}
-
-	if (port == -1)
-		event_errx(1, "Could not start web server");
-
-	*pport = port;
-	return (myhttp);
-}
-
-EVRPC_HEADER(Message, msg, kill);
-EVRPC_HEADER(NeverReply, msg, kill);
-
-EVRPC_GENERATE(Message, msg, kill);
-EVRPC_GENERATE(NeverReply, msg, kill);
-
-static int need_input_hook = 0;
-static int need_output_hook = 0;
-
-static void
-MessageCb(EVRPC_STRUCT(Message)* rpc, void *arg)
-{
-	struct kill* kill_reply = rpc->reply;
-
-	if (need_input_hook) {
-		struct evhttp_request* req = EVRPC_REQUEST_HTTP(rpc);
-		const char *header = evhttp_find_header(
-			req->input_headers, "X-Hook");
-		assert(strcmp(header, "input") == 0);
-	}
-
-	/* we just want to fill in some non-sense */
-	EVTAG_ASSIGN(kill_reply, weapon, "dagger");
-	EVTAG_ASSIGN(kill_reply, action, "wave around like an idiot");
-
-	/* no reply to the RPC */
-	EVRPC_REQUEST_DONE(rpc);
-}
-
-static EVRPC_STRUCT(NeverReply) *saved_rpc;
-
-static void
-NeverReplyCb(EVRPC_STRUCT(NeverReply)* rpc, void *arg)
-{
-	test_ok += 1;
-	saved_rpc = rpc;
-}
-
-static void
-rpc_setup(struct evhttp **phttp, short *pport, struct evrpc_base **pbase)
-{
-	short port;
-	struct evhttp *http = NULL;
-	struct evrpc_base *base = NULL;
-
-	http = http_setup(&port);
-	base = evrpc_init(http);
-	
-	EVRPC_REGISTER(base, Message, msg, kill, MessageCb, NULL);
-	EVRPC_REGISTER(base, NeverReply, msg, kill, NeverReplyCb, NULL);
-
-	*phttp = http;
-	*pport = port;
-	*pbase = base;
-
-	need_input_hook = 0;
-	need_output_hook = 0;
-}
-
-static void
-rpc_teardown(struct evrpc_base *base)
-{
-	assert(EVRPC_UNREGISTER(base, Message) == 0);
-	assert(EVRPC_UNREGISTER(base, NeverReply) == 0);
-
-	evrpc_free(base);
-}
-
-static void
-rpc_postrequest_failure(struct evhttp_request *req, void *arg)
-{
-	if (req->response_code != HTTP_SERVUNAVAIL) {
-	
-		fprintf(stderr, "FAILED (response code)\n");
-		exit(1);
-	}
-
-	test_ok = 1;
-	event_loopexit(NULL);
-}
-
-/*
- * Test a malformed payload submitted as an RPC
- */
-
-static void
-rpc_basic_test(void)
-{
-	short port;
-	struct evhttp *http = NULL;
-	struct evrpc_base *base = NULL;
-	struct evhttp_connection *evcon = NULL;
-	struct evhttp_request *req = NULL;
-
-	fprintf(stdout, "Testing Basic RPC Support: ");
-
-	rpc_setup(&http, &port, &base);
-
-	evcon = evhttp_connection_new("127.0.0.1", port);
-	if (evcon == NULL) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/*
-	 * At this point, we want to schedule an HTTP POST request
-	 * server using our make request method.
-	 */
-
-	req = evhttp_request_new(rpc_postrequest_failure, NULL);
-	if (req == NULL) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/* Add the information that we care about */
-	evhttp_add_header(req->output_headers, "Host", "somehost");
-	evbuffer_add_printf(req->output_buffer, "Some Nonsense");
-	
-	if (evhttp_make_request(evcon, req,
-		EVHTTP_REQ_POST,
-		"/.rpc.Message") == -1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	test_ok = 0;
-
-	event_dispatch();
-
-	evhttp_connection_free(evcon);
-
-	rpc_teardown(base);
-	
-	if (test_ok != 1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	fprintf(stdout, "OK\n");
-
-	evhttp_free(http);
-}
-
-static void
-rpc_postrequest_done(struct evhttp_request *req, void *arg)
-{
-	struct kill* kill_reply = NULL;
-
-	if (req->response_code != HTTP_OK) {
-	
-		fprintf(stderr, "FAILED (response code)\n");
-		exit(1);
-	}
-
-	kill_reply = kill_new();
-
-	if ((kill_unmarshal(kill_reply, req->input_buffer)) == -1) {
-		fprintf(stderr, "FAILED (unmarshal)\n");
-		exit(1);
-	}
-	
-	kill_free(kill_reply);
-
-	test_ok = 1;
-	event_loopexit(NULL);
-}
-
-static void
-rpc_basic_message(void)
-{
-	short port;
-	struct evhttp *http = NULL;
-	struct evrpc_base *base = NULL;
-	struct evhttp_connection *evcon = NULL;
-	struct evhttp_request *req = NULL;
-	struct msg *msg;
-
-	fprintf(stdout, "Testing Good RPC Post: ");
-
-	rpc_setup(&http, &port, &base);
-
-	evcon = evhttp_connection_new("127.0.0.1", port);
-	if (evcon == NULL) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/*
-	 * At this point, we want to schedule an HTTP POST request
-	 * server using our make request method.
-	 */
-
-	req = evhttp_request_new(rpc_postrequest_done, NULL);
-	if (req == NULL) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	/* Add the information that we care about */
-	evhttp_add_header(req->output_headers, "Host", "somehost");
-
-	/* set up the basic message */
-	msg = msg_new();
-	EVTAG_ASSIGN(msg, from_name, "niels");
-	EVTAG_ASSIGN(msg, to_name, "tester");
-	msg_marshal(req->output_buffer, msg);
-	msg_free(msg);
-
-	if (evhttp_make_request(evcon, req,
-		EVHTTP_REQ_POST,
-		"/.rpc.Message") == -1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	test_ok = 0;
-
-	event_dispatch();
-
-	evhttp_connection_free(evcon);
-	
-	rpc_teardown(base);
-	
-	if (test_ok != 1) {
-		fprintf(stdout, "FAILED\n");
-		exit(1);
-	}
-
-	fprintf(stdout, "OK\n");
-
-	evhttp_free(http);
-}
-
-static struct evrpc_pool *
-rpc_pool_with_connection(short port)
-{
-	struct evhttp_connection *evcon;
-	struct evrpc_pool *pool;
-
-	pool = evrpc_pool_new(NULL);
-	assert(pool != NULL);
-
-	evcon = evhttp_connection_new("127.0.0.1", port);
-	assert(evcon != NULL);
-
-	evrpc_pool_add_connection(pool, evcon);
-	
-	return (pool);
-}
-
-static void
-GotKillCb(struct evrpc_status *status,
-    struct msg *msg, struct kill *kill, void *arg)
-{
-	char *weapon;
-	char *action;
-
-	if (need_output_hook) {
-		struct evhttp_request *req = status->http_req;
-		const char *header = evhttp_find_header(
-			req->input_headers, "X-Pool-Hook");
-		assert(strcmp(header, "ran") == 0);
-	}
-
-	if (status->error != EVRPC_STATUS_ERR_NONE)
-		goto done;
-
-	if (EVTAG_GET(kill, weapon, &weapon) == -1) {
-		fprintf(stderr, "get weapon\n");
-		goto done;
-	}
-	if (EVTAG_GET(kill, action, &action) == -1) {
-		fprintf(stderr, "get action\n");
-		goto done;
-	}
-
-	if (strcmp(weapon, "dagger"))
-		goto done;
-
-	if (strcmp(action, "wave around like an idiot"))
-		goto done;
-
-	test_ok += 1;
-
-done:
-	event_loopexit(NULL);
-}
-
-static void
-GotKillCbTwo(struct evrpc_status *status,
-    struct msg *msg, struct kill *kill, void *arg)
-{
-	char *weapon;
-	char *action;
-
-	if (status->error != EVRPC_STATUS_ERR_NONE)
-		goto done;
-
-	if (EVTAG_GET(kill, weapon, &weapon) == -1) {
-		fprintf(stderr, "get weapon\n");
-		goto done;
-	}
-	if (EVTAG_GET(kill, action, &action) == -1) {
-		fprintf(stderr, "get action\n");
-		goto done;
-	}
-
-	if (strcmp(weapon, "dagger"))
-		goto done;
-
-	if (strcmp(action, "wave around like an idiot"))
-		goto done;
-
-	test_ok += 1;
-
-done:
-	if (test_ok == 2)
-		event_loopexit(NULL);
-}
-
-static int
-rpc_hook_add_header(struct evhttp_request *req,
-    struct evbuffer *evbuf, void *arg)
-{
-	const char *hook_type = arg;
-	if (strcmp("input", hook_type) == 0)
-		evhttp_add_header(req->input_headers, "X-Hook", hook_type);
-	else 
-		evhttp_add_header(req->output_headers, "X-Hook", hook_type);
-	return (0);
-}
-
-static int
-rpc_hook_remove_header(struct evhttp_request *req,
-    struct evbuffer *evbuf, void *arg)
-{
-	const char *header = evhttp_find_header(req->input_headers, "X-Hook");
-	assert(header != NULL);
-	assert(strcmp(header, arg) == 0);
-	evhttp_remove_header(req->input_headers, "X-Hook");
-	evhttp_add_header(req->input_headers, "X-Pool-Hook", "ran");
-
-	return (0);
-}
-
-static void
-rpc_basic_client(void)
-{
-	short port;
-	struct evhttp *http = NULL;
-	struct evrpc_base *base = NULL;
-	struct evrpc_pool *pool = NULL;
-	struct msg *msg;
-	struct kill *kill;
-
-	fprintf(stdout, "Testing RPC Client: ");
-
-	rpc_setup(&http, &port, &base);
-
-	need_input_hook = 1;
-	need_output_hook = 1;
-
-	assert(evrpc_add_hook(base, EVRPC_INPUT, rpc_hook_add_header, (void*)"input")
-	    != NULL);
-	assert(evrpc_add_hook(base, EVRPC_OUTPUT, rpc_hook_add_header, (void*)"output")
-	    != NULL);
-
-	pool = rpc_pool_with_connection(port);
-
-	assert(evrpc_add_hook(pool, EVRPC_INPUT, rpc_hook_remove_header, (void*)"output"));
-
-	/* set up the basic message */
-	msg = msg_new();
-	EVTAG_ASSIGN(msg, from_name, "niels");
-	EVTAG_ASSIGN(msg, to_name, "tester");
-
-	kill = kill_new();
-
-	EVRPC_MAKE_REQUEST(Message, pool, msg, kill,  GotKillCb, NULL);
-
-	test_ok = 0;
-
-	event_dispatch();
-	
-	if (test_ok != 1) {
-		fprintf(stdout, "FAILED (1)\n");
-		exit(1);
-	}
-
-	/* we do it twice to make sure that reuse works correctly */
-	kill_clear(kill);
-
-	EVRPC_MAKE_REQUEST(Message, pool, msg, kill,  GotKillCb, NULL);
-
-	event_dispatch();
-	
-	rpc_teardown(base);
-	
-	if (test_ok != 2) {
-		fprintf(stdout, "FAILED (2)\n");
-		exit(1);
-	}
-
-	fprintf(stdout, "OK\n");
-
-	msg_free(msg);
-	kill_free(kill);
-
-	evrpc_pool_free(pool);
-	evhttp_free(http);
-}
-
-/* 
- * We are testing that the second requests gets send over the same
- * connection after the first RPCs completes.
- */
-static void
-rpc_basic_queued_client(void)
-{
-	short port;
-	struct evhttp *http = NULL;
-	struct evrpc_base *base = NULL;
-	struct evrpc_pool *pool = NULL;
-	struct msg *msg;
-	struct kill *kill_one, *kill_two;
-
-	fprintf(stdout, "Testing RPC (Queued) Client: ");
-
-	rpc_setup(&http, &port, &base);
-
-	pool = rpc_pool_with_connection(port);
-
-	/* set up the basic message */
-	msg = msg_new();
-	EVTAG_ASSIGN(msg, from_name, "niels");
-	EVTAG_ASSIGN(msg, to_name, "tester");
-
-	kill_one = kill_new();
-	kill_two = kill_new();
-
-	EVRPC_MAKE_REQUEST(Message, pool, msg, kill_one,  GotKillCbTwo, NULL);
-	EVRPC_MAKE_REQUEST(Message, pool, msg, kill_two,  GotKillCb, NULL);
-
-	test_ok = 0;
-
-	event_dispatch();
-	
-	rpc_teardown(base);
-	
-	if (test_ok != 2) {
-		fprintf(stdout, "FAILED (1)\n");
-		exit(1);
-	}
-
-	fprintf(stdout, "OK\n");
-
-	msg_free(msg);
-	kill_free(kill_one);
-	kill_free(kill_two);
-
-	evrpc_pool_free(pool);
-	evhttp_free(http);
-}
-
-static void
-GotErrorCb(struct evrpc_status *status,
-    struct msg *msg, struct kill *kill, void *arg)
-{
-	if (status->error != EVRPC_STATUS_ERR_TIMEOUT)
-		goto done;
-
-	/* should never be complete but just to check */
-	if (kill_complete(kill) == 0)
-		goto done;
-
-	test_ok += 1;
-
-done:
-	event_loopexit(NULL);
-}
-
-static void
-rpc_client_timeout(void)
-{
-	short port;
-	struct evhttp *http = NULL;
-	struct evrpc_base *base = NULL;
-	struct evrpc_pool *pool = NULL;
-	struct msg *msg;
-	struct kill *kill;
-
-	fprintf(stdout, "Testing RPC Client Timeout: ");
-
-	rpc_setup(&http, &port, &base);
-
-	pool = rpc_pool_with_connection(port);
-
-	/* set the timeout to 5 seconds */
-	evrpc_pool_set_timeout(pool, 5);
-
-	/* set up the basic message */
-	msg = msg_new();
-	EVTAG_ASSIGN(msg, from_name, "niels");
-	EVTAG_ASSIGN(msg, to_name, "tester");
-
-	kill = kill_new();
-
-	EVRPC_MAKE_REQUEST(NeverReply, pool, msg, kill, GotErrorCb, NULL);
-
-	test_ok = 0;
-
-	event_dispatch();
-	
-	/* free the saved RPC structure up */
-	EVRPC_REQUEST_DONE(saved_rpc);
-
-	rpc_teardown(base);
-	
-	if (test_ok != 2) {
-		fprintf(stdout, "FAILED (1)\n");
-		exit(1);
-	}
-
-	fprintf(stdout, "OK\n");
-
-	msg_free(msg);
-	kill_free(kill);
-
-	evrpc_pool_free(pool);
-	evhttp_free(http);
-}
-
-void
-rpc_suite(void)
-{
-	rpc_basic_test();
-	rpc_basic_message();
-	rpc_basic_client();
-	rpc_basic_queued_client();
-	rpc_client_timeout();
-}
diff --git a/base/third_party/libevent/test/test-eof.c b/base/third_party/libevent/test/test-eof.c
deleted file mode 100644
index 3264a7b..0000000
--- a/base/third_party/libevent/test/test-eof.c
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Compile with:
- * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent
- */
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-
-#ifdef WIN32
-#include <winsock2.h>
-#endif
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#ifdef HAVE_SYS_SOCKET_H
-#include <sys/socket.h>
-#endif
-#include <fcntl.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#include <errno.h>
-
-#include <event.h>
-#include <evutil.h>
-
-int test_okay = 1;
-int called = 0;
-
-static void
-read_cb(int fd, short event, void *arg)
-{
-	char buf[256];
-	int len;
-
-	len = recv(fd, buf, sizeof(buf), 0);
-
-	printf("%s: read %d%s\n", __func__,
-	    len, len ? "" : " - means EOF");
-
-	if (len) {
-		if (!called)
-			event_add(arg, NULL);
-	} else if (called == 1)
-		test_okay = 0;
-
-	called++;
-}
-
-#ifndef SHUT_WR
-#define SHUT_WR 1
-#endif
-
-int
-main (int argc, char **argv)
-{
-	struct event ev;
-	const char *test = "test string";
-	int pair[2];
-
-	if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
-		return (1);
-
-	
-	send(pair[0], test, strlen(test)+1, 0);
-	shutdown(pair[0], SHUT_WR);
-
-	/* Initalize the event library */
-	event_init();
-
-	/* Initalize one event */
-	event_set(&ev, pair[1], EV_READ, read_cb, &ev);
-
-	event_add(&ev, NULL);
-
-	event_dispatch();
-
-	return (test_okay);
-}
-
diff --git a/base/third_party/libevent/test/test-init.c b/base/third_party/libevent/test/test-init.c
deleted file mode 100644
index d60aa36..0000000
--- a/base/third_party/libevent/test/test-init.c
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Compile with:
- * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent
- */
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef WIN32
-#include <winsock2.h>
-#endif
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#ifdef HAVE_SYS_SOCKET_H
-#include <sys/socket.h>
-#endif
-#include <fcntl.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#include <errno.h>
-
-#include <event.h>
-
-int
-main(int argc, char **argv)
-{
-	/* Initalize the event library */
-	event_init();
-
-	return (0);
-}
-
diff --git a/base/third_party/libevent/test/test-time.c b/base/third_party/libevent/test/test-time.c
deleted file mode 100644
index 703bc32..0000000
--- a/base/third_party/libevent/test/test-time.c
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Compile with:
- * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent
- */
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-#ifdef WIN32
-#include <winsock2.h>
-#endif
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#include <fcntl.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#include <errno.h>
-
-#include <event.h>
-
-int called = 0;
-
-#define NEVENT	20000
-
-struct event *ev[NEVENT];
-
-static int
-rand_int(int n)
-{
-#ifdef WIN32
-	return (int)(rand() * n);
-#else
-	return (int)(random() % n);
-#endif
-}
-
-static void
-time_cb(int fd, short event, void *arg)
-{
-	struct timeval tv;
-	int i, j;
-
-	called++;
-
-	if (called < 10*NEVENT) {
-		for (i = 0; i < 10; i++) {
-			j = rand_int(NEVENT);
-			tv.tv_sec = 0;
-			tv.tv_usec = rand_int(50000);
-			if (tv.tv_usec % 2)
-				evtimer_add(ev[j], &tv);
-			else
-				evtimer_del(ev[j]);
-		}
-	}
-}
-
-int
-main (int argc, char **argv)
-{
-	struct timeval tv;
-	int i;
-
-	/* Initalize the event library */
-	event_init();
-
-	for (i = 0; i < NEVENT; i++) {
-		ev[i] = malloc(sizeof(struct event));
-
-		/* Initalize one event */
-		evtimer_set(ev[i], time_cb, ev[i]);
-		tv.tv_sec = 0;
-		tv.tv_usec = rand_int(50000);
-		evtimer_add(ev[i], &tv);
-	}
-
-	event_dispatch();
-
-	return (called < NEVENT);
-}
-
diff --git a/base/third_party/libevent/test/test-weof.c b/base/third_party/libevent/test/test-weof.c
deleted file mode 100644
index 7fd6c8b..0000000
--- a/base/third_party/libevent/test/test-weof.c
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Compile with:
- * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent
- */
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-
-
-#ifdef WIN32
-#include <winsock2.h>
-#endif
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#ifdef HAVE_SYS_SOCKET_H
-#include <sys/socket.h>
-#endif
-#include <fcntl.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <signal.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#include <errno.h>
-
-#include <event.h>
-#include <evutil.h>
-
-int pair[2];
-int test_okay = 1;
-int called = 0;
-
-static void
-write_cb(int fd, short event, void *arg)
-{
-	const char *test = "test string";
-	int len;
-
-	len = send(fd, test, strlen(test) + 1, 0);
-
-	printf("%s: write %d%s\n", __func__,
-	    len, len ? "" : " - means EOF");
-
-	if (len > 0) {
-		if (!called)
-			event_add(arg, NULL);
-		EVUTIL_CLOSESOCKET(pair[0]);
-	} else if (called == 1)
-		test_okay = 0;
-
-	called++;
-}
-
-int
-main (int argc, char **argv)
-{
-	struct event ev;
-
-#ifndef WIN32
-	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
-		return (1);
-#endif
-
-	if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
-		return (1);
-
-	/* Initalize the event library */
-	event_init();
-
-	/* Initalize one event */
-	event_set(&ev, pair[1], EV_WRITE, write_cb, &ev);
-
-	event_add(&ev, NULL);
-
-	event_dispatch();
-
-	return (test_okay);
-}
-
diff --git a/base/third_party/libevent/test/test.sh b/base/third_party/libevent/test/test.sh
deleted file mode 100755
index 506a198..0000000
--- a/base/third_party/libevent/test/test.sh
+++ /dev/null
@@ -1,91 +0,0 @@
-#!/bin/sh
-
-setup () {
-	 EVENT_NOKQUEUE=yes; export EVENT_NOKQUEUE
-	 EVENT_NODEVPOLL=yes; export EVENT_NODEVPOLL
-	 EVENT_NOPOLL=yes; export EVENT_NOPOLL
-	 EVENT_NOSELECT=yes; export EVENT_NOSELECT
-	 EVENT_NOEPOLL=yes; export EVENT_NOEPOLL
-	 EVENT_NOEVPORT=yes; export EVENT_NOEVPORT
-}
-
-test () {
-	if ./test-init 2>/dev/null ;
-	then
-	        true
-	else
-		echo Skipping test
-		return
-	fi	
-
-echo -n " test-eof: "
-if ./test-eof >/dev/null ; 
-then 
-	echo OKAY ; 
-else 
-	echo FAILED ; 
-fi
-echo -n " test-weof: "
-if ./test-weof >/dev/null ; 
-then 
-	echo OKAY ; 
-else 
-	echo FAILED ; 
-fi
-echo -n " test-time: "
-if ./test-time >/dev/null ; 
-then 
-	echo OKAY ; 
-else 
-	echo FAILED ; 
-fi
-echo -n " regress: "
-if ./regress >/dev/null ; 
-then 
-	echo OKAY ; 
-else 
-	echo FAILED ; 
-fi
-}
-
-echo "Running tests:"
-
-# Need to do this by hand?
-setup
-unset EVENT_NOKQUEUE
-export EVENT_NOKQUEUE
-echo "KQUEUE"
-test
-
-setup
-unset EVENT_NODEVPOLL
-export EVENT_NODEVPOLL
-echo "DEVPOLL"
-test
-
-setup
-unset EVENT_NOPOLL
-export EVENT_NOPOLL
-echo "POLL"
-test
-
-setup
-unset EVENT_NOSELECT
-export EVENT_NOSELECT
-echo "SELECT"
-test
-
-setup
-unset EVENT_NOEPOLL
-export EVENT_NOEPOLL
-echo "EPOLL"
-test
-
-setup
-unset EVENT_NOEVPORT
-export EVENT_NOEVPORT
-echo "EVPORT"
-test
-
-
-
diff --git a/base/third_party/libevent/whatsnew-14.txt b/base/third_party/libevent/whatsnew-14.txt
deleted file mode 100644
index 769dda7..0000000
--- a/base/third_party/libevent/whatsnew-14.txt
+++ /dev/null
@@ -1,167 +0,0 @@
-What's New In Libevent 1.4:
-
-0. About this document
-
-  This document describes the key differences between Libevent 1.3 and
-  Libevent 1.4, from a user's point of view.  It was most recently
-  updated based on features from libevent 1.4.2-rc.
-
-1. Packaging Issues.
-
-1.1. The great library division.
-
-  The libevent source now builds two libraries: libevent_core and
-  libevent_extra.  The libevent_core library includes event loops,
-  timers, buffer code, and various small compatibility functions.  The
-  libevent_extra library includes code for HTTP, DNS, RPC, and so on.
-  Thus, if you're writing software that only uses libevent's event
-  loop, you should link against only the libevent_core library,
-  whereas if you're writing software that uses libevent's protocol
-  support as well, you need to link libevent_extra as well.
-
-  For backward compatibility, libevent also builds a library called
-  "libevent" that includes everything.
-
-1.2. The event-config.h header
-
-  Libevent configure script now builds two headers from its configure
-  script: config.h (which it uses internally) and event-config.h
-  (which it installs as a header file).  All of the macros in
-  event-config.h are modified so that they're safe to include in other
-  projects.  This allows libevent's header files (like event.h and
-  evutil.h) information about platform configuration.
-
-  What does this mean for you?  As of 1.4.x, it should never be
-  necessary to include extra files or define extra types before you
-  include event.h (or any other libevent header); event.h can now look
-  at the information in event-config.h and figure out what it needs to
-  include.
-
-1.3. Documentation
-
-  Libevent now includes better doxygen documentation.  It's not
-  perfect or complete, though; if you find a mistake, please let us
-  know.
-
-1.4. Libtool usage
-
-  We now use libtool's library versioning support correctly.  If we
-  don't mess this up, it means that binaries linked against old
-  version of libevent should continue working when we make changes to
-  libevent that don't break backward compatibility.
-
-1.5. Portability
-
-  Libevent now builds with MSVC again.  We've only tested it with MSVC
-  2005, and the project files might not be right.  Please let us know
-  if you run into any issues.
-
-  Libevent now builds on platforms where /bin/sh is not bash.
-
-  Libevent's regression test no longer requires Python to be
-  installed.
-
-2. New and Improved APIs:
-
-  (This list includes functions that are new, functions whose behavior
-  has changed, and functions that were included in previous releases
-  but which never actually worked before.)
-
-2.1. Utility functions are defined in evutil.h
-
-  Libevent now exposes a small set of functions for cross-platform
-  network programming in evutil.h, on the theory that they've been
-  useful enough to us that other people may likely want to use them
-  too.  These are mainly workarounds for Windows issues for now: they
-  include evutil_socketpair (to fake socketpair on platforms that
-  don't have it) and evutil_make_socket_nonblocking (to make a socket
-  nonblocking in a cross-platform way.  See the header for more
-  information.
-
-2.2. In the libevent core.
-
-  The event_base_free() function now works.  Previously, it would
-  crash with an assertion failure if there were events pending on a
-  base.  Now, it simply deletes all the pending events and frees the
-  base.  Be careful -- this might leak fds and memory associated with
-  the old events.  To avoid leaks, you should still remove all the
-  events and free their resources before you delete the base.
-
-  Libevent should now work properly with fork().  Just call
-  event_reinit() on your event base after the fork call, and it should
-  work okay.  Please let us know about any bugs you find.
-
-  There's a new event_base_new() function that acts just like
-  event_init(), but does not replace the default base.  If you are
-  using multiple event bases in your code, you should just use
-  event_base_new() instead of event_init(), to avoid accidental bugs.
-
-  There's new event_loopbreak() function to make a current event loop
-  stop exiting and return.  Unlike event_loopexit, it stops subsequent
-  pending events from getting executed.  This behavior is useful for
-  scripting languages to implement exceptions from inside callbacks.
-
-  There's a new event_base_get_method() function, for use in place of
-  event_get_method() in multi-base applications.
-
-2.3. New in HTTP.
-
-  There's an evhttp_connection_set_local_address() function you can
-  use to set the local address of an HTTP connection.
-
-  HTTP/1.1 chunking now correctly ends chunks with '\r\n'.
-
-2.4. New in DNS
-
-  Instead of picking your method for generating DNS transaction IDs at
-  startup, you can use evdns_set_transaction_id() to provide a
-  transaction ID function at runtime.
-
-  The "class" field in evdns_server_request is now renamed to
-  dns_question_class, so that it won't break compilation under C++.
-  This uses some preprocessor hacks so that C code using the old name
-  won't break.  Eventually, the old name will be deprecated entirely;
-  please don't use it.
-
-2.5. New in RPC
-
-  There are now hooks on RPC input and output; can be used to
-  implement RPC independent processing such as compression or
-  authentication.
-
-  RPC tags can now be up to 32 bits.  This is wire-compatible, but
-  changes some of the types in the APIs.  Please let us know if this
-  is problematic for you.
-
-3. Big bugfixes
-
-  We've done a lot, with help from users on different platforms, to
-  make the different backends behave more similarly with respect to
-  signals and timeouts.  The kqueue and solaris backends were the big
-  offenders previously, but they should be better now.  Windows should
-  be better too, though it's likely that problems remain there.
-
-  The libevent headers (though not the source files!) should now build
-  cleanly on C++.
-
-  (For more bugfixes, see the ChangeLog file.  These are only the
-  biggies.)
-
-4. Big performance improvements
-
-  Libevent now uses a min-heap rather than a red-black tree to track
-  timeouts.  This means that finding the next timeout to fire is now
-  O(1) instead of (lg n).
-
-  The win32 select-based backend now uses a red-black tree to map
-  SOCKET handles to event structures.  This changes the performance
-  characteristics of the event loop on win32 from O(n^2) to O(n lg n).
-  Not perfect, but better.
-
-5. Removed code and features
-
-  The rtsig backend is now removed.  It hasn't even compiled for a
-  while, and nobody seemed to miss it very much.  All the platforms
-  that have rtsig seem to have a better option instead these days.
-  Please let us know if rtsig was crucial for you.
-
diff --git a/base/threading/platform_thread.h b/base/threading/platform_thread.h
index b891aef..7668c1c 100644
--- a/base/threading/platform_thread.h
+++ b/base/threading/platform_thread.h
@@ -103,19 +103,6 @@
 
 const PlatformThreadId kInvalidThreadId(0);
 
-// Valid values for priority of Thread::Options and SimpleThread::Options, and
-// SetCurrentThreadPriority(), listed in increasing order of importance.
-enum class ThreadPriority : int {
-  // Suitable for threads that shouldn't disrupt high priority work.
-  BACKGROUND,
-  // Default priority level.
-  NORMAL,
-  // Suitable for threads which generate data for the display (at ~60Hz).
-  DISPLAY,
-  // Suitable for low-latency, glitch-resistant audio.
-  REALTIME_AUDIO,
-};
-
 // A namespace for low-level thread functions.
 class BASE_EXPORT PlatformThread {
  public:
@@ -148,13 +135,6 @@
   // Sleeps for the specified duration.
   static void Sleep(base::TimeDelta duration);
 
-  // Sets the thread name visible to debuggers/tools. This will try to
-  // initialize the context for current thread unless it's a WorkerThread.
-  static void SetName(const std::string& name);
-
-  // Gets the thread name, if previously set by SetName.
-  static const char* GetName();
-
   // Creates a new thread.  The |stack_size| parameter can be 0 to indicate
   // that the default stack size should be used.  Upon success,
   // |*thread_handle| will be assigned a handle to the newly created thread,
@@ -165,28 +145,13 @@
   // the Delegate object outlives the thread.
   static bool Create(size_t stack_size,
                      Delegate* delegate,
-                     PlatformThreadHandle* thread_handle) {
-    return CreateWithPriority(stack_size, delegate, thread_handle,
-                              ThreadPriority::NORMAL);
-  }
-
-  // CreateWithPriority() does the same thing as Create() except the priority of
-  // the thread is set based on |priority|.
-  static bool CreateWithPriority(size_t stack_size, Delegate* delegate,
-                                 PlatformThreadHandle* thread_handle,
-                                 ThreadPriority priority);
+                     PlatformThreadHandle* thread_handle);
 
   // CreateNonJoinable() does the same thing as Create() except the thread
   // cannot be Join()'d.  Therefore, it also does not output a
   // PlatformThreadHandle.
   static bool CreateNonJoinable(size_t stack_size, Delegate* delegate);
 
-  // CreateNonJoinableWithPriority() does the same thing as CreateNonJoinable()
-  // except the priority of the thread is set based on |priority|.
-  static bool CreateNonJoinableWithPriority(size_t stack_size,
-                                            Delegate* delegate,
-                                            ThreadPriority priority);
-
   // Joins with a thread created via the Create function.  This function blocks
   // the caller until the designated thread exits.  This will invalidate
   // |thread_handle|.
@@ -196,41 +161,6 @@
   // and |thread_handle| is invalidated after this call.
   static void Detach(PlatformThreadHandle thread_handle);
 
-  // Returns true if SetCurrentThreadPriority() can be used to increase the
-  // priority of the current thread.
-  static bool CanIncreaseCurrentThreadPriority();
-
-  // Toggles the current thread's priority at runtime.
-  //
-  // A thread may not be able to raise its priority back up after lowering it if
-  // the process does not have a proper permission, e.g. CAP_SYS_NICE on Linux.
-  // A thread may not be able to lower its priority back down after raising it
-  // to REALTIME_AUDIO.
-  //
-  // This function must not be called from the main thread on Mac. This is to
-  // avoid performance regressions (https://crbug.com/601270).
-  //
-  // Since changing other threads' priority is not permitted in favor of
-  // security, this interface is restricted to change only the current thread
-  // priority (https://crbug.com/399473).
-  static void SetCurrentThreadPriority(ThreadPriority priority);
-
-  static ThreadPriority GetCurrentThreadPriority();
-
-#if defined(OS_LINUX)
-  // Toggles a specific thread's priority at runtime. This can be used to
-  // change the priority of a thread in a different process and will fail
-  // if the calling process does not have proper permissions. The
-  // SetCurrentThreadPriority() function above is preferred in favor of
-  // security but on platforms where sandboxed processes are not allowed to
-  // change priority this function exists to allow a non-sandboxed process
-  // to change the priority of sandboxed threads for improved performance.
-  // Warning: Don't use this for a main thread because that will change the
-  // whole thread group's (i.e. process) priority.
-  static void SetThreadPriority(PlatformThreadId thread_id,
-                                ThreadPriority priority);
-#endif
-
  private:
   DISALLOW_IMPLICIT_CONSTRUCTORS(PlatformThread);
 };
diff --git a/base/threading/platform_thread_internal_posix.cc b/base/threading/platform_thread_internal_posix.cc
deleted file mode 100644
index 378a24d..0000000
--- a/base/threading/platform_thread_internal_posix.cc
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2015 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/threading/platform_thread_internal_posix.h"
-
-#include "base/containers/adapters.h"
-#include "base/logging.h"
-
-namespace base {
-
-namespace internal {
-
-int ThreadPriorityToNiceValue(ThreadPriority priority) {
-  for (const auto& pair : kThreadPriorityToNiceValueMap) {
-    if (pair.priority == priority)
-      return pair.nice_value;
-  }
-  NOTREACHED() << "Unknown ThreadPriority";
-  return 0;
-}
-
-ThreadPriority NiceValueToThreadPriority(int nice_value) {
-  // Try to find a priority that best describes |nice_value|. If there isn't
-  // an exact match, this method returns the closest priority whose nice value
-  // is higher (lower priority) than |nice_value|.
-  for (const auto& pair : Reversed(kThreadPriorityToNiceValueMap)) {
-    if (pair.nice_value >= nice_value)
-      return pair.priority;
-  }
-
-  // Reaching here means |nice_value| is more than any of the defined
-  // priorities. The lowest priority is suitable in this case.
-  return ThreadPriority::BACKGROUND;
-}
-
-}  // namespace internal
-
-}  // namespace base
diff --git a/base/threading/platform_thread_internal_posix.h b/base/threading/platform_thread_internal_posix.h
deleted file mode 100644
index 5f4a215..0000000
--- a/base/threading/platform_thread_internal_posix.h
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright 2015 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_THREADING_PLATFORM_THREAD_INTERNAL_POSIX_H_
-#define BASE_THREADING_PLATFORM_THREAD_INTERNAL_POSIX_H_
-
-#include "base/base_export.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-
-namespace internal {
-
-struct ThreadPriorityToNiceValuePair {
-  ThreadPriority priority;
-  int nice_value;
-};
-// The elements must be listed in the order of increasing priority (lowest
-// priority first), that is, in the order of decreasing nice values (highest
-// nice value first).
-BASE_EXPORT extern
-const ThreadPriorityToNiceValuePair kThreadPriorityToNiceValueMap[4];
-
-// Returns the nice value matching |priority| based on the platform-specific
-// implementation of kThreadPriorityToNiceValueMap.
-int ThreadPriorityToNiceValue(ThreadPriority priority);
-
-// Returns the ThreadPrioirty matching |nice_value| based on the platform-
-// specific implementation of kThreadPriorityToNiceValueMap.
-BASE_EXPORT ThreadPriority NiceValueToThreadPriority(int nice_value);
-
-// Allows platform specific tweaks to the generic POSIX solution for
-// SetCurrentThreadPriority. Returns true if the platform-specific
-// implementation handled this |priority| change, false if the generic
-// implementation should instead proceed.
-bool SetCurrentThreadPriorityForPlatform(ThreadPriority priority);
-
-// Returns true if there is a platform-specific ThreadPriority set on the
-// current thread (and returns the actual ThreadPriority via |priority|).
-// Returns false otherwise, leaving |priority| untouched.
-bool GetCurrentThreadPriorityForPlatform(ThreadPriority* priority);
-
-}  // namespace internal
-
-}  // namespace base
-
-#endif  // BASE_THREADING_PLATFORM_THREAD_INTERNAL_POSIX_H_
diff --git a/base/threading/platform_thread_linux.cc b/base/threading/platform_thread_linux.cc
index 7bad123..66ff4c1 100644
--- a/base/threading/platform_thread_linux.cc
+++ b/base/threading/platform_thread_linux.cc
@@ -9,11 +9,8 @@
 #include <stddef.h>
 
 #include "base/files/file_util.h"
-#include "base/lazy_instance.h"
 #include "base/logging.h"
 #include "base/strings/string_number_conversions.h"
-#include "base/threading/platform_thread_internal_posix.h"
-#include "base/threading/thread_id_name_manager.h"
 #include "build_config.h"
 
 #if !defined(OS_NACL) && !defined(OS_AIX)
@@ -26,140 +23,6 @@
 #endif
 
 namespace base {
-namespace {
-#if !defined(OS_NACL)
-const FilePath::CharType kCgroupDirectory[] =
-    FILE_PATH_LITERAL("/sys/fs/cgroup");
-
-FilePath ThreadPriorityToCgroupDirectory(const FilePath& cgroup_filepath,
-                                         ThreadPriority priority) {
-  switch (priority) {
-    case ThreadPriority::NORMAL:
-      return cgroup_filepath;
-    case ThreadPriority::BACKGROUND:
-      return cgroup_filepath.Append(FILE_PATH_LITERAL("non-urgent"));
-    case ThreadPriority::DISPLAY:
-    case ThreadPriority::REALTIME_AUDIO:
-      return cgroup_filepath.Append(FILE_PATH_LITERAL("urgent"));
-  }
-  NOTREACHED();
-  return FilePath();
-}
-
-void SetThreadCgroup(PlatformThreadId thread_id,
-                     const FilePath& cgroup_directory) {
-  FilePath tasks_filepath = cgroup_directory.Append(FILE_PATH_LITERAL("tasks"));
-  std::string tid = IntToString(thread_id);
-  WriteFile(tasks_filepath, tid.c_str(), tid.size());
-}
-
-void SetThreadCgroupForThreadPriority(PlatformThreadId thread_id,
-                                      const FilePath& cgroup_filepath,
-                                      ThreadPriority priority) {
-  // Append "chrome" suffix.
-  FilePath cgroup_directory = ThreadPriorityToCgroupDirectory(
-      cgroup_filepath.Append(FILE_PATH_LITERAL("chrome")), priority);
-
-  // Silently ignore request if cgroup directory doesn't exist.
-  if (!DirectoryExists(cgroup_directory))
-    return;
-
-  SetThreadCgroup(thread_id, cgroup_directory);
-}
-
-void SetThreadCgroupsForThreadPriority(PlatformThreadId thread_id,
-                                       ThreadPriority priority) {
-  FilePath cgroup_filepath(kCgroupDirectory);
-  SetThreadCgroupForThreadPriority(
-      thread_id, cgroup_filepath.Append(FILE_PATH_LITERAL("cpuset")), priority);
-  SetThreadCgroupForThreadPriority(
-      thread_id, cgroup_filepath.Append(FILE_PATH_LITERAL("schedtune")),
-      priority);
-}
-#endif
-}  // namespace
-
-namespace internal {
-
-namespace {
-#if !defined(OS_NACL)
-const struct sched_param kRealTimePrio = {8};
-#endif
-}  // namespace
-
-const ThreadPriorityToNiceValuePair kThreadPriorityToNiceValueMap[4] = {
-    {ThreadPriority::BACKGROUND, 10},
-    {ThreadPriority::NORMAL, 0},
-    {ThreadPriority::DISPLAY, -8},
-    {ThreadPriority::REALTIME_AUDIO, -10},
-};
-
-bool SetCurrentThreadPriorityForPlatform(ThreadPriority priority) {
-#if !defined(OS_NACL)
-  SetThreadCgroupsForThreadPriority(PlatformThread::CurrentId(), priority);
-  return priority == ThreadPriority::REALTIME_AUDIO &&
-         pthread_setschedparam(pthread_self(), SCHED_RR, &kRealTimePrio) == 0;
-#else
-  return false;
-#endif
-}
-
-bool GetCurrentThreadPriorityForPlatform(ThreadPriority* priority) {
-#if !defined(OS_NACL)
-  int maybe_sched_rr = 0;
-  struct sched_param maybe_realtime_prio = {0};
-  if (pthread_getschedparam(pthread_self(), &maybe_sched_rr,
-                            &maybe_realtime_prio) == 0 &&
-      maybe_sched_rr == SCHED_RR &&
-      maybe_realtime_prio.sched_priority == kRealTimePrio.sched_priority) {
-    *priority = ThreadPriority::REALTIME_AUDIO;
-    return true;
-  }
-#endif
-  return false;
-}
-
-}  // namespace internal
-
-// static
-void PlatformThread::SetName(const std::string& name) {
-  ThreadIdNameManager::GetInstance()->SetName(name);
-
-#if !defined(OS_NACL) && !defined(OS_AIX)
-  // On linux we can get the thread names to show up in the debugger by setting
-  // the process name for the LWP.  We don't want to do this for the main
-  // thread because that would rename the process, causing tools like killall
-  // to stop working.
-  if (PlatformThread::CurrentId() == getpid())
-    return;
-
-  // http://0pointer.de/blog/projects/name-your-threads.html
-  // Set the name for the LWP (which gets truncated to 15 characters).
-  // Note that glibc also has a 'pthread_setname_np' api, but it may not be
-  // available everywhere and it's only benefit over using prctl directly is
-  // that it can set the name of threads other than the current thread.
-  int err = prctl(PR_SET_NAME, name.c_str());
-  // We expect EPERM failures in sandboxed processes, just ignore those.
-  if (err < 0 && errno != EPERM)
-    DPLOG(ERROR) << "prctl(PR_SET_NAME)";
-#endif  //  !defined(OS_NACL) && !defined(OS_AIX)
-}
-
-#if !defined(OS_NACL) && !defined(OS_AIX)
-// static
-void PlatformThread::SetThreadPriority(PlatformThreadId thread_id,
-                                       ThreadPriority priority) {
-  // Changing current main threads' priority is not permitted in favor of
-  // security, this interface is restricted to change only non-main thread
-  // priority.
-  CHECK_NE(thread_id, getpid());
-
-  SetThreadCgroupsForThreadPriority(thread_id, priority);
-
-  const int nice_setting = internal::ThreadPriorityToNiceValue(priority);
-  setpriority(PRIO_PROCESS, thread_id, nice_setting);
-}
-#endif  //  !defined(OS_NACL) && !defined(OS_AIX)
 
 void InitThreading() {}
 
diff --git a/base/threading/platform_thread_mac.mm b/base/threading/platform_thread_mac.mm
index 9df7f45..8174dba 100644
--- a/base/threading/platform_thread_mac.mm
+++ b/base/threading/platform_thread_mac.mm
@@ -13,11 +13,9 @@
 
 #include <algorithm>
 
-#include "base/lazy_instance.h"
 #include "base/logging.h"
 #include "base/mac/foundation_util.h"
 #include "base/mac/mach_logging.h"
-#include "base/threading/thread_id_name_manager.h"
 #include "build_config.h"
 
 namespace base {
@@ -47,154 +45,6 @@
   }
 }
 
-// static
-void PlatformThread::SetName(const std::string& name) {
-  ThreadIdNameManager::GetInstance()->SetName(name);
-
-  // Mac OS X does not expose the length limit of the name, so
-  // hardcode it.
-  const int kMaxNameLength = 63;
-  std::string shortened_name = name.substr(0, kMaxNameLength);
-  // pthread_setname() fails (harmlessly) in the sandbox, ignore when it does.
-  // See http://crbug.com/47058
-  pthread_setname_np(shortened_name.c_str());
-}
-
-namespace {
-
-// Enables time-contraint policy and priority suitable for low-latency,
-// glitch-resistant audio.
-void SetPriorityRealtimeAudio() {
-  // Increase thread priority to real-time.
-
-  // Please note that the thread_policy_set() calls may fail in
-  // rare cases if the kernel decides the system is under heavy load
-  // and is unable to handle boosting the thread priority.
-  // In these cases we just return early and go on with life.
-
-  mach_port_t mach_thread_id =
-      pthread_mach_thread_np(PlatformThread::CurrentHandle().platform_handle());
-
-  // Make thread fixed priority.
-  thread_extended_policy_data_t policy;
-  policy.timeshare = 0;  // Set to 1 for a non-fixed thread.
-  kern_return_t result =
-      thread_policy_set(mach_thread_id,
-                        THREAD_EXTENDED_POLICY,
-                        reinterpret_cast<thread_policy_t>(&policy),
-                        THREAD_EXTENDED_POLICY_COUNT);
-  if (result != KERN_SUCCESS) {
-    return;
-  }
-
-  // Set to relatively high priority.
-  thread_precedence_policy_data_t precedence;
-  precedence.importance = 63;
-  result = thread_policy_set(mach_thread_id,
-                             THREAD_PRECEDENCE_POLICY,
-                             reinterpret_cast<thread_policy_t>(&precedence),
-                             THREAD_PRECEDENCE_POLICY_COUNT);
-  if (result != KERN_SUCCESS) {
-    return;
-  }
-
-  // Most important, set real-time constraints.
-
-  // Define the guaranteed and max fraction of time for the audio thread.
-  // These "duty cycle" values can range from 0 to 1.  A value of 0.5
-  // means the scheduler would give half the time to the thread.
-  // These values have empirically been found to yield good behavior.
-  // Good means that audio performance is high and other threads won't starve.
-  const double kGuaranteedAudioDutyCycle = 0.75;
-  const double kMaxAudioDutyCycle = 0.85;
-
-  // Define constants determining how much time the audio thread can
-  // use in a given time quantum.  All times are in milliseconds.
-
-  // About 128 frames @44.1KHz
-  const double kTimeQuantum = 2.9;
-
-  // Time guaranteed each quantum.
-  const double kAudioTimeNeeded = kGuaranteedAudioDutyCycle * kTimeQuantum;
-
-  // Maximum time each quantum.
-  const double kMaxTimeAllowed = kMaxAudioDutyCycle * kTimeQuantum;
-
-  // Get the conversion factor from milliseconds to absolute time
-  // which is what the time-constraints call needs.
-  mach_timebase_info_data_t tb_info;
-  mach_timebase_info(&tb_info);
-  double ms_to_abs_time =
-      (static_cast<double>(tb_info.denom) / tb_info.numer) * 1000000;
-
-  thread_time_constraint_policy_data_t time_constraints;
-  time_constraints.period = kTimeQuantum * ms_to_abs_time;
-  time_constraints.computation = kAudioTimeNeeded * ms_to_abs_time;
-  time_constraints.constraint = kMaxTimeAllowed * ms_to_abs_time;
-  time_constraints.preemptible = 0;
-
-  result =
-      thread_policy_set(mach_thread_id,
-                        THREAD_TIME_CONSTRAINT_POLICY,
-                        reinterpret_cast<thread_policy_t>(&time_constraints),
-                        THREAD_TIME_CONSTRAINT_POLICY_COUNT);
-  return;
-}
-
-}  // anonymous namespace
-
-// static
-bool PlatformThread::CanIncreaseCurrentThreadPriority() {
-  return true;
-}
-
-// static
-void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority) {
-  // Changing the priority of the main thread causes performance regressions.
-  // https://crbug.com/601270
-  DCHECK(![[NSThread currentThread] isMainThread]);
-
-  switch (priority) {
-    case ThreadPriority::BACKGROUND:
-      [[NSThread currentThread] setThreadPriority:0];
-      break;
-    case ThreadPriority::NORMAL:
-    case ThreadPriority::DISPLAY:
-      [[NSThread currentThread] setThreadPriority:0.5];
-      break;
-    case ThreadPriority::REALTIME_AUDIO:
-      SetPriorityRealtimeAudio();
-      DCHECK_EQ([[NSThread currentThread] threadPriority], 1.0);
-      break;
-  }
-
-  [[[NSThread currentThread] threadDictionary]
-      setObject:@(static_cast<int>(priority))
-         forKey:kThreadPriorityKey];
-}
-
-// static
-ThreadPriority PlatformThread::GetCurrentThreadPriority() {
-  NSNumber* priority = base::mac::ObjCCast<NSNumber>([[[NSThread currentThread]
-      threadDictionary] objectForKey:kThreadPriorityKey]);
-
-  if (!priority)
-    return ThreadPriority::NORMAL;
-
-  ThreadPriority thread_priority =
-      static_cast<ThreadPriority>(priority.intValue);
-  switch (thread_priority) {
-    case ThreadPriority::BACKGROUND:
-    case ThreadPriority::NORMAL:
-    case ThreadPriority::DISPLAY:
-    case ThreadPriority::REALTIME_AUDIO:
-      return thread_priority;
-    default:
-      NOTREACHED() << "Unknown priority.";
-      return ThreadPriority::NORMAL;
-  }
-}
-
 size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes) {
 #if defined(OS_IOS)
   return 0;
diff --git a/base/threading/platform_thread_posix.cc b/base/threading/platform_thread_posix.cc
index 372442f..ce47a30 100644
--- a/base/threading/platform_thread_posix.cc
+++ b/base/threading/platform_thread_posix.cc
@@ -15,11 +15,7 @@
 
 #include <memory>
 
-#include "base/lazy_instance.h"
 #include "base/logging.h"
-#include "base/threading/platform_thread_internal_posix.h"
-#include "base/threading/thread_id_name_manager.h"
-#include "base/threading/thread_restrictions.h"
 #include "build_config.h"
 
 #if defined(OS_LINUX)
@@ -41,12 +37,10 @@
 namespace {
 
 struct ThreadParams {
-  ThreadParams()
-      : delegate(nullptr), joinable(false), priority(ThreadPriority::NORMAL) {}
+  ThreadParams() : delegate(nullptr), joinable(false) {}
 
   PlatformThread::Delegate* delegate;
   bool joinable;
-  ThreadPriority priority;
 };
 
 void* ThreadFunc(void* params) {
@@ -57,27 +51,10 @@
         static_cast<ThreadParams*>(params));
 
     delegate = thread_params->delegate;
-    if (!thread_params->joinable)
-      base::ThreadRestrictions::SetSingletonAllowed(false);
-
-#if !defined(OS_NACL)
-    // Threads on linux/android may inherit their priority from the thread
-    // where they were created. This explicitly sets the priority of all new
-    // threads.
-    PlatformThread::SetCurrentThreadPriority(thread_params->priority);
-#endif
   }
 
-  ThreadIdNameManager::GetInstance()->RegisterThread(
-      PlatformThread::CurrentHandle().platform_handle(),
-      PlatformThread::CurrentId());
-
   delegate->ThreadMain();
 
-  ThreadIdNameManager::GetInstance()->RemoveName(
-      PlatformThread::CurrentHandle().platform_handle(),
-      PlatformThread::CurrentId());
-
   base::TerminateOnThread();
   return nullptr;
 }
@@ -85,8 +62,7 @@
 bool CreateThread(size_t stack_size,
                   bool joinable,
                   PlatformThread::Delegate* delegate,
-                  PlatformThreadHandle* thread_handle,
-                  ThreadPriority priority) {
+                  PlatformThreadHandle* thread_handle) {
   DCHECK(thread_handle);
   base::InitThreading();
 
@@ -108,7 +84,6 @@
   std::unique_ptr<ThreadParams> params(new ThreadParams);
   params->delegate = delegate;
   params->joinable = joinable;
-  params->priority = priority;
 
   pthread_t handle;
   int err = pthread_create(&handle, &attributes, ThreadFunc, params.get());
@@ -188,41 +163,24 @@
 }
 
 // static
-const char* PlatformThread::GetName() {
-  return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
-}
-
-// static
-bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate,
-                                        PlatformThreadHandle* thread_handle,
-                                        ThreadPriority priority) {
+bool PlatformThread::Create(size_t stack_size,
+                            Delegate* delegate,
+                            PlatformThreadHandle* thread_handle) {
   return CreateThread(stack_size, true /* joinable thread */, delegate,
-                      thread_handle, priority);
+                      thread_handle);
 }
 
 // static
 bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
-  return CreateNonJoinableWithPriority(stack_size, delegate,
-                                       ThreadPriority::NORMAL);
-}
-
-// static
-bool PlatformThread::CreateNonJoinableWithPriority(size_t stack_size,
-                                                   Delegate* delegate,
-                                                   ThreadPriority priority) {
   PlatformThreadHandle unused;
 
   bool result = CreateThread(stack_size, false /* non-joinable thread */,
-                             delegate, &unused, priority);
+                             delegate, &unused);
   return result;
 }
 
 // static
 void PlatformThread::Join(PlatformThreadHandle thread_handle) {
-  // Joining another thread may block the current thread for a long time, since
-  // the thread referred to by |thread_handle| may still be running long-lived /
-  // blocking tasks.
-  AssertBlockingAllowed();
   CHECK_EQ(0, pthread_join(thread_handle.platform_handle(), nullptr));
 }
 
@@ -231,66 +189,4 @@
   CHECK_EQ(0, pthread_detach(thread_handle.platform_handle()));
 }
 
-// Mac and Fuchsia have their own Set/GetCurrentThreadPriority()
-// implementations.
-#if !defined(OS_MACOSX) && !defined(OS_FUCHSIA)
-
-// static
-bool PlatformThread::CanIncreaseCurrentThreadPriority() {
-#if defined(OS_NACL)
-  return false;
-#else
-  // Only root can raise thread priority on POSIX environment. On Linux, users
-  // who have CAP_SYS_NICE permission also can raise the thread priority, but
-  // libcap.so would be needed to check the capability.
-  return geteuid() == 0;
-#endif  // defined(OS_NACL)
-}
-
-// static
-void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority) {
-#if defined(OS_NACL)
-  NOTIMPLEMENTED();
-#else
-  if (internal::SetCurrentThreadPriorityForPlatform(priority))
-    return;
-
-  // setpriority(2) should change the whole thread group's (i.e. process)
-  // priority. However, as stated in the bugs section of
-  // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current
-  // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread
-  // attribute". Also, 0 is prefered to the current thread id since it is
-  // equivalent but makes sandboxing easier (https://crbug.com/399473).
-  const int nice_setting = internal::ThreadPriorityToNiceValue(priority);
-  setpriority(PRIO_PROCESS, 0, nice_setting);
-#endif  // defined(OS_NACL)
-}
-
-// static
-ThreadPriority PlatformThread::GetCurrentThreadPriority() {
-#if defined(OS_NACL)
-  NOTIMPLEMENTED();
-  return ThreadPriority::NORMAL;
-#else
-  // Mirrors SetCurrentThreadPriority()'s implementation.
-  ThreadPriority platform_specific_priority;
-  if (internal::GetCurrentThreadPriorityForPlatform(
-          &platform_specific_priority)) {
-    return platform_specific_priority;
-  }
-
-  // Need to clear errno before calling getpriority():
-  // http://man7.org/linux/man-pages/man2/getpriority.2.html
-  errno = 0;
-  int nice_value = getpriority(PRIO_PROCESS, 0);
-  if (errno != 0) {
-    return ThreadPriority::NORMAL;
-  }
-
-  return internal::NiceValueToThreadPriority(nice_value);
-#endif  // !defined(OS_NACL)
-}
-
-#endif  // !defined(OS_MACOSX) && !defined(OS_FUCHSIA)
-
 }  // namespace base
diff --git a/base/threading/platform_thread_win.cc b/base/threading/platform_thread_win.cc
index 9b72bd5..9efc951 100644
--- a/base/threading/platform_thread_win.cc
+++ b/base/threading/platform_thread_win.cc
@@ -8,8 +8,6 @@
 
 #include "base/logging.h"
 #include "base/strings/utf_string_conversions.h"
-#include "base/threading/thread_id_name_manager.h"
-#include "base/threading/thread_restrictions.h"
 #include "base/win/scoped_handle.h"
 
 #include <windows.h>
@@ -51,17 +49,11 @@
 struct ThreadParams {
   PlatformThread::Delegate* delegate;
   bool joinable;
-  ThreadPriority priority;
 };
 
 DWORD __stdcall ThreadFunc(void* params) {
   ThreadParams* thread_params = static_cast<ThreadParams*>(params);
   PlatformThread::Delegate* delegate = thread_params->delegate;
-  if (!thread_params->joinable)
-    base::ThreadRestrictions::SetSingletonAllowed(false);
-
-  if (thread_params->priority != ThreadPriority::NORMAL)
-    PlatformThread::SetCurrentThreadPriority(thread_params->priority);
 
   // Retrieve a copy of the thread handle to use as the key in the
   // thread name mapping.
@@ -78,20 +70,11 @@
 
   if (did_dup) {
     scoped_platform_handle.Set(platform_handle);
-    ThreadIdNameManager::GetInstance()->RegisterThread(
-        scoped_platform_handle.Get(),
-        PlatformThread::CurrentId());
   }
 
   delete thread_params;
   delegate->ThreadMain();
 
-  if (did_dup) {
-    ThreadIdNameManager::GetInstance()->RemoveName(
-        scoped_platform_handle.Get(),
-        PlatformThread::CurrentId());
-  }
-
   return 0;
 }
 
@@ -100,8 +83,7 @@
 // is created.
 bool CreateThreadInternal(size_t stack_size,
                           PlatformThread::Delegate* delegate,
-                          PlatformThreadHandle* out_thread_handle,
-                          ThreadPriority priority) {
+                          PlatformThreadHandle* out_thread_handle) {
   unsigned int flags = 0;
   if (stack_size > 0) {
     flags = STACK_SIZE_PARAM_IS_A_RESERVATION;
@@ -110,7 +92,6 @@
   ThreadParams* params = new ThreadParams;
   params->delegate = delegate;
   params->joinable = out_thread_handle != nullptr;
-  params->priority = priority;
 
   void* thread_handle;
   {
@@ -168,51 +149,17 @@
 }
 
 // static
-void PlatformThread::SetName(const std::string& name) {
-  ThreadIdNameManager::GetInstance()->SetName(name);
-
-  // The SetThreadDescription API works even if no debugger is attached.
-  auto set_thread_description_func =
-      reinterpret_cast<SetThreadDescription>(::GetProcAddress(
-          ::GetModuleHandle(L"Kernel32.dll"), "SetThreadDescription"));
-  if (set_thread_description_func) {
-    set_thread_description_func(::GetCurrentThread(),
-                                base::UTF8ToWide(name).c_str());
-  }
-
-  // The debugger needs to be around to catch the name in the exception.  If
-  // there isn't a debugger, we are just needlessly throwing an exception.
-  if (!::IsDebuggerPresent())
-    return;
-
-  SetNameInternal(CurrentId(), name.c_str());
-}
-
-// static
-const char* PlatformThread::GetName() {
-  return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
-}
-
-// static
-bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate,
-                                        PlatformThreadHandle* thread_handle,
-                                        ThreadPriority priority) {
+bool PlatformThread::Create(size_t stack_size,
+                            Delegate* delegate,
+                            PlatformThreadHandle* thread_handle) {
   DCHECK(thread_handle);
-  return CreateThreadInternal(stack_size, delegate, thread_handle, priority);
+  return CreateThreadInternal(stack_size, delegate, thread_handle);
 }
 
 // static
 bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
-  return CreateNonJoinableWithPriority(stack_size, delegate,
-                                       ThreadPriority::NORMAL);
-}
-
-// static
-bool PlatformThread::CreateNonJoinableWithPriority(size_t stack_size,
-                                                   Delegate* delegate,
-                                                   ThreadPriority priority) {
-  return CreateThreadInternal(stack_size, delegate, nullptr /* non-joinable */,
-                              priority);
+  return CreateThreadInternal(stack_size, delegate, nullptr /* non-joinable */
+                              );
 }
 
 // static
@@ -243,62 +190,4 @@
   CloseHandle(thread_handle.platform_handle());
 }
 
-// static
-bool PlatformThread::CanIncreaseCurrentThreadPriority() {
-  return true;
-}
-
-// static
-void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority) {
-  int desired_priority = THREAD_PRIORITY_ERROR_RETURN;
-  switch (priority) {
-    case ThreadPriority::BACKGROUND:
-      desired_priority = THREAD_PRIORITY_LOWEST;
-      break;
-    case ThreadPriority::NORMAL:
-      desired_priority = THREAD_PRIORITY_NORMAL;
-      break;
-    case ThreadPriority::DISPLAY:
-      desired_priority = THREAD_PRIORITY_ABOVE_NORMAL;
-      break;
-    case ThreadPriority::REALTIME_AUDIO:
-      desired_priority = THREAD_PRIORITY_TIME_CRITICAL;
-      break;
-    default:
-      NOTREACHED() << "Unknown priority.";
-      break;
-  }
-  DCHECK_NE(desired_priority, THREAD_PRIORITY_ERROR_RETURN);
-
-#if DCHECK_IS_ON()
-  const BOOL success =
-#endif
-      ::SetThreadPriority(PlatformThread::CurrentHandle().platform_handle(),
-                          desired_priority);
-  DPLOG_IF(ERROR, !success) << "Failed to set thread priority to "
-                            << desired_priority;
-}
-
-// static
-ThreadPriority PlatformThread::GetCurrentThreadPriority() {
-  int priority =
-      ::GetThreadPriority(PlatformThread::CurrentHandle().platform_handle());
-  switch (priority) {
-    case THREAD_PRIORITY_LOWEST:
-      return ThreadPriority::BACKGROUND;
-    case THREAD_PRIORITY_NORMAL:
-      return ThreadPriority::NORMAL;
-    case THREAD_PRIORITY_ABOVE_NORMAL:
-      return ThreadPriority::DISPLAY;
-    case THREAD_PRIORITY_TIME_CRITICAL:
-      return ThreadPriority::REALTIME_AUDIO;
-    case THREAD_PRIORITY_ERROR_RETURN:
-      DPCHECK(false) << "GetThreadPriority error";
-      FALLTHROUGH;
-    default:
-      NOTREACHED() << "Unexpected priority: " << priority;
-      return ThreadPriority::NORMAL;
-  }
-}
-
 }  // namespace base
diff --git a/base/threading/post_task_and_reply_impl.cc b/base/threading/post_task_and_reply_impl.cc
deleted file mode 100644
index 83c9dcb..0000000
--- a/base/threading/post_task_and_reply_impl.cc
+++ /dev/null
@@ -1,125 +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 "base/threading/post_task_and_reply_impl.h"
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/logging.h"
-#include "base/memory/ref_counted.h"
-#include "base/sequenced_task_runner.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-
-namespace base {
-
-namespace {
-
-class PostTaskAndReplyRelay {
- public:
-  PostTaskAndReplyRelay(const Location& from_here,
-                        OnceClosure task,
-                        OnceClosure reply)
-      : from_here_(from_here),
-        task_(std::move(task)),
-        reply_(std::move(reply)) {}
-  PostTaskAndReplyRelay(PostTaskAndReplyRelay&&) = default;
-
-  ~PostTaskAndReplyRelay() {
-    if (reply_) {
-      // This can run:
-      // 1) On origin sequence, when:
-      //    1a) Posting |task_| fails.
-      //    1b) |reply_| is cancelled before running.
-      //    1c) The DeleteSoon() below is scheduled.
-      // 2) On destination sequence, when:
-      //    2a) |task_| is cancelled before running.
-      //    2b) Posting |reply_| fails.
-
-      if (!reply_task_runner_->RunsTasksInCurrentSequence()) {
-        // Case 2a) or 2b).
-        //
-        // Destroy callbacks asynchronously on |reply_task_runner| since their
-        // destructors can rightfully be affine to it. As always, DeleteSoon()
-        // might leak its argument if the target execution environment is
-        // shutdown (e.g. MessageLoop deleted, TaskScheduler shutdown).
-        //
-        // Note: while it's obvious why |reply_| can be affine to
-        // |reply_task_runner|, the reason that |task_| can also be affine to it
-        // is that it if neither tasks ran, |task_| may still hold an object
-        // which was intended to be moved to |reply_| when |task_| ran (such an
-        // object's destruction can be affine to |reply_task_runner_| -- e.g.
-        // https://crbug.com/829122).
-        auto relay_to_delete =
-            std::make_unique<PostTaskAndReplyRelay>(std::move(*this));
-        reply_task_runner_->DeleteSoon(from_here_, std::move(relay_to_delete));
-      }
-
-      // Case 1a), 1b), 1c).
-      //
-      // Callbacks will be destroyed synchronously at the end of this scope.
-    } else {
-      // This can run when both callbacks have run or have been moved to another
-      // PostTaskAndReplyRelay instance. If |reply_| is null, |task_| must be
-      // null too.
-      DCHECK(!task_);
-    }
-  }
-
-  // No assignment operator because of const members.
-  PostTaskAndReplyRelay& operator=(PostTaskAndReplyRelay&&) = delete;
-
-  // Static function is used because it is not possible to bind a method call to
-  // a non-pointer type.
-  static void RunTaskAndPostReply(PostTaskAndReplyRelay relay) {
-    DCHECK(relay.task_);
-    std::move(relay.task_).Run();
-
-    // Keep a reference to the reply TaskRunner for the PostTask() call before
-    // |relay| is moved into a callback.
-    scoped_refptr<SequencedTaskRunner> reply_task_runner =
-        relay.reply_task_runner_;
-
-    reply_task_runner->PostTask(
-        relay.from_here_,
-        BindOnce(&PostTaskAndReplyRelay::RunReply, std::move(relay)));
-  }
-
- private:
-  // Static function is used because it is not possible to bind a method call to
-  // a non-pointer type.
-  static void RunReply(PostTaskAndReplyRelay relay) {
-    DCHECK(!relay.task_);
-    DCHECK(relay.reply_);
-    std::move(relay.reply_).Run();
-  }
-
-  const Location from_here_;
-  OnceClosure task_;
-  OnceClosure reply_;
-  const scoped_refptr<SequencedTaskRunner> reply_task_runner_ =
-      SequencedTaskRunnerHandle::Get();
-
-  DISALLOW_COPY_AND_ASSIGN(PostTaskAndReplyRelay);
-};
-
-}  // namespace
-
-namespace internal {
-
-bool PostTaskAndReplyImpl::PostTaskAndReply(const Location& from_here,
-                                            OnceClosure task,
-                                            OnceClosure reply) {
-  DCHECK(task) << from_here.ToString();
-  DCHECK(reply) << from_here.ToString();
-
-  return PostTask(from_here,
-                  BindOnce(&PostTaskAndReplyRelay::RunTaskAndPostReply,
-                           PostTaskAndReplyRelay(from_here, std::move(task),
-                                                 std::move(reply))));
-}
-
-}  // namespace internal
-
-}  // namespace base
diff --git a/base/threading/post_task_and_reply_impl.h b/base/threading/post_task_and_reply_impl.h
deleted file mode 100644
index 54038ce..0000000
--- a/base/threading/post_task_and_reply_impl.h
+++ /dev/null
@@ -1,46 +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.
-
-// This file contains the implementation for TaskRunner::PostTaskAndReply.
-
-#ifndef BASE_THREADING_POST_TASK_AND_REPLY_IMPL_H_
-#define BASE_THREADING_POST_TASK_AND_REPLY_IMPL_H_
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/location.h"
-
-namespace base {
-namespace internal {
-
-// Inherit from this in a class that implements PostTask to send a task to a
-// custom execution context.
-//
-// If you're looking for a concrete implementation of PostTaskAndReply, you
-// probably want base::TaskRunner or base/task_scheduler/post_task.h
-class BASE_EXPORT PostTaskAndReplyImpl {
- public:
-  virtual ~PostTaskAndReplyImpl() = default;
-
-  // Posts |task| by calling PostTask(). On completion, posts |reply| to the
-  // origin sequence. Can only be called when
-  // SequencedTaskRunnerHandle::IsSet(). Each callback is deleted synchronously
-  // after running, or scheduled for asynchronous deletion on the origin
-  // sequence if it can't run (e.g. if a TaskRunner skips it on shutdown). See
-  // SequencedTaskRunner::DeleteSoon() for when objects scheduled for
-  // asynchronous deletion can be leaked. Note: All //base task posting APIs
-  // require callbacks to support deletion on the posting sequence if they can't
-  // be scheduled.
-  bool PostTaskAndReply(const Location& from_here,
-                        OnceClosure task,
-                        OnceClosure reply);
-
- private:
-  virtual bool PostTask(const Location& from_here, OnceClosure task) = 0;
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_THREADING_POST_TASK_AND_REPLY_IMPL_H_
diff --git a/base/threading/scoped_blocking_call.cc b/base/threading/scoped_blocking_call.cc
deleted file mode 100644
index 1d2931c..0000000
--- a/base/threading/scoped_blocking_call.cc
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright 2017 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/threading/scoped_blocking_call.h"
-
-#include "base/lazy_instance.h"
-#include "base/threading/thread_local.h"
-
-namespace base {
-
-namespace {
-
-LazyInstance<ThreadLocalPointer<internal::BlockingObserver>>::Leaky
-    tls_blocking_observer = LAZY_INSTANCE_INITIALIZER;
-
-// Last ScopedBlockingCall instantiated on this thread.
-LazyInstance<ThreadLocalPointer<ScopedBlockingCall>>::Leaky
-    tls_last_scoped_blocking_call = LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace
-
-ScopedBlockingCall::ScopedBlockingCall(BlockingType blocking_type)
-    : blocking_observer_(tls_blocking_observer.Get().Get()),
-      previous_scoped_blocking_call_(tls_last_scoped_blocking_call.Get().Get()),
-      is_will_block_(blocking_type == BlockingType::WILL_BLOCK ||
-                     (previous_scoped_blocking_call_ &&
-                      previous_scoped_blocking_call_->is_will_block_)) {
-  tls_last_scoped_blocking_call.Get().Set(this);
-
-  if (blocking_observer_) {
-    if (!previous_scoped_blocking_call_) {
-      blocking_observer_->BlockingStarted(blocking_type);
-    } else if (blocking_type == BlockingType::WILL_BLOCK &&
-               !previous_scoped_blocking_call_->is_will_block_) {
-      blocking_observer_->BlockingTypeUpgraded();
-    }
-  }
-}
-
-ScopedBlockingCall::~ScopedBlockingCall() {
-  DCHECK_EQ(this, tls_last_scoped_blocking_call.Get().Get());
-  tls_last_scoped_blocking_call.Get().Set(previous_scoped_blocking_call_);
-  if (blocking_observer_ && !previous_scoped_blocking_call_)
-    blocking_observer_->BlockingEnded();
-}
-
-namespace internal {
-
-void SetBlockingObserverForCurrentThread(BlockingObserver* blocking_observer) {
-  DCHECK(!tls_blocking_observer.Get().Get());
-  tls_blocking_observer.Get().Set(blocking_observer);
-}
-
-void ClearBlockingObserverForTesting() {
-  tls_blocking_observer.Get().Set(nullptr);
-}
-
-ScopedClearBlockingObserverForTesting::ScopedClearBlockingObserverForTesting()
-    : blocking_observer_(tls_blocking_observer.Get().Get()) {
-  tls_blocking_observer.Get().Set(nullptr);
-}
-
-ScopedClearBlockingObserverForTesting::
-    ~ScopedClearBlockingObserverForTesting() {
-  DCHECK(!tls_blocking_observer.Get().Get());
-  tls_blocking_observer.Get().Set(blocking_observer_);
-}
-
-}  // namespace internal
-
-}  // namespace base
diff --git a/base/threading/scoped_blocking_call.h b/base/threading/scoped_blocking_call.h
deleted file mode 100644
index e376c30..0000000
--- a/base/threading/scoped_blocking_call.h
+++ /dev/null
@@ -1,140 +0,0 @@
-// Copyright 2017 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_THREADING_SCOPED_BLOCKING_CALL_H
-#define BASE_THREADING_SCOPED_BLOCKING_CALL_H
-
-#include "base/base_export.h"
-#include "base/logging.h"
-
-namespace base {
-
-// BlockingType indicates the likelihood that a blocking call will actually
-// block.
-enum class BlockingType {
-  // The call might block (e.g. file I/O that might hit in memory cache).
-  MAY_BLOCK,
-  // The call will definitely block (e.g. cache already checked and now pinging
-  // server synchronously).
-  WILL_BLOCK
-};
-
-namespace internal {
-class BlockingObserver;
-}
-
-// This class must be instantiated in every scope where a blocking call is made.
-// CPU usage should be minimal within that scope. //base APIs that block
-// instantiate their own ScopedBlockingCall; it is not necessary to instantiate
-// another ScopedBlockingCall in the scope where these APIs are used.
-//
-// Good:
-//   Data data;
-//   {
-//     ScopedBlockingCall scoped_blocking_call(BlockingType::WILL_BLOCK);
-//     data = GetDataFromNetwork();
-//   }
-//   CPUIntensiveProcessing(data);
-//
-// Bad:
-//   ScopedBlockingCall scoped_blocking_call(BlockingType::WILL_BLOCK);
-//   Data data = GetDataFromNetwork();
-//   CPUIntensiveProcessing(data);  // CPU usage within a ScopedBlockingCall.
-//
-// Good:
-//   Data a;
-//   Data b;
-//   {
-//     ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
-//     a = GetDataFromMemoryCacheOrNetwork();
-//     b = GetDataFromMemoryCacheOrNetwork();
-//   }
-//   CPUIntensiveProcessing(a);
-//   CPUIntensiveProcessing(b);
-//
-// Bad:
-//   ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
-//   Data a = GetDataFromMemoryCacheOrNetwork();
-//   Data b = GetDataFromMemoryCacheOrNetwork();
-//   CPUIntensiveProcessing(a);  // CPU usage within a ScopedBlockingCall.
-//   CPUIntensiveProcessing(b);  // CPU usage within a ScopedBlockingCall.
-//
-// Good:
-//   base::WaitableEvent waitable_event(...);
-//   waitable_event.Wait();
-//
-// Bad:
-//  base::WaitableEvent waitable_event(...);
-//  ScopedBlockingCall scoped_blocking_call(BlockingType::WILL_BLOCK);
-//  waitable_event.Wait();  // Wait() instantiates its own ScopedBlockingCall.
-//
-// When a ScopedBlockingCall is instantiated from a TaskScheduler parallel or
-// sequenced task, the thread pool size is incremented to compensate for the
-// blocked thread (more or less aggressively depending on BlockingType).
-class BASE_EXPORT ScopedBlockingCall {
- public:
-  ScopedBlockingCall(BlockingType blocking_type);
-  ~ScopedBlockingCall();
-
- private:
-  internal::BlockingObserver* const blocking_observer_;
-
-  // Previous ScopedBlockingCall instantiated on this thread.
-  ScopedBlockingCall* const previous_scoped_blocking_call_;
-
-  // Whether the BlockingType of the current thread was WILL_BLOCK after this
-  // ScopedBlockingCall was instantiated.
-  const bool is_will_block_;
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedBlockingCall);
-};
-
-namespace internal {
-
-// Interface for an observer to be informed when a thread enters or exits
-// the scope of ScopedBlockingCall objects.
-class BASE_EXPORT BlockingObserver {
- public:
-  virtual ~BlockingObserver() = default;
-
-  // Invoked when a ScopedBlockingCall is instantiated on the observed thread
-  // where there wasn't an existing ScopedBlockingCall.
-  virtual void BlockingStarted(BlockingType blocking_type) = 0;
-
-  // Invoked when a WILL_BLOCK ScopedBlockingCall is instantiated on the
-  // observed thread where there was a MAY_BLOCK ScopedBlockingCall but not a
-  // WILL_BLOCK ScopedBlockingCall.
-  virtual void BlockingTypeUpgraded() = 0;
-
-  // Invoked when the last ScopedBlockingCall on the observed thread is
-  // destroyed.
-  virtual void BlockingEnded() = 0;
-};
-
-// Registers |blocking_observer| on the current thread. It is invalid to call
-// this on a thread where there is an active ScopedBlockingCall.
-BASE_EXPORT void SetBlockingObserverForCurrentThread(
-    BlockingObserver* blocking_observer);
-
-BASE_EXPORT void ClearBlockingObserverForTesting();
-
-// Unregisters the |blocking_observer| on the current thread within its scope.
-// Used in TaskScheduler tests to prevent calls to //base sync primitives from
-// affecting the thread pool capacity.
-class BASE_EXPORT ScopedClearBlockingObserverForTesting {
- public:
-  ScopedClearBlockingObserverForTesting();
-  ~ScopedClearBlockingObserverForTesting();
-
- private:
-  BlockingObserver* const blocking_observer_;
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedClearBlockingObserverForTesting);
-};
-
-}  // namespace internal
-
-}  // namespace base
-
-#endif  // BASE_THREADING_SCOPED_BLOCKING_CALL_H
diff --git a/base/threading/sequence_local_storage_map.cc b/base/threading/sequence_local_storage_map.cc
deleted file mode 100644
index 2837aa0..0000000
--- a/base/threading/sequence_local_storage_map.cc
+++ /dev/null
@@ -1,105 +0,0 @@
-// Copyright 2017 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/threading/sequence_local_storage_map.h"
-
-#include <utility>
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/threading/thread_local.h"
-
-namespace base {
-namespace internal {
-
-namespace {
-LazyInstance<ThreadLocalPointer<SequenceLocalStorageMap>>::Leaky
-    tls_current_sequence_local_storage = LAZY_INSTANCE_INITIALIZER;
-}  // namespace
-
-SequenceLocalStorageMap::SequenceLocalStorageMap() = default;
-
-SequenceLocalStorageMap::~SequenceLocalStorageMap() = default;
-
-ScopedSetSequenceLocalStorageMapForCurrentThread::
-    ScopedSetSequenceLocalStorageMapForCurrentThread(
-        SequenceLocalStorageMap* sequence_local_storage) {
-  DCHECK(!tls_current_sequence_local_storage.Get().Get());
-  tls_current_sequence_local_storage.Get().Set(sequence_local_storage);
-}
-
-ScopedSetSequenceLocalStorageMapForCurrentThread::
-    ~ScopedSetSequenceLocalStorageMapForCurrentThread() {
-  tls_current_sequence_local_storage.Get().Set(nullptr);
-}
-
-SequenceLocalStorageMap& SequenceLocalStorageMap::GetForCurrentThread() {
-  SequenceLocalStorageMap* current_sequence_local_storage =
-      tls_current_sequence_local_storage.Get().Get();
-
-  DCHECK(current_sequence_local_storage)
-      << "SequenceLocalStorageSlot cannot be used because no "
-         "SequenceLocalStorageMap was stored in TLS. Use "
-         "ScopedSetSequenceLocalStorageMapForCurrentThread to store a "
-         "SequenceLocalStorageMap object in TLS.";
-
-  return *current_sequence_local_storage;
-}
-
-void* SequenceLocalStorageMap::Get(int slot_id) {
-  const auto it = sls_map_.find(slot_id);
-  if (it == sls_map_.end())
-    return nullptr;
-  return it->second.value();
-}
-
-void SequenceLocalStorageMap::Set(
-    int slot_id,
-    SequenceLocalStorageMap::ValueDestructorPair value_destructor_pair) {
-  auto it = sls_map_.find(slot_id);
-
-  if (it == sls_map_.end())
-    sls_map_.emplace(slot_id, std::move(value_destructor_pair));
-  else
-    it->second = std::move(value_destructor_pair);
-
-  // The maximum number of entries in the map is 256. This can be adjusted, but
-  // will require reviewing the choice of data structure for the map.
-  DCHECK_LE(sls_map_.size(), 256U);
-}
-
-SequenceLocalStorageMap::ValueDestructorPair::ValueDestructorPair(
-    void* value,
-    DestructorFunc* destructor)
-    : value_(value), destructor_(destructor) {}
-
-SequenceLocalStorageMap::ValueDestructorPair::~ValueDestructorPair() {
-  if (value_)
-    destructor_(value_);
-}
-
-SequenceLocalStorageMap::ValueDestructorPair::ValueDestructorPair(
-    ValueDestructorPair&& value_destructor_pair)
-    : value_(value_destructor_pair.value_),
-      destructor_(value_destructor_pair.destructor_) {
-  value_destructor_pair.value_ = nullptr;
-}
-
-SequenceLocalStorageMap::ValueDestructorPair&
-SequenceLocalStorageMap::ValueDestructorPair::operator=(
-    ValueDestructorPair&& value_destructor_pair) {
-  // Destroy |value_| before overwriting it with a new value.
-  if (value_)
-    destructor_(value_);
-
-  value_ = value_destructor_pair.value_;
-  destructor_ = value_destructor_pair.destructor_;
-
-  value_destructor_pair.value_ = nullptr;
-
-  return *this;
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/threading/sequence_local_storage_map.h b/base/threading/sequence_local_storage_map.h
deleted file mode 100644
index 8b9155c..0000000
--- a/base/threading/sequence_local_storage_map.h
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright 2017 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_THREADING_SEQUENCE_LOCAL_STORAGE_MAP_H_
-#define BASE_THREADING_SEQUENCE_LOCAL_STORAGE_MAP_H_
-
-#include "base/base_export.h"
-#include "base/containers/flat_map.h"
-#include "base/macros.h"
-
-namespace base {
-namespace internal {
-
-// A SequenceLocalStorageMap holds (slot_id) -> (value, destructor) items for a
-// sequence. When a task runs, it is expected that a pointer to its sequence's
-// SequenceLocalStorageMap is set in TLS using
-// ScopedSetSequenceMapLocalStorageForCurrentThread. When a
-// SequenceLocalStorageMap is destroyed, it invokes the destructors associated
-// with values stored within it.
-// The Get() and Set() methods should not be accessed directly.
-// Use SequenceLocalStorageSlot to Get() and Set() values in the current
-// sequence's SequenceLocalStorageMap.
-class BASE_EXPORT SequenceLocalStorageMap {
- public:
-  SequenceLocalStorageMap();
-  ~SequenceLocalStorageMap();
-
-  // Returns the SequenceLocalStorage bound to the current thread. It is invalid
-  // to call this outside the scope of a
-  // ScopedSetSequenceLocalStorageForCurrentThread.
-  static SequenceLocalStorageMap& GetForCurrentThread();
-
-  // Holds a pointer to a value alongside a destructor for this pointer.
-  // Calls the destructor on the value upon destruction.
-  class BASE_EXPORT ValueDestructorPair {
-   public:
-    using DestructorFunc = void(void*);
-
-    ValueDestructorPair(void* value, DestructorFunc* destructor);
-    ~ValueDestructorPair();
-
-    ValueDestructorPair(ValueDestructorPair&& value_destructor_pair);
-
-    ValueDestructorPair& operator=(ValueDestructorPair&& value_destructor_pair);
-
-    void* value() const { return value_; }
-
-   private:
-    void* value_;
-    DestructorFunc* destructor_;
-
-    DISALLOW_COPY_AND_ASSIGN(ValueDestructorPair);
-  };
-
-  // Returns the value stored in |slot_id| or nullptr if no value was stored.
-  void* Get(int slot_id);
-
-  // Stores |value_destructor_pair| in |slot_id|. Overwrites and destroys any
-  // previously stored value.
-  void Set(int slot_id, ValueDestructorPair value_destructor_pair);
-
- private:
-  // Map from slot id to ValueDestructorPair.
-  // flat_map was chosen because there are expected to be relatively few entries
-  // in the map. For low number of entries, flat_map is known to perform better
-  // than other map implementations.
-  base::flat_map<int, ValueDestructorPair> sls_map_;
-
-  DISALLOW_COPY_AND_ASSIGN(SequenceLocalStorageMap);
-};
-
-// Within the scope of this object,
-// SequenceLocalStorageMap::GetForCurrentThread() will return a reference to the
-// SequenceLocalStorageMap object passed to the constructor. There can be only
-// one ScopedSetSequenceLocalStorageMapForCurrentThread instance per scope.
-class BASE_EXPORT ScopedSetSequenceLocalStorageMapForCurrentThread {
- public:
-  ScopedSetSequenceLocalStorageMapForCurrentThread(
-      SequenceLocalStorageMap* sequence_local_storage);
-
-  ~ScopedSetSequenceLocalStorageMapForCurrentThread();
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(ScopedSetSequenceLocalStorageMapForCurrentThread);
-};
-}  // namespace internal
-}  // namespace base
-
-#endif  // BASE_THREADING_SEQUENCE_LOCAL_STORAGE_MAP_H_
diff --git a/base/threading/sequence_local_storage_slot.cc b/base/threading/sequence_local_storage_slot.cc
deleted file mode 100644
index b7db40b..0000000
--- a/base/threading/sequence_local_storage_slot.cc
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright 2017 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/threading/sequence_local_storage_slot.h"
-
-#include <limits>
-
-#include "base/atomic_sequence_num.h"
-#include "base/logging.h"
-
-namespace base {
-namespace internal {
-
-namespace {
-AtomicSequenceNumber g_sequence_local_storage_slot_generator;
-}  // namespace
-
-int GetNextSequenceLocalStorageSlotNumber() {
-  int slot_id = g_sequence_local_storage_slot_generator.GetNext();
-  DCHECK_LT(slot_id, std::numeric_limits<int>::max());
-  return slot_id;
-}
-
-}  // namespace internal
-}  // namespace base
diff --git a/base/threading/sequence_local_storage_slot.h b/base/threading/sequence_local_storage_slot.h
deleted file mode 100644
index 315df7d..0000000
--- a/base/threading/sequence_local_storage_slot.h
+++ /dev/null
@@ -1,105 +0,0 @@
-// Copyright 2017 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_THREADING_SEQUENCE_LOCAL_STORAGE_SLOT_H_
-#define BASE_THREADING_SEQUENCE_LOCAL_STORAGE_SLOT_H_
-
-#include <memory>
-#include <utility>
-
-#include "base/base_export.h"
-#include "base/threading/sequence_local_storage_map.h"
-
-namespace base {
-
-namespace internal {
-BASE_EXPORT int GetNextSequenceLocalStorageSlotNumber();
-}
-
-// SequenceLocalStorageSlot allows arbitrary values to be stored and retrieved
-// from a sequence. Values are deleted when the sequence is deleted.
-//
-// Example usage:
-//
-// namespace {
-// base::LazyInstance<SequenceLocalStorageSlot<int>> sls_value;
-// }
-//
-// void Read() {
-//   int value = sls_value.Get().Get();
-//   ...
-// }
-//
-// void Write() {
-//   sls_value.Get().Set(42);
-// }
-//
-// void PostTasks() {
-//   // Since Read() runs on the same sequence as Write(), it
-//   // will read the value "42". A Read() running on a different
-//   // sequence would not see that value.
-//   scoped_refptr<base::SequencedTaskRunner> task_runner = ...;
-//   task_runner->PostTask(FROM_HERE, base::BindOnce(&Write));
-//   task_runner->PostTask(FROM_HERE, base::BindOnce(&Read));
-// }
-//
-// SequenceLocalStorageSlot must be used within the scope of a
-// ScopedSetSequenceLocalStorageMapForCurrentThread object.
-// Note: this is true on all TaskScheduler workers and on threads bound to a
-// MessageLoop.
-template <typename T, typename Deleter = std::default_delete<T>>
-class SequenceLocalStorageSlot {
- public:
-  SequenceLocalStorageSlot()
-      : slot_id_(internal::GetNextSequenceLocalStorageSlotNumber()) {}
-  ~SequenceLocalStorageSlot() = default;
-
-  // Get the sequence-local value stored in this slot. Returns a
-  // default-constructed value if no value was previously set.
-  T& Get() {
-    void* value =
-        internal::SequenceLocalStorageMap::GetForCurrentThread().Get(slot_id_);
-
-    // Sets and returns a default-constructed value if no value was previously
-    // set.
-    if (!value) {
-      Set(T());
-      return Get();
-    }
-    return *(static_cast<T*>(value));
-  }
-
-  // Set this slot's sequence-local value to |value|.
-  // Note that if T is expensive to copy, it may be more appropriate to instead
-  // store a std::unique_ptr<T>. This is enforced by the
-  // DISALLOW_COPY_AND_ASSIGN style rather than directly by this class however.
-  void Set(T value) {
-    // Allocates the |value| with new rather than std::make_unique.
-    // Since SequenceLocalStorageMap needs to store values of various types
-    // within the same map, the type of value_destructor_pair.value is void*
-    // (std::unique_ptr<void> is invalid). Memory is freed by calling
-    // |value_destructor_pair.destructor| in the destructor of
-    // ValueDestructorPair which is invoked when the value is overwritten by
-    // another call to SequenceLocalStorageMap::Set or when the
-    // SequenceLocalStorageMap is deleted.
-    T* value_ptr = new T(std::move(value));
-
-    internal::SequenceLocalStorageMap::ValueDestructorPair::DestructorFunc*
-        destructor = [](void* ptr) { Deleter()(static_cast<T*>(ptr)); };
-
-    internal::SequenceLocalStorageMap::ValueDestructorPair
-        value_destructor_pair(value_ptr, destructor);
-
-    internal::SequenceLocalStorageMap::GetForCurrentThread().Set(
-        slot_id_, std::move(value_destructor_pair));
-  }
-
- private:
-  // |slot_id_| is used as a key in SequenceLocalStorageMap
-  const int slot_id_;
-  DISALLOW_COPY_AND_ASSIGN(SequenceLocalStorageSlot);
-};
-
-}  // namespace base
-#endif  // BASE_THREADING_SEQUENCE_LOCAL_STORAGE_SLOT_H_
diff --git a/base/threading/sequenced_task_runner_handle.cc b/base/threading/sequenced_task_runner_handle.cc
deleted file mode 100644
index e6920f5..0000000
--- a/base/threading/sequenced_task_runner_handle.cc
+++ /dev/null
@@ -1,59 +0,0 @@
-// Copyright 2015 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/threading/sequenced_task_runner_handle.h"
-
-#include <utility>
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/threading/thread_local.h"
-#include "base/threading/thread_task_runner_handle.h"
-
-namespace base {
-
-namespace {
-
-LazyInstance<ThreadLocalPointer<SequencedTaskRunnerHandle>>::Leaky
-    sequenced_task_runner_tls = LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace
-
-// static
-scoped_refptr<SequencedTaskRunner> SequencedTaskRunnerHandle::Get() {
-  // Return the registered SequencedTaskRunner, if any.
-  const SequencedTaskRunnerHandle* handle =
-      sequenced_task_runner_tls.Pointer()->Get();
-  if (handle)
-    return handle->task_runner_;
-
-  // Note if you hit this: the problem is the lack of a sequenced context. The
-  // ThreadTaskRunnerHandle is just the last attempt at finding such a context.
-  CHECK(ThreadTaskRunnerHandle::IsSet())
-      << "Error: This caller requires a sequenced context (i.e. the "
-         "current task needs to run from a SequencedTaskRunner).";
-  return ThreadTaskRunnerHandle::Get();
-}
-
-// static
-bool SequencedTaskRunnerHandle::IsSet() {
-  return sequenced_task_runner_tls.Pointer()->Get() ||
-         ThreadTaskRunnerHandle::IsSet();
-}
-
-SequencedTaskRunnerHandle::SequencedTaskRunnerHandle(
-    scoped_refptr<SequencedTaskRunner> task_runner)
-    : task_runner_(std::move(task_runner)) {
-  DCHECK(task_runner_->RunsTasksInCurrentSequence());
-  DCHECK(!SequencedTaskRunnerHandle::IsSet());
-  sequenced_task_runner_tls.Pointer()->Set(this);
-}
-
-SequencedTaskRunnerHandle::~SequencedTaskRunnerHandle() {
-  DCHECK(task_runner_->RunsTasksInCurrentSequence());
-  DCHECK_EQ(sequenced_task_runner_tls.Pointer()->Get(), this);
-  sequenced_task_runner_tls.Pointer()->Set(nullptr);
-}
-
-}  // namespace base
diff --git a/base/threading/sequenced_task_runner_handle.h b/base/threading/sequenced_task_runner_handle.h
deleted file mode 100644
index f55cee5..0000000
--- a/base/threading/sequenced_task_runner_handle.h
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2015 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_THREADING_SEQUENCED_TASK_RUNNER_HANDLE_H_
-#define BASE_THREADING_SEQUENCED_TASK_RUNNER_HANDLE_H_
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/sequenced_task_runner.h"
-
-namespace base {
-
-class BASE_EXPORT SequencedTaskRunnerHandle {
- public:
-  // Returns a SequencedTaskRunner which guarantees that posted tasks will only
-  // run after the current task is finished and will satisfy a SequenceChecker.
-  // It should only be called if IsSet() returns true (see the comment there for
-  // the requirements).
-  static scoped_refptr<SequencedTaskRunner> Get();
-
-  // Returns true if one of the following conditions is fulfilled:
-  // a) A SequencedTaskRunner has been assigned to the current thread by
-  //    instantiating a SequencedTaskRunnerHandle.
-  // b) The current thread has a ThreadTaskRunnerHandle (which includes any
-  //    thread that has a MessageLoop associated with it).
-  static bool IsSet();
-
-  // Binds |task_runner| to the current thread.
-  explicit SequencedTaskRunnerHandle(
-      scoped_refptr<SequencedTaskRunner> task_runner);
-  ~SequencedTaskRunnerHandle();
-
- private:
-  scoped_refptr<SequencedTaskRunner> task_runner_;
-
-  DISALLOW_COPY_AND_ASSIGN(SequencedTaskRunnerHandle);
-};
-
-}  // namespace base
-
-#endif  // BASE_THREADING_SEQUENCED_TASK_RUNNER_HANDLE_H_
diff --git a/base/threading/simple_thread.cc b/base/threading/simple_thread.cc
deleted file mode 100644
index 04a5285..0000000
--- a/base/threading/simple_thread.cc
+++ /dev/null
@@ -1,182 +0,0 @@
-// Copyright (c) 2010 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/threading/simple_thread.h"
-
-#include "base/logging.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/threading/platform_thread.h"
-#include "base/threading/thread_restrictions.h"
-
-namespace base {
-
-SimpleThread::SimpleThread(const std::string& name_prefix)
-    : SimpleThread(name_prefix, Options()) {}
-
-SimpleThread::SimpleThread(const std::string& name_prefix,
-                           const Options& options)
-    : name_prefix_(name_prefix),
-      options_(options),
-      event_(WaitableEvent::ResetPolicy::MANUAL,
-             WaitableEvent::InitialState::NOT_SIGNALED) {}
-
-SimpleThread::~SimpleThread() {
-  DCHECK(HasBeenStarted()) << "SimpleThread was never started.";
-  DCHECK(!options_.joinable || HasBeenJoined())
-      << "Joinable SimpleThread destroyed without being Join()ed.";
-}
-
-void SimpleThread::Start() {
-  StartAsync();
-  ThreadRestrictions::ScopedAllowWait allow_wait;
-  event_.Wait();  // Wait for the thread to complete initialization.
-}
-
-void SimpleThread::Join() {
-  DCHECK(options_.joinable) << "A non-joinable thread can't be joined.";
-  DCHECK(HasStartBeenAttempted()) << "Tried to Join a never-started thread.";
-  DCHECK(!HasBeenJoined()) << "Tried to Join a thread multiple times.";
-  BeforeJoin();
-  PlatformThread::Join(thread_);
-  thread_ = PlatformThreadHandle();
-  joined_ = true;
-}
-
-void SimpleThread::StartAsync() {
-  DCHECK(!HasStartBeenAttempted()) << "Tried to Start a thread multiple times.";
-  start_called_ = true;
-  BeforeStart();
-  bool success =
-      options_.joinable
-          ? PlatformThread::CreateWithPriority(options_.stack_size, this,
-                                               &thread_, options_.priority)
-          : PlatformThread::CreateNonJoinableWithPriority(
-                options_.stack_size, this, options_.priority);
-  DCHECK(success);
-}
-
-PlatformThreadId SimpleThread::tid() {
-  DCHECK(HasBeenStarted());
-  return tid_;
-}
-
-bool SimpleThread::HasBeenStarted() {
-  ThreadRestrictions::ScopedAllowWait allow_wait;
-  return event_.IsSignaled();
-}
-
-void SimpleThread::ThreadMain() {
-  tid_ = PlatformThread::CurrentId();
-  // Construct our full name of the form "name_prefix_/TID".
-  std::string name(name_prefix_);
-  name.push_back('/');
-  name.append(IntToString(tid_));
-  PlatformThread::SetName(name);
-
-  // We've initialized our new thread, signal that we're done to Start().
-  event_.Signal();
-
-  BeforeRun();
-  Run();
-}
-
-DelegateSimpleThread::DelegateSimpleThread(Delegate* delegate,
-                                           const std::string& name_prefix)
-    : DelegateSimpleThread(delegate, name_prefix, Options()) {}
-
-DelegateSimpleThread::DelegateSimpleThread(Delegate* delegate,
-                                           const std::string& name_prefix,
-                                           const Options& options)
-    : SimpleThread(name_prefix, options),
-      delegate_(delegate) {
-  DCHECK(delegate_);
-}
-
-DelegateSimpleThread::~DelegateSimpleThread() = default;
-
-void DelegateSimpleThread::Run() {
-  DCHECK(delegate_) << "Tried to call Run without a delegate (called twice?)";
-
-  // Non-joinable DelegateSimpleThreads are allowed to be deleted during Run().
-  // Member state must not be accessed after invoking Run().
-  Delegate* delegate = delegate_;
-  delegate_ = nullptr;
-  delegate->Run();
-}
-
-DelegateSimpleThreadPool::DelegateSimpleThreadPool(
-    const std::string& name_prefix,
-    int num_threads)
-    : name_prefix_(name_prefix),
-      num_threads_(num_threads),
-      dry_(WaitableEvent::ResetPolicy::MANUAL,
-           WaitableEvent::InitialState::NOT_SIGNALED) {}
-
-DelegateSimpleThreadPool::~DelegateSimpleThreadPool() {
-  DCHECK(threads_.empty());
-  DCHECK(delegates_.empty());
-  DCHECK(!dry_.IsSignaled());
-}
-
-void DelegateSimpleThreadPool::Start() {
-  DCHECK(threads_.empty()) << "Start() called with outstanding threads.";
-  for (int i = 0; i < num_threads_; ++i) {
-    DelegateSimpleThread* thread = new DelegateSimpleThread(this, name_prefix_);
-    thread->Start();
-    threads_.push_back(thread);
-  }
-}
-
-void DelegateSimpleThreadPool::JoinAll() {
-  DCHECK(!threads_.empty()) << "JoinAll() called with no outstanding threads.";
-
-  // Tell all our threads to quit their worker loop.
-  AddWork(nullptr, num_threads_);
-
-  // Join and destroy all the worker threads.
-  for (int i = 0; i < num_threads_; ++i) {
-    threads_[i]->Join();
-    delete threads_[i];
-  }
-  threads_.clear();
-  DCHECK(delegates_.empty());
-}
-
-void DelegateSimpleThreadPool::AddWork(Delegate* delegate, int repeat_count) {
-  AutoLock locked(lock_);
-  for (int i = 0; i < repeat_count; ++i)
-    delegates_.push(delegate);
-  // If we were empty, signal that we have work now.
-  if (!dry_.IsSignaled())
-    dry_.Signal();
-}
-
-void DelegateSimpleThreadPool::Run() {
-  Delegate* work = nullptr;
-
-  while (true) {
-    dry_.Wait();
-    {
-      AutoLock locked(lock_);
-      if (!dry_.IsSignaled())
-        continue;
-
-      DCHECK(!delegates_.empty());
-      work = delegates_.front();
-      delegates_.pop();
-
-      // Signal to any other threads that we're currently out of work.
-      if (delegates_.empty())
-        dry_.Reset();
-    }
-
-    // A NULL delegate pointer signals us to quit.
-    if (!work)
-      break;
-
-    work->Run();
-  }
-}
-
-}  // namespace base
diff --git a/base/threading/simple_thread.h b/base/threading/simple_thread.h
deleted file mode 100644
index 976f557..0000000
--- a/base/threading/simple_thread.h
+++ /dev/null
@@ -1,232 +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.
-
-// WARNING: You should probably be using Thread (thread.h) instead.  Thread is
-//          Chrome's message-loop based Thread abstraction, and if you are a
-//          thread running in the browser, there will likely be assumptions
-//          that your thread will have an associated message loop.
-//
-// This is a simple thread interface that backs to a native operating system
-// thread.  You should use this only when you want a thread that does not have
-// an associated MessageLoop.  Unittesting is the best example of this.
-//
-// The simplest interface to use is DelegateSimpleThread, which will create
-// a new thread, and execute the Delegate's virtual Run() in this new thread
-// until it has completed, exiting the thread.
-//
-// NOTE: You *MUST* call Join on the thread to clean up the underlying thread
-// resources.  You are also responsible for destructing the SimpleThread object.
-// It is invalid to destroy a SimpleThread while it is running, or without
-// Start() having been called (and a thread never created).  The Delegate
-// object should live as long as a DelegateSimpleThread.
-//
-// Thread Safety: A SimpleThread is not completely thread safe.  It is safe to
-// access it from the creating thread or from the newly created thread.  This
-// implies that the creator thread should be the thread that calls Join.
-//
-// Example:
-//   class MyThreadRunner : public DelegateSimpleThread::Delegate { ... };
-//   MyThreadRunner runner;
-//   DelegateSimpleThread thread(&runner, "good_name_here");
-//   thread.Start();
-//   // Start will return after the Thread has been successfully started and
-//   // initialized.  The newly created thread will invoke runner->Run(), and
-//   // run until it returns.
-//   thread.Join();  // Wait until the thread has exited.  You *MUST* Join!
-//   // The SimpleThread object is still valid, however you may not call Join
-//   // or Start again.
-
-#ifndef BASE_THREADING_SIMPLE_THREAD_H_
-#define BASE_THREADING_SIMPLE_THREAD_H_
-
-#include <stddef.h>
-
-#include <string>
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/compiler_specific.h"
-#include "base/containers/queue.h"
-#include "base/macros.h"
-#include "base/synchronization/lock.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-
-// This is the base SimpleThread.  You can derive from it and implement the
-// virtual Run method, or you can use the DelegateSimpleThread interface.
-class BASE_EXPORT SimpleThread : public PlatformThread::Delegate {
- public:
-  struct BASE_EXPORT Options {
-   public:
-    Options() = default;
-    explicit Options(ThreadPriority priority_in) : priority(priority_in) {}
-    ~Options() = default;
-
-    // Allow copies.
-    Options(const Options& other) = default;
-    Options& operator=(const Options& other) = default;
-
-    // A custom stack size, or 0 for the system default.
-    size_t stack_size = 0;
-
-    ThreadPriority priority = ThreadPriority::NORMAL;
-
-    // If false, the underlying thread's PlatformThreadHandle will not be kept
-    // around and as such the SimpleThread instance will not be Join()able and
-    // must not be deleted before Run() is invoked. After that, it's up to
-    // the subclass to determine when it is safe to delete itself.
-    bool joinable = true;
-  };
-
-  // Create a SimpleThread.  |options| should be used to manage any specific
-  // configuration involving the thread creation and management.
-  // Every thread has a name, in the form of |name_prefix|/TID, for example
-  // "my_thread/321".  The thread will not be created until Start() is called.
-  explicit SimpleThread(const std::string& name_prefix);
-  SimpleThread(const std::string& name_prefix, const Options& options);
-
-  ~SimpleThread() override;
-
-  // Starts the thread and returns only after the thread has started and
-  // initialized (i.e. ThreadMain() has been called).
-  void Start();
-
-  // Joins the thread. If StartAsync() was used to start the thread, then this
-  // first waits for the thread to start cleanly, then it joins.
-  void Join();
-
-  // Starts the thread, but returns immediately, without waiting for the thread
-  // to have initialized first (i.e. this does not wait for ThreadMain() to have
-  // been run first).
-  void StartAsync();
-
-  // Subclasses should override the Run method.
-  virtual void Run() = 0;
-
-  // Returns the thread id, only valid after the thread has started. If the
-  // thread was started using Start(), then this will be valid after the call to
-  // Start(). If StartAsync() was used to start the thread, then this must not
-  // be called before HasBeenStarted() returns True.
-  PlatformThreadId tid();
-
-  // Returns True if the thread has been started and initialized (i.e. if
-  // ThreadMain() has run). If the thread was started with StartAsync(), but it
-  // hasn't been initialized yet (i.e. ThreadMain() has not run), then this will
-  // return False.
-  bool HasBeenStarted();
-
-  // Returns True if Join() has ever been called.
-  bool HasBeenJoined() { return joined_; }
-
-  // Returns true if Start() or StartAsync() has been called.
-  bool HasStartBeenAttempted() { return start_called_; }
-
-  // Overridden from PlatformThread::Delegate:
-  void ThreadMain() override;
-
- private:
-  // This is called just before the thread is started. This is called regardless
-  // of whether Start() or StartAsync() is used to start the thread.
-  virtual void BeforeStart() {}
-
-  // This is called just after the thread has been initialized and just before
-  // Run() is called. This is called on the newly started thread.
-  virtual void BeforeRun() {}
-
-  // This is called just before the thread is joined. The thread is started and
-  // has been initialized before this is called.
-  virtual void BeforeJoin() {}
-
-  const std::string name_prefix_;
-  std::string name_;
-  const Options options_;
-  PlatformThreadHandle thread_;  // PlatformThread handle, reset after Join.
-  WaitableEvent event_;          // Signaled if Start() was ever called.
-  PlatformThreadId tid_ = kInvalidThreadId;  // The backing thread's id.
-  bool joined_ = false;                      // True if Join has been called.
-  // Set to true when the platform-thread creation has started.
-  bool start_called_ = false;
-
-  DISALLOW_COPY_AND_ASSIGN(SimpleThread);
-};
-
-// A SimpleThread which delegates Run() to its Delegate. Non-joinable
-// DelegateSimpleThread are safe to delete after Run() was invoked, their
-// Delegates are also safe to delete after that point from this class' point of
-// view (although implementations must of course make sure that Run() will not
-// use their Delegate's member state after its deletion).
-class BASE_EXPORT DelegateSimpleThread : public SimpleThread {
- public:
-  class BASE_EXPORT Delegate {
-   public:
-    virtual ~Delegate() = default;
-    virtual void Run() = 0;
-  };
-
-  DelegateSimpleThread(Delegate* delegate,
-                       const std::string& name_prefix);
-  DelegateSimpleThread(Delegate* delegate,
-                       const std::string& name_prefix,
-                       const Options& options);
-
-  ~DelegateSimpleThread() override;
-  void Run() override;
-
- private:
-  Delegate* delegate_;
-
-  DISALLOW_COPY_AND_ASSIGN(DelegateSimpleThread);
-};
-
-// DelegateSimpleThreadPool allows you to start up a fixed number of threads,
-// and then add jobs which will be dispatched to the threads.  This is
-// convenient when you have a lot of small work that you want done
-// multi-threaded, but don't want to spawn a thread for each small bit of work.
-//
-// You just call AddWork() to add a delegate to the list of work to be done.
-// JoinAll() will make sure that all outstanding work is processed, and wait
-// for everything to finish.  You can reuse a pool, so you can call Start()
-// again after you've called JoinAll().
-class BASE_EXPORT DelegateSimpleThreadPool
-    : public DelegateSimpleThread::Delegate {
- public:
-  typedef DelegateSimpleThread::Delegate Delegate;
-
-  DelegateSimpleThreadPool(const std::string& name_prefix, int num_threads);
-  ~DelegateSimpleThreadPool() override;
-
-  // Start up all of the underlying threads, and start processing work if we
-  // have any.
-  void Start();
-
-  // Make sure all outstanding work is finished, and wait for and destroy all
-  // of the underlying threads in the pool.
-  void JoinAll();
-
-  // It is safe to AddWork() any time, before or after Start().
-  // Delegate* should always be a valid pointer, NULL is reserved internally.
-  void AddWork(Delegate* work, int repeat_count);
-  void AddWork(Delegate* work) {
-    AddWork(work, 1);
-  }
-
-  // We implement the Delegate interface, for running our internal threads.
-  void Run() override;
-
- private:
-  const std::string name_prefix_;
-  int num_threads_;
-  std::vector<DelegateSimpleThread*> threads_;
-  base::queue<Delegate*> delegates_;
-  base::Lock lock_;            // Locks delegates_
-  WaitableEvent dry_;    // Not signaled when there is no work to do.
-
-  DISALLOW_COPY_AND_ASSIGN(DelegateSimpleThreadPool);
-};
-
-}  // namespace base
-
-#endif  // BASE_THREADING_SIMPLE_THREAD_H_
diff --git a/base/threading/thread.cc b/base/threading/thread.cc
deleted file mode 100644
index 382c600..0000000
--- a/base/threading/thread.cc
+++ /dev/null
@@ -1,368 +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 "base/threading/thread.h"
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/lazy_instance.h"
-#include "base/location.h"
-#include "base/logging.h"
-#include "base/run_loop.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/threading/thread_id_name_manager.h"
-#include "base/threading/thread_local.h"
-#include "base/threading/thread_restrictions.h"
-#include "build_config.h"
-
-#if defined(OS_POSIX) && !defined(OS_NACL)
-#include "base/files/file_descriptor_watcher_posix.h"
-#endif
-
-#if defined(OS_WIN)
-#include "base/win/scoped_com_initializer.h"
-#endif
-
-namespace base {
-
-namespace {
-
-// We use this thread-local variable to record whether or not a thread exited
-// because its Stop method was called.  This allows us to catch cases where
-// MessageLoop::QuitWhenIdle() is called directly, which is unexpected when
-// using a Thread to setup and run a MessageLoop.
-base::LazyInstance<base::ThreadLocalBoolean>::Leaky lazy_tls_bool =
-    LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace
-
-Thread::Options::Options() = default;
-
-Thread::Options::Options(MessageLoop::Type type, size_t size)
-    : message_loop_type(type), stack_size(size) {}
-
-Thread::Options::Options(const Options& other) = default;
-
-Thread::Options::~Options() = default;
-
-Thread::Thread(const std::string& name)
-    : id_event_(WaitableEvent::ResetPolicy::MANUAL,
-                WaitableEvent::InitialState::NOT_SIGNALED),
-      name_(name),
-      start_event_(WaitableEvent::ResetPolicy::MANUAL,
-                   WaitableEvent::InitialState::NOT_SIGNALED) {
-  // Only bind the sequence on Start(): the state is constant between
-  // construction and Start() and it's thus valid for Start() to be called on
-  // another sequence as long as every other operation is then performed on that
-  // sequence.
-  owning_sequence_checker_.DetachFromSequence();
-}
-
-Thread::~Thread() {
-  Stop();
-}
-
-bool Thread::Start() {
-  DCHECK(owning_sequence_checker_.CalledOnValidSequence());
-
-  Options options;
-#if defined(OS_WIN)
-  if (com_status_ == STA)
-    options.message_loop_type = MessageLoop::TYPE_UI;
-#endif
-  return StartWithOptions(options);
-}
-
-bool Thread::StartWithOptions(const Options& options) {
-  DCHECK(owning_sequence_checker_.CalledOnValidSequence());
-  DCHECK(!message_loop_);
-  DCHECK(!IsRunning());
-  DCHECK(!stopping_) << "Starting a non-joinable thread a second time? That's "
-                     << "not allowed!";
-#if defined(OS_WIN)
-  DCHECK((com_status_ != STA) ||
-      (options.message_loop_type == MessageLoop::TYPE_UI));
-#endif
-
-  // Reset |id_| here to support restarting the thread.
-  id_event_.Reset();
-  id_ = kInvalidThreadId;
-
-  SetThreadWasQuitProperly(false);
-
-  MessageLoop::Type type = options.message_loop_type;
-  if (!options.message_pump_factory.is_null())
-    type = MessageLoop::TYPE_CUSTOM;
-
-  message_loop_timer_slack_ = options.timer_slack;
-  std::unique_ptr<MessageLoop> message_loop_owned =
-      MessageLoop::CreateUnbound(type, options.message_pump_factory);
-  message_loop_ = message_loop_owned.get();
-  start_event_.Reset();
-
-  // Hold |thread_lock_| while starting the new thread to synchronize with
-  // Stop() while it's not guaranteed to be sequenced (until crbug/629139 is
-  // fixed).
-  {
-    AutoLock lock(thread_lock_);
-    bool success =
-        options.joinable
-            ? PlatformThread::CreateWithPriority(options.stack_size, this,
-                                                 &thread_, options.priority)
-            : PlatformThread::CreateNonJoinableWithPriority(
-                  options.stack_size, this, options.priority);
-    if (!success) {
-      DLOG(ERROR) << "failed to create thread";
-      message_loop_ = nullptr;
-      return false;
-    }
-  }
-
-  joinable_ = options.joinable;
-
-  // The ownership of |message_loop_| is managed by the newly created thread
-  // within the ThreadMain.
-  ignore_result(message_loop_owned.release());
-
-  DCHECK(message_loop_);
-  return true;
-}
-
-bool Thread::StartAndWaitForTesting() {
-  DCHECK(owning_sequence_checker_.CalledOnValidSequence());
-  bool result = Start();
-  if (!result)
-    return false;
-  WaitUntilThreadStarted();
-  return true;
-}
-
-bool Thread::WaitUntilThreadStarted() const {
-  DCHECK(owning_sequence_checker_.CalledOnValidSequence());
-  if (!message_loop_)
-    return false;
-  base::ThreadRestrictions::ScopedAllowWait allow_wait;
-  start_event_.Wait();
-  return true;
-}
-
-void Thread::FlushForTesting() {
-  DCHECK(owning_sequence_checker_.CalledOnValidSequence());
-  if (!message_loop_)
-    return;
-
-  WaitableEvent done(WaitableEvent::ResetPolicy::AUTOMATIC,
-                     WaitableEvent::InitialState::NOT_SIGNALED);
-  task_runner()->PostTask(FROM_HERE,
-                          BindOnce(&WaitableEvent::Signal, Unretained(&done)));
-  done.Wait();
-}
-
-void Thread::Stop() {
-  DCHECK(joinable_);
-
-  // TODO(gab): Fix improper usage of this API (http://crbug.com/629139) and
-  // enable this check, until then synchronization with Start() via
-  // |thread_lock_| is required...
-  // DCHECK(owning_sequence_checker_.CalledOnValidSequence());
-  AutoLock lock(thread_lock_);
-
-  StopSoon();
-
-  // Can't join if the |thread_| is either already gone or is non-joinable.
-  if (thread_.is_null())
-    return;
-
-  // Wait for the thread to exit.
-  //
-  // TODO(darin): Unfortunately, we need to keep |message_loop_| around until
-  // the thread exits.  Some consumers are abusing the API.  Make them stop.
-  //
-  PlatformThread::Join(thread_);
-  thread_ = base::PlatformThreadHandle();
-
-  // The thread should nullify |message_loop_| on exit (note: Join() adds an
-  // implicit memory barrier and no lock is thus required for this check).
-  DCHECK(!message_loop_);
-
-  stopping_ = false;
-}
-
-void Thread::StopSoon() {
-  // TODO(gab): Fix improper usage of this API (http://crbug.com/629139) and
-  // enable this check.
-  // DCHECK(owning_sequence_checker_.CalledOnValidSequence());
-
-  if (stopping_ || !message_loop_)
-    return;
-
-  stopping_ = true;
-
-  if (using_external_message_loop_) {
-    // Setting |stopping_| to true above should have been sufficient for this
-    // thread to be considered "stopped" per it having never set its |running_|
-    // bit by lack of its own ThreadMain.
-    DCHECK(!IsRunning());
-    message_loop_ = nullptr;
-    return;
-  }
-
-  task_runner()->PostTask(
-      FROM_HERE, base::BindOnce(&Thread::ThreadQuitHelper, Unretained(this)));
-}
-
-void Thread::DetachFromSequence() {
-  DCHECK(owning_sequence_checker_.CalledOnValidSequence());
-  owning_sequence_checker_.DetachFromSequence();
-}
-
-PlatformThreadId Thread::GetThreadId() const {
-  // If the thread is created but not started yet, wait for |id_| being ready.
-  base::ThreadRestrictions::ScopedAllowWait allow_wait;
-  id_event_.Wait();
-  return id_;
-}
-
-PlatformThreadHandle Thread::GetThreadHandle() const {
-  AutoLock lock(thread_lock_);
-  return thread_;
-}
-
-bool Thread::IsRunning() const {
-  // TODO(gab): Fix improper usage of this API (http://crbug.com/629139) and
-  // enable this check.
-  // DCHECK(owning_sequence_checker_.CalledOnValidSequence());
-
-  // If the thread's already started (i.e. |message_loop_| is non-null) and not
-  // yet requested to stop (i.e. |stopping_| is false) we can just return true.
-  // (Note that |stopping_| is touched only on the same sequence that starts /
-  // started the new thread so we need no locking here.)
-  if (message_loop_ && !stopping_)
-    return true;
-  // Otherwise check the |running_| flag, which is set to true by the new thread
-  // only while it is inside Run().
-  AutoLock lock(running_lock_);
-  return running_;
-}
-
-void Thread::Run(RunLoop* run_loop) {
-  // Overridable protected method to be called from our |thread_| only.
-  DCHECK(id_event_.IsSignaled());
-  DCHECK_EQ(id_, PlatformThread::CurrentId());
-
-  run_loop->Run();
-}
-
-// static
-void Thread::SetThreadWasQuitProperly(bool flag) {
-  lazy_tls_bool.Pointer()->Set(flag);
-}
-
-// static
-bool Thread::GetThreadWasQuitProperly() {
-  bool quit_properly = true;
-#ifndef NDEBUG
-  quit_properly = lazy_tls_bool.Pointer()->Get();
-#endif
-  return quit_properly;
-}
-
-void Thread::SetMessageLoop(MessageLoop* message_loop) {
-  DCHECK(owning_sequence_checker_.CalledOnValidSequence());
-  DCHECK(message_loop);
-
-  // Setting |message_loop_| should suffice for this thread to be considered
-  // as "running", until Stop() is invoked.
-  DCHECK(!IsRunning());
-  message_loop_ = message_loop;
-  DCHECK(IsRunning());
-
-  using_external_message_loop_ = true;
-}
-
-void Thread::ThreadMain() {
-  // First, make GetThreadId() available to avoid deadlocks. It could be called
-  // any place in the following thread initialization code.
-  DCHECK(!id_event_.IsSignaled());
-  // Note: this read of |id_| while |id_event_| isn't signaled is exceptionally
-  // okay because ThreadMain has a happens-after relationship with the other
-  // write in StartWithOptions().
-  DCHECK_EQ(kInvalidThreadId, id_);
-  id_ = PlatformThread::CurrentId();
-  DCHECK_NE(kInvalidThreadId, id_);
-  id_event_.Signal();
-
-  // Complete the initialization of our Thread object.
-  PlatformThread::SetName(name_.c_str());
-
-  // Lazily initialize the |message_loop| so that it can run on this thread.
-  DCHECK(message_loop_);
-  std::unique_ptr<MessageLoop> message_loop(message_loop_);
-  message_loop_->BindToCurrentThread();
-  message_loop_->SetTimerSlack(message_loop_timer_slack_);
-
-#if defined(OS_POSIX) && !defined(OS_NACL)
-  // Allow threads running a MessageLoopForIO to use FileDescriptorWatcher API.
-  std::unique_ptr<FileDescriptorWatcher> file_descriptor_watcher;
-  if (MessageLoopForIO::IsCurrent()) {
-    file_descriptor_watcher.reset(new FileDescriptorWatcher(
-        static_cast<MessageLoopForIO*>(message_loop_)));
-  }
-#endif
-
-#if defined(OS_WIN)
-  std::unique_ptr<win::ScopedCOMInitializer> com_initializer;
-  if (com_status_ != NONE) {
-    com_initializer.reset((com_status_ == STA) ?
-        new win::ScopedCOMInitializer() :
-        new win::ScopedCOMInitializer(win::ScopedCOMInitializer::kMTA));
-  }
-#endif
-
-  // Let the thread do extra initialization.
-  Init();
-
-  {
-    AutoLock lock(running_lock_);
-    running_ = true;
-  }
-
-  start_event_.Signal();
-
-  RunLoop run_loop;
-  run_loop_ = &run_loop;
-  Run(run_loop_);
-
-  {
-    AutoLock lock(running_lock_);
-    running_ = false;
-  }
-
-  // Let the thread do extra cleanup.
-  CleanUp();
-
-#if defined(OS_WIN)
-  com_initializer.reset();
-#endif
-
-  if (message_loop->type() != MessageLoop::TYPE_CUSTOM) {
-    // Assert that RunLoop::QuitWhenIdle was called by ThreadQuitHelper. Don't
-    // check for custom message pumps, because their shutdown might not allow
-    // this.
-    DCHECK(GetThreadWasQuitProperly());
-  }
-
-  // We can't receive messages anymore.
-  // (The message loop is destructed at the end of this block)
-  message_loop_ = nullptr;
-  run_loop_ = nullptr;
-}
-
-void Thread::ThreadQuitHelper() {
-  DCHECK(run_loop_);
-  run_loop_->QuitWhenIdle();
-  SetThreadWasQuitProperly(true);
-}
-
-}  // namespace base
diff --git a/base/threading/thread.h b/base/threading/thread.h
deleted file mode 100644
index 86a454c..0000000
--- a/base/threading/thread.h
+++ /dev/null
@@ -1,356 +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_THREADING_THREAD_H_
-#define BASE_THREADING_THREAD_H_
-
-#include <stddef.h>
-
-#include <memory>
-#include <string>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/message_loop/message_loop.h"
-#include "base/message_loop/timer_slack.h"
-#include "base/sequence_checker.h"
-#include "base/single_thread_task_runner.h"
-#include "base/synchronization/atomic_flag.h"
-#include "base/synchronization/lock.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/threading/platform_thread.h"
-#include "build_config.h"
-
-namespace base {
-
-class MessagePump;
-class RunLoop;
-
-// IMPORTANT: Instead of creating a base::Thread, consider using
-// base::Create(Sequenced|SingleThread)TaskRunnerWithTraits().
-//
-// A simple thread abstraction that establishes a MessageLoop on a new thread.
-// The consumer uses the MessageLoop of the thread to cause code to execute on
-// the thread.  When this object is destroyed the thread is terminated.  All
-// pending tasks queued on the thread's message loop will run to completion
-// before the thread is terminated.
-//
-// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS!  See ~Thread().
-//
-// After the thread is stopped, the destruction sequence is:
-//
-//  (1) Thread::CleanUp()
-//  (2) MessageLoop::~MessageLoop
-//  (3.b) MessageLoopCurrent::DestructionObserver::WillDestroyCurrentMessageLoop
-//
-// This API is not thread-safe: unless indicated otherwise its methods are only
-// valid from the owning sequence (which is the one from which Start() is
-// invoked -- should it differ from the one on which it was constructed).
-//
-// Sometimes it's useful to kick things off on the initial sequence (e.g.
-// construction, Start(), task_runner()), but to then hand the Thread over to a
-// pool of users for the last one of them to destroy it when done. For that use
-// case, Thread::DetachFromSequence() allows the owning sequence to give up
-// ownership. The caller is then responsible to ensure a happens-after
-// relationship between the DetachFromSequence() call and the next use of that
-// Thread object (including ~Thread()).
-class BASE_EXPORT Thread : PlatformThread::Delegate {
- public:
-  struct BASE_EXPORT Options {
-    typedef Callback<std::unique_ptr<MessagePump>()> MessagePumpFactory;
-
-    Options();
-    Options(MessageLoop::Type type, size_t size);
-    Options(const Options& other);
-    ~Options();
-
-    // Specifies the type of message loop that will be allocated on the thread.
-    // This is ignored if message_pump_factory.is_null() is false.
-    MessageLoop::Type message_loop_type = MessageLoop::TYPE_DEFAULT;
-
-    // Specifies timer slack for thread message loop.
-    TimerSlack timer_slack = TIMER_SLACK_NONE;
-
-    // Used to create the MessagePump for the MessageLoop. The callback is Run()
-    // on the thread. If message_pump_factory.is_null(), then a MessagePump
-    // appropriate for |message_loop_type| is created. Setting this forces the
-    // MessageLoop::Type to TYPE_CUSTOM.
-    MessagePumpFactory message_pump_factory;
-
-    // Specifies the maximum stack size that the thread is allowed to use.
-    // This does not necessarily correspond to the thread's initial stack size.
-    // A value of 0 indicates that the default maximum should be used.
-    size_t stack_size = 0;
-
-    // Specifies the initial thread priority.
-    ThreadPriority priority = ThreadPriority::NORMAL;
-
-    // If false, the thread will not be joined on destruction. This is intended
-    // for threads that want TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN
-    // semantics. Non-joinable threads can't be joined (must be leaked and
-    // can't be destroyed or Stop()'ed).
-    // TODO(gab): allow non-joinable instances to be deleted without causing
-    // user-after-frees (proposal @ https://crbug.com/629139#c14)
-    bool joinable = true;
-  };
-
-  // Constructor.
-  // name is a display string to identify the thread.
-  explicit Thread(const std::string& name);
-
-  // Destroys the thread, stopping it if necessary.
-  //
-  // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
-  // guarantee Stop() is explicitly called before the subclass is destroyed).
-  // This is required to avoid a data race between the destructor modifying the
-  // vtable, and the thread's ThreadMain calling the virtual method Run().  It
-  // also ensures that the CleanUp() virtual method is called on the subclass
-  // before it is destructed.
-  ~Thread() override;
-
-#if defined(OS_WIN)
-  // Causes the thread to initialize COM.  This must be called before calling
-  // Start() or StartWithOptions().  If |use_mta| is false, the thread is also
-  // started with a TYPE_UI message loop.  It is an error to call
-  // init_com_with_mta(false) and then StartWithOptions() with any message loop
-  // type other than TYPE_UI.
-  void init_com_with_mta(bool use_mta) {
-    DCHECK(!message_loop_);
-    com_status_ = use_mta ? MTA : STA;
-  }
-#endif
-
-  // Starts the thread.  Returns true if the thread was successfully started;
-  // otherwise, returns false.  Upon successful return, the message_loop()
-  // getter will return non-null.
-  //
-  // Note: This function can't be called on Windows with the loader lock held;
-  // i.e. during a DllMain, global object construction or destruction, atexit()
-  // callback.
-  bool Start();
-
-  // Starts the thread. Behaves exactly like Start in addition to allow to
-  // override the default options.
-  //
-  // Note: This function can't be called on Windows with the loader lock held;
-  // i.e. during a DllMain, global object construction or destruction, atexit()
-  // callback.
-  bool StartWithOptions(const Options& options);
-
-  // Starts the thread and wait for the thread to start and run initialization
-  // before returning. It's same as calling Start() and then
-  // WaitUntilThreadStarted().
-  // Note that using this (instead of Start() or StartWithOptions() causes
-  // jank on the calling thread, should be used only in testing code.
-  bool StartAndWaitForTesting();
-
-  // Blocks until the thread starts running. Called within StartAndWait().
-  // Note that calling this causes jank on the calling thread, must be used
-  // carefully for production code.
-  bool WaitUntilThreadStarted() const;
-
-  // Blocks until all tasks previously posted to this thread have been executed.
-  void FlushForTesting();
-
-  // Signals the thread to exit and returns once the thread has exited. The
-  // Thread object is completely reset and may be used as if it were newly
-  // constructed (i.e., Start may be called again). Can only be called if
-  // |joinable_|.
-  //
-  // Stop may be called multiple times and is simply ignored if the thread is
-  // already stopped or currently stopping.
-  //
-  // Start/Stop are not thread-safe and callers that desire to invoke them from
-  // different threads must ensure mutual exclusion.
-  //
-  // NOTE: If you are a consumer of Thread, it is not necessary to call this
-  // before deleting your Thread objects, as the destructor will do it.
-  // IF YOU ARE A SUBCLASS OF Thread, YOU MUST CALL THIS IN YOUR DESTRUCTOR.
-  void Stop();
-
-  // Signals the thread to exit in the near future.
-  //
-  // WARNING: This function is not meant to be commonly used. Use at your own
-  // risk. Calling this function will cause message_loop() to become invalid in
-  // the near future. This function was created to workaround a specific
-  // deadlock on Windows with printer worker thread. In any other case, Stop()
-  // should be used.
-  //
-  // Call Stop() to reset the thread object once it is known that the thread has
-  // quit.
-  void StopSoon();
-
-  // Detaches the owning sequence, indicating that the next call to this API
-  // (including ~Thread()) can happen from a different sequence (to which it
-  // will be rebound). This call itself must happen on the current owning
-  // sequence and the caller must ensure the next API call has a happens-after
-  // relationship with this one.
-  void DetachFromSequence();
-
-  // Returns the message loop for this thread.  Use the MessageLoop's
-  // PostTask methods to execute code on the thread.  This only returns
-  // non-null after a successful call to Start.  After Stop has been called,
-  // this will return nullptr.
-  //
-  // NOTE: You must not call this MessageLoop's Quit method directly.  Use
-  // the Thread's Stop method instead.
-  //
-  // In addition to this Thread's owning sequence, this can also safely be
-  // called from the underlying thread itself.
-  MessageLoop* message_loop() const {
-    // This class doesn't provide synchronization around |message_loop_| and as
-    // such only the owner should access it (and the underlying thread which
-    // never sees it before it's set). In practice, many callers are coming from
-    // unrelated threads but provide their own implicit (e.g. memory barriers
-    // from task posting) or explicit (e.g. locks) synchronization making the
-    // access of |message_loop_| safe... Changing all of those callers is
-    // unfeasible; instead verify that they can reliably see
-    // |message_loop_ != nullptr| without synchronization as a proof that their
-    // external synchronization catches the unsynchronized effects of Start().
-    // TODO(gab): Despite all of the above this test has to be disabled for now
-    // per crbug.com/629139#c6.
-    // DCHECK(owning_sequence_checker_.CalledOnValidSequence() ||
-    //        (id_event_.IsSignaled() && id_ == PlatformThread::CurrentId()) ||
-    //        message_loop_);
-    return message_loop_;
-  }
-
-  // Returns a TaskRunner for this thread. Use the TaskRunner's PostTask
-  // methods to execute code on the thread. Returns nullptr if the thread is not
-  // running (e.g. before Start or after Stop have been called). Callers can
-  // hold on to this even after the thread is gone; in this situation, attempts
-  // to PostTask() will fail.
-  //
-  // In addition to this Thread's owning sequence, this can also safely be
-  // called from the underlying thread itself.
-  scoped_refptr<SingleThreadTaskRunner> task_runner() const {
-    // Refer to the DCHECK and comment inside |message_loop()|.
-    DCHECK(owning_sequence_checker_.CalledOnValidSequence() ||
-           (id_event_.IsSignaled() && id_ == PlatformThread::CurrentId()) ||
-           message_loop_);
-    return message_loop_ ? message_loop_->task_runner() : nullptr;
-  }
-
-  // Returns the name of this thread (for display in debugger too).
-  const std::string& thread_name() const { return name_; }
-
-  // Returns the thread ID.  Should not be called before the first Start*()
-  // call.  Keeps on returning the same ID even after a Stop() call. The next
-  // Start*() call renews the ID.
-  //
-  // WARNING: This function will block if the thread hasn't started yet.
-  //
-  // This method is thread-safe.
-  PlatformThreadId GetThreadId() const;
-
-  // Returns the current thread handle. If called before Start*() returns or
-  // after Stop() returns, an empty thread handle will be returned.
-  //
-  // This method is thread-safe.
-  //
-  // TODO(robliao): Remove this when it no longer needs to be temporarily
-  // exposed for http://crbug.com/717380.
-  PlatformThreadHandle GetThreadHandle() const;
-
-  // Returns true if the thread has been started, and not yet stopped.
-  bool IsRunning() const;
-
- protected:
-  // Called just prior to starting the message loop
-  virtual void Init() {}
-
-  // Called to start the run loop
-  virtual void Run(RunLoop* run_loop);
-
-  // Called just after the message loop ends
-  virtual void CleanUp() {}
-
-  static void SetThreadWasQuitProperly(bool flag);
-  static bool GetThreadWasQuitProperly();
-
-  // Bind this Thread to an existing MessageLoop instead of starting a new one.
-  // TODO(gab): Remove this after ios/ has undergone the same surgery as
-  // BrowserThreadImpl (ref.
-  // https://chromium-review.googlesource.com/c/chromium/src/+/969104).
-  void SetMessageLoop(MessageLoop* message_loop);
-
-  bool using_external_message_loop() const {
-    return using_external_message_loop_;
-  }
-
- private:
-#if defined(OS_WIN)
-  enum ComStatus {
-    NONE,
-    STA,
-    MTA,
-  };
-#endif
-
-  // PlatformThread::Delegate methods:
-  void ThreadMain() override;
-
-  void ThreadQuitHelper();
-
-#if defined(OS_WIN)
-  // Whether this thread needs to initialize COM, and if so, in what mode.
-  ComStatus com_status_ = NONE;
-#endif
-
-  // Mirrors the Options::joinable field used to start this thread. Verified
-  // on Stop() -- non-joinable threads can't be joined (must be leaked).
-  bool joinable_ = true;
-
-  // If true, we're in the middle of stopping, and shouldn't access
-  // |message_loop_|. It may non-nullptr and invalid.
-  // Should be written on the thread that created this thread. Also read data
-  // could be wrong on other threads.
-  bool stopping_ = false;
-
-  // True while inside of Run().
-  bool running_ = false;
-  mutable base::Lock running_lock_;  // Protects |running_|.
-
-  // The thread's handle.
-  PlatformThreadHandle thread_;
-  mutable base::Lock thread_lock_;  // Protects |thread_|.
-
-  // The thread's id once it has started.
-  PlatformThreadId id_ = kInvalidThreadId;
-  // Protects |id_| which must only be read while it's signaled.
-  mutable WaitableEvent id_event_;
-
-  // The thread's MessageLoop and RunLoop. Valid only while the thread is alive.
-  // Set by the created thread.
-  MessageLoop* message_loop_ = nullptr;
-  RunLoop* run_loop_ = nullptr;
-
-  // True only if |message_loop_| was externally provided by |SetMessageLoop()|
-  // in which case this Thread has no underlying |thread_| and should merely
-  // drop |message_loop_| on Stop(). In that event, this remains true after
-  // Stop() was invoked so that subclasses can use this state to build their own
-  // cleanup logic as required.
-  bool using_external_message_loop_ = false;
-
-  // Stores Options::timer_slack_ until the message loop has been bound to
-  // a thread.
-  TimerSlack message_loop_timer_slack_ = TIMER_SLACK_NONE;
-
-  // The name of the thread.  Used for debugging purposes.
-  const std::string name_;
-
-  // Signaled when the created thread gets ready to use the message loop.
-  mutable WaitableEvent start_event_;
-
-  // This class is not thread-safe, use this to verify access from the owning
-  // sequence of the Thread.
-  SequenceChecker owning_sequence_checker_;
-
-  DISALLOW_COPY_AND_ASSIGN(Thread);
-};
-
-}  // namespace base
-
-#endif  // BASE_THREADING_THREAD_H_
diff --git a/base/threading/thread_checker.h b/base/threading/thread_checker.h
deleted file mode 100644
index 6799e25..0000000
--- a/base/threading/thread_checker.h
+++ /dev/null
@@ -1,103 +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_THREADING_THREAD_CHECKER_H_
-#define BASE_THREADING_THREAD_CHECKER_H_
-
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/threading/thread_checker_impl.h"
-
-// ThreadChecker is a helper class used to help verify that some methods of a
-// class are called from the same thread (for thread-affinity).
-//
-// Use the macros below instead of the ThreadChecker directly so that the unused
-// member doesn't result in an extra byte (four when padded) per instance in
-// production.
-//
-// Usage of this class should be *rare* as most classes require thread-safety
-// but not thread-affinity. Prefer base::SequenceChecker to verify thread-safe
-// access.
-//
-// Thread-affinity checks should only be required in classes that use thread-
-// local-storage or a third-party API that does.
-//
-// Prefer to encode the minimum requirements of each class instead of the
-// environment it happens to run in today. e.g. if a class requires thread-
-// safety but not thread-affinity, use a SequenceChecker even if it happens to
-// run on a SingleThreadTaskRunner today. That makes it easier to understand
-// what would need to change to turn that SingleThreadTaskRunner into a
-// SequencedTaskRunner for ease of scheduling as well as minimizes side-effects
-// if that change is made.
-//
-// Usage:
-//   class MyClass {
-//    public:
-//     MyClass() {
-//       // It's sometimes useful to detach on construction for objects that are
-//       // constructed in one place and forever after used from another
-//       // thread.
-//       DETACH_FROM_THREAD(my_thread_checker_);
-//     }
-//
-//     ~MyClass() {
-//       // ThreadChecker doesn't automatically check it's destroyed on origin
-//       // thread for the same reason it's sometimes detached in the
-//       // constructor. It's okay to destroy off thread if the owner otherwise
-//       // knows usage on the associated thread is done. If you're not
-//       // detaching in the constructor, you probably want to explicitly check
-//       // in the destructor.
-//       DCHECK_CALLED_ON_VALID_THREAD(my_thread_checker_);
-//     }
-//
-//     void MyMethod() {
-//       DCHECK_CALLED_ON_VALID_THREAD(my_thread_checker_);
-//       ... (do stuff) ...
-//     }
-//
-//    private:
-//     THREAD_CHECKER(my_thread_checker_);
-//   }
-
-#if DCHECK_IS_ON()
-#define THREAD_CHECKER(name) base::ThreadChecker name
-#define DCHECK_CALLED_ON_VALID_THREAD(name) DCHECK((name).CalledOnValidThread())
-#define DETACH_FROM_THREAD(name) (name).DetachFromThread()
-#else  // DCHECK_IS_ON()
-#define THREAD_CHECKER(name)
-#define DCHECK_CALLED_ON_VALID_THREAD(name) EAT_STREAM_PARAMETERS
-#define DETACH_FROM_THREAD(name)
-#endif  // DCHECK_IS_ON()
-
-namespace base {
-
-// Do nothing implementation, for use in release mode.
-//
-// Note: You should almost always use the ThreadChecker class (through the above
-// macros) to get the right version for your build configuration.
-class ThreadCheckerDoNothing {
- public:
-  ThreadCheckerDoNothing() = default;
-  bool CalledOnValidThread() const WARN_UNUSED_RESULT { return true; }
-  void DetachFromThread() {}
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(ThreadCheckerDoNothing);
-};
-
-// Note that ThreadCheckerImpl::CalledOnValidThread() returns false when called
-// from tasks posted to SingleThreadTaskRunners bound to different sequences,
-// even if the tasks happen to run on the same thread (e.g. two independent
-// SingleThreadTaskRunners on the TaskScheduler that happen to share a thread).
-#if DCHECK_IS_ON()
-class ThreadChecker : public ThreadCheckerImpl {
-};
-#else
-class ThreadChecker : public ThreadCheckerDoNothing {
-};
-#endif  // DCHECK_IS_ON()
-
-}  // namespace base
-
-#endif  // BASE_THREADING_THREAD_CHECKER_H_
diff --git a/base/threading/thread_checker_impl.cc b/base/threading/thread_checker_impl.cc
deleted file mode 100644
index d5ccbdb..0000000
--- a/base/threading/thread_checker_impl.cc
+++ /dev/null
@@ -1,57 +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 "base/threading/thread_checker_impl.h"
-
-#include "base/threading/thread_task_runner_handle.h"
-
-namespace base {
-
-ThreadCheckerImpl::ThreadCheckerImpl() {
-  AutoLock auto_lock(lock_);
-  EnsureAssigned();
-}
-
-ThreadCheckerImpl::~ThreadCheckerImpl() = default;
-
-bool ThreadCheckerImpl::CalledOnValidThread() const {
-  AutoLock auto_lock(lock_);
-  EnsureAssigned();
-
-  // Always return true when called from the task from which this
-  // ThreadCheckerImpl was assigned to a thread.
-  if (task_token_ == TaskToken::GetForCurrentThread())
-    return true;
-
-  // If this ThreadCheckerImpl is bound to a valid SequenceToken, it must be
-  // equal to the current SequenceToken and there must be a registered
-  // ThreadTaskRunnerHandle. Otherwise, the fact that the current task runs on
-  // the thread to which this ThreadCheckerImpl is bound is fortuitous.
-  if (sequence_token_.IsValid() &&
-      (sequence_token_ != SequenceToken::GetForCurrentThread() ||
-       !ThreadTaskRunnerHandle::IsSet())) {
-    return false;
-  }
-
-  return thread_id_ == PlatformThread::CurrentRef();
-}
-
-void ThreadCheckerImpl::DetachFromThread() {
-  AutoLock auto_lock(lock_);
-  thread_id_ = PlatformThreadRef();
-  task_token_ = TaskToken();
-  sequence_token_ = SequenceToken();
-}
-
-void ThreadCheckerImpl::EnsureAssigned() const {
-  lock_.AssertAcquired();
-  if (!thread_id_.is_null())
-    return;
-
-  thread_id_ = PlatformThread::CurrentRef();
-  task_token_ = TaskToken::GetForCurrentThread();
-  sequence_token_ = SequenceToken::GetForCurrentThread();
-}
-
-}  // namespace base
diff --git a/base/threading/thread_checker_impl.h b/base/threading/thread_checker_impl.h
deleted file mode 100644
index 103dfe7..0000000
--- a/base/threading/thread_checker_impl.h
+++ /dev/null
@@ -1,62 +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_THREADING_THREAD_CHECKER_IMPL_H_
-#define BASE_THREADING_THREAD_CHECKER_IMPL_H_
-
-#include "base/base_export.h"
-#include "base/compiler_specific.h"
-#include "base/sequence_token.h"
-#include "base/synchronization/lock.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-
-// Real implementation of ThreadChecker, for use in debug mode, or for temporary
-// use in release mode (e.g. to CHECK on a threading issue seen only in the
-// wild).
-//
-// Note: You should almost always use the ThreadChecker class to get the right
-// version for your build configuration.
-class BASE_EXPORT ThreadCheckerImpl {
- public:
-  ThreadCheckerImpl();
-  ~ThreadCheckerImpl();
-
-  bool CalledOnValidThread() const WARN_UNUSED_RESULT;
-
-  // Changes the thread that is checked for in CalledOnValidThread.  This may
-  // be useful when an object may be created on one thread and then used
-  // exclusively on another thread.
-  void DetachFromThread();
-
- private:
-  void EnsureAssigned() const;
-
-  // Members are mutable so that CalledOnValidThread() can set them.
-
-  // Synchronizes access to all members.
-  mutable base::Lock lock_;
-
-  // Thread on which CalledOnValidThread() may return true.
-  mutable PlatformThreadRef thread_id_;
-
-  // TaskToken for which CalledOnValidThread() always returns true. This allows
-  // CalledOnValidThread() to return true when called multiple times from the
-  // same task, even if it's not running in a single-threaded context itself
-  // (allowing usage of ThreadChecker objects on the stack in the scope of one-
-  // off tasks). Note: CalledOnValidThread() may return true even if the current
-  // TaskToken is not equal to this.
-  mutable TaskToken task_token_;
-
-  // SequenceToken for which CalledOnValidThread() may return true. Used to
-  // ensure that CalledOnValidThread() doesn't return true for TaskScheduler
-  // tasks that happen to run on the same thread but weren't posted to the same
-  // SingleThreadTaskRunner.
-  mutable SequenceToken sequence_token_;
-};
-
-}  // namespace base
-
-#endif  // BASE_THREADING_THREAD_CHECKER_IMPL_H_
diff --git a/base/threading/thread_id_name_manager.cc b/base/threading/thread_id_name_manager.cc
deleted file mode 100644
index 101b57d..0000000
--- a/base/threading/thread_id_name_manager.cc
+++ /dev/null
@@ -1,133 +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 "base/threading/thread_id_name_manager.h"
-
-#include <stdlib.h>
-#include <string.h>
-
-#include "base/logging.h"
-#include "base/memory/singleton.h"
-#include "base/no_destructor.h"
-#include "base/strings/string_util.h"
-#include "base/threading/thread_local.h"
-
-namespace base {
-namespace {
-
-static const char kDefaultName[] = "";
-static std::string* g_default_name;
-
-ThreadLocalStorage::Slot& GetThreadNameTLS() {
-  static base::NoDestructor<base::ThreadLocalStorage::Slot> thread_name_tls;
-  return *thread_name_tls;
-}
-}
-
-ThreadIdNameManager::ThreadIdNameManager()
-    : main_process_name_(nullptr), main_process_id_(kInvalidThreadId) {
-  g_default_name = new std::string(kDefaultName);
-
-  AutoLock locked(lock_);
-  name_to_interned_name_[kDefaultName] = g_default_name;
-}
-
-ThreadIdNameManager::~ThreadIdNameManager() = default;
-
-ThreadIdNameManager* ThreadIdNameManager::GetInstance() {
-  return Singleton<ThreadIdNameManager,
-      LeakySingletonTraits<ThreadIdNameManager> >::get();
-}
-
-const char* ThreadIdNameManager::GetDefaultInternedString() {
-  return g_default_name->c_str();
-}
-
-void ThreadIdNameManager::RegisterThread(PlatformThreadHandle::Handle handle,
-                                         PlatformThreadId id) {
-  AutoLock locked(lock_);
-  thread_id_to_handle_[id] = handle;
-  thread_handle_to_interned_name_[handle] =
-      name_to_interned_name_[kDefaultName];
-}
-
-void ThreadIdNameManager::InstallSetNameCallback(SetNameCallback callback) {
-  AutoLock locked(lock_);
-  set_name_callback_ = std::move(callback);
-}
-
-void ThreadIdNameManager::SetName(const std::string& name) {
-  PlatformThreadId id = PlatformThread::CurrentId();
-  std::string* leaked_str = nullptr;
-  {
-    AutoLock locked(lock_);
-    NameToInternedNameMap::iterator iter = name_to_interned_name_.find(name);
-    if (iter != name_to_interned_name_.end()) {
-      leaked_str = iter->second;
-    } else {
-      leaked_str = new std::string(name);
-      name_to_interned_name_[name] = leaked_str;
-    }
-
-    ThreadIdToHandleMap::iterator id_to_handle_iter =
-        thread_id_to_handle_.find(id);
-
-    GetThreadNameTLS().Set(const_cast<char*>(leaked_str->c_str()));
-    if (set_name_callback_) {
-      set_name_callback_.Run(leaked_str->c_str());
-    }
-
-    // The main thread of a process will not be created as a Thread object which
-    // means there is no PlatformThreadHandler registered.
-    if (id_to_handle_iter == thread_id_to_handle_.end()) {
-      main_process_name_ = leaked_str;
-      main_process_id_ = id;
-      return;
-    }
-    thread_handle_to_interned_name_[id_to_handle_iter->second] = leaked_str;
-  }
-}
-
-const char* ThreadIdNameManager::GetName(PlatformThreadId id) {
-  AutoLock locked(lock_);
-
-  if (id == main_process_id_)
-    return main_process_name_->c_str();
-
-  ThreadIdToHandleMap::iterator id_to_handle_iter =
-      thread_id_to_handle_.find(id);
-  if (id_to_handle_iter == thread_id_to_handle_.end())
-    return name_to_interned_name_[kDefaultName]->c_str();
-
-  ThreadHandleToInternedNameMap::iterator handle_to_name_iter =
-      thread_handle_to_interned_name_.find(id_to_handle_iter->second);
-  return handle_to_name_iter->second->c_str();
-}
-
-const char* ThreadIdNameManager::GetNameForCurrentThread() {
-  const char* name = reinterpret_cast<const char*>(GetThreadNameTLS().Get());
-  return name ? name : kDefaultName;
-}
-
-void ThreadIdNameManager::RemoveName(PlatformThreadHandle::Handle handle,
-                                     PlatformThreadId id) {
-  AutoLock locked(lock_);
-  ThreadHandleToInternedNameMap::iterator handle_to_name_iter =
-      thread_handle_to_interned_name_.find(handle);
-
-  DCHECK(handle_to_name_iter != thread_handle_to_interned_name_.end());
-  thread_handle_to_interned_name_.erase(handle_to_name_iter);
-
-  ThreadIdToHandleMap::iterator id_to_handle_iter =
-      thread_id_to_handle_.find(id);
-  DCHECK((id_to_handle_iter!= thread_id_to_handle_.end()));
-  // The given |id| may have been re-used by the system. Make sure the
-  // mapping points to the provided |handle| before removal.
-  if (id_to_handle_iter->second != handle)
-    return;
-
-  thread_id_to_handle_.erase(id_to_handle_iter);
-}
-
-}  // namespace base
diff --git a/base/threading/thread_id_name_manager.h b/base/threading/thread_id_name_manager.h
deleted file mode 100644
index f17dc1a..0000000
--- a/base/threading/thread_id_name_manager.h
+++ /dev/null
@@ -1,80 +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_THREADING_THREAD_ID_NAME_MANAGER_H_
-#define BASE_THREADING_THREAD_ID_NAME_MANAGER_H_
-
-#include <map>
-#include <string>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/synchronization/lock.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-
-template <typename T>
-struct DefaultSingletonTraits;
-
-class BASE_EXPORT ThreadIdNameManager {
- public:
-  static ThreadIdNameManager* GetInstance();
-
-  static const char* GetDefaultInternedString();
-
-  // Register the mapping between a thread |id| and |handle|.
-  void RegisterThread(PlatformThreadHandle::Handle handle, PlatformThreadId id);
-
-  // The callback is called on the thread, immediately after the name is set.
-  // |name| is a pointer to a C string that is guaranteed to remain valid for
-  // the duration of the process.
-  using SetNameCallback = base::RepeatingCallback<void(const char* name)>;
-  void InstallSetNameCallback(SetNameCallback callback);
-
-  // Set the name for the current thread.
-  void SetName(const std::string& name);
-
-  // Get the name for the given id.
-  const char* GetName(PlatformThreadId id);
-
-  // Unlike |GetName|, this method using TLS and avoids touching |lock_|.
-  const char* GetNameForCurrentThread();
-
-  // Remove the name for the given id.
-  void RemoveName(PlatformThreadHandle::Handle handle, PlatformThreadId id);
-
- private:
-  friend struct DefaultSingletonTraits<ThreadIdNameManager>;
-
-  typedef std::map<PlatformThreadId, PlatformThreadHandle::Handle>
-      ThreadIdToHandleMap;
-  typedef std::map<PlatformThreadHandle::Handle, std::string*>
-      ThreadHandleToInternedNameMap;
-  typedef std::map<std::string, std::string*> NameToInternedNameMap;
-
-  ThreadIdNameManager();
-  ~ThreadIdNameManager();
-
-  // lock_ protects the name_to_interned_name_, thread_id_to_handle_ and
-  // thread_handle_to_interned_name_ maps.
-  Lock lock_;
-
-  NameToInternedNameMap name_to_interned_name_;
-  ThreadIdToHandleMap thread_id_to_handle_;
-  ThreadHandleToInternedNameMap thread_handle_to_interned_name_;
-
-  // Treat the main process specially as there is no PlatformThreadHandle.
-  std::string* main_process_name_;
-  PlatformThreadId main_process_id_;
-
-  SetNameCallback set_name_callback_;
-
-  DISALLOW_COPY_AND_ASSIGN(ThreadIdNameManager);
-};
-
-}  // namespace base
-
-#endif  // BASE_THREADING_THREAD_ID_NAME_MANAGER_H_
diff --git a/base/threading/thread_local.h b/base/threading/thread_local.h
deleted file mode 100644
index cad9add..0000000
--- a/base/threading/thread_local.h
+++ /dev/null
@@ -1,99 +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.
-
-// WARNING: Thread local storage is a bit tricky to get right. Please make sure
-// that this is really the proper solution for what you're trying to achieve.
-// Don't prematurely optimize, most likely you can just use a Lock.
-//
-// These classes implement a wrapper around ThreadLocalStorage::Slot. On
-// construction, they will allocate a TLS slot, and free the TLS slot on
-// destruction. No memory management (creation or destruction) is handled. This
-// means for uses of ThreadLocalPointer, you must correctly manage the memory
-// yourself, these classes will not destroy the pointer for you. There are no
-// at-thread-exit actions taken by these classes.
-//
-// ThreadLocalPointer<Type> wraps a Type*. It performs no creation or
-// destruction, so memory management must be handled elsewhere. The first call
-// to Get() on a thread will return NULL. You can update the pointer with a call
-// to Set().
-//
-// ThreadLocalBoolean wraps a bool. It will default to false if it has never
-// been set otherwise with Set().
-//
-// Thread Safety: An instance of ThreadLocalStorage is completely thread safe
-// once it has been created. If you want to dynamically create an instance, you
-// must of course properly deal with safety and race conditions. This means a
-// function-level static initializer is generally inappropiate.
-//
-// In Android, the system TLS is limited.
-//
-// Example usage:
-//   // My class is logically attached to a single thread. We cache a pointer
-//   // on the thread it was created on, so we can implement current().
-//   MyClass::MyClass() {
-//     DCHECK(Singleton<ThreadLocalPointer<MyClass> >::get()->Get() == NULL);
-//     Singleton<ThreadLocalPointer<MyClass> >::get()->Set(this);
-//   }
-//
-//   MyClass::~MyClass() {
-//     DCHECK(Singleton<ThreadLocalPointer<MyClass> >::get()->Get() != NULL);
-//     Singleton<ThreadLocalPointer<MyClass> >::get()->Set(NULL);
-//   }
-//
-//   // Return the current MyClass associated with the calling thread, can be
-//   // NULL if there isn't a MyClass associated.
-//   MyClass* MyClass::current() {
-//     return Singleton<ThreadLocalPointer<MyClass> >::get()->Get();
-//   }
-
-#ifndef BASE_THREADING_THREAD_LOCAL_H_
-#define BASE_THREADING_THREAD_LOCAL_H_
-
-#include "base/macros.h"
-#include "base/threading/thread_local_storage.h"
-
-namespace base {
-
-template <typename Type>
-class ThreadLocalPointer {
- public:
-  ThreadLocalPointer() = default;
-  ~ThreadLocalPointer() = default;
-
-  Type* Get() {
-    return static_cast<Type*>(slot_.Get());
-  }
-
-  void Set(Type* ptr) {
-    slot_.Set(const_cast<void*>(static_cast<const void*>(ptr)));
-  }
-
- private:
-  ThreadLocalStorage::Slot slot_;
-
-  DISALLOW_COPY_AND_ASSIGN(ThreadLocalPointer<Type>);
-};
-
-class ThreadLocalBoolean {
- public:
-  ThreadLocalBoolean() = default;
-  ~ThreadLocalBoolean() = default;
-
-  bool Get() {
-    return tlp_.Get() != nullptr;
-  }
-
-  void Set(bool val) {
-    tlp_.Set(val ? this : nullptr);
-  }
-
- private:
-  ThreadLocalPointer<void> tlp_;
-
-  DISALLOW_COPY_AND_ASSIGN(ThreadLocalBoolean);
-};
-
-}  // namespace base
-
-#endif  // BASE_THREADING_THREAD_LOCAL_H_
diff --git a/base/threading/thread_local_storage.cc b/base/threading/thread_local_storage.cc
deleted file mode 100644
index 466bd2f..0000000
--- a/base/threading/thread_local_storage.cc
+++ /dev/null
@@ -1,397 +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 "base/threading/thread_local_storage.h"
-
-#include "base/atomicops.h"
-#include "base/logging.h"
-#include "base/synchronization/lock.h"
-#include "build_config.h"
-
-using base::internal::PlatformThreadLocalStorage;
-
-// Chrome Thread Local Storage (TLS)
-//
-// This TLS system allows Chrome to use a single OS level TLS slot process-wide,
-// and allows us to control the slot limits instead of being at the mercy of the
-// platform. To do this, Chrome TLS replicates an array commonly found in the OS
-// thread metadata.
-//
-// Overview:
-//
-// OS TLS Slots       Per-Thread                 Per-Process Global
-//     ...
-//     []             Chrome TLS Array           Chrome TLS Metadata
-//     [] ----------> [][][][][ ][][][][]        [][][][][ ][][][][]
-//     []                      |                          |
-//     ...                     V                          V
-//                      Metadata Version           Slot Information
-//                         Your Data!
-//
-// Using a single OS TLS slot, Chrome TLS allocates an array on demand for the
-// lifetime of each thread that requests Chrome TLS data. Each per-thread TLS
-// array matches the length of the per-process global metadata array.
-//
-// A per-process global TLS metadata array tracks information about each item in
-// the per-thread array:
-//   * Status: Tracks if the slot is allocated or free to assign.
-//   * Destructor: An optional destructor to call on thread destruction for that
-//                 specific slot.
-//   * Version: Tracks the current version of the TLS slot. Each TLS slot
-//              allocation is associated with a unique version number.
-//
-//              Most OS TLS APIs guarantee that a newly allocated TLS slot is
-//              initialized to 0 for all threads. The Chrome TLS system provides
-//              this guarantee by tracking the version for each TLS slot here
-//              on each per-thread Chrome TLS array entry. Threads that access
-//              a slot with a mismatched version will receive 0 as their value.
-//              The metadata version is incremented when the client frees a
-//              slot. The per-thread metadata version is updated when a client
-//              writes to the slot. This scheme allows for constant time
-//              invalidation and avoids the need to iterate through each Chrome
-//              TLS array to mark the slot as zero.
-//
-// Just like an OS TLS API, clients of the Chrome TLS are responsible for
-// managing any necessary lifetime of the data in their slots. The only
-// convenience provided is automatic destruction when a thread ends. If a client
-// frees a slot, that client is responsible for destroying the data in the slot.
-
-namespace {
-// In order to make TLS destructors work, we need to keep around a function
-// pointer to the destructor for each slot. We keep this array of pointers in a
-// global (static) array.
-// We use the single OS-level TLS slot (giving us one pointer per thread) to
-// hold a pointer to a per-thread array (table) of slots that we allocate to
-// Chromium consumers.
-
-// g_native_tls_key is the one native TLS that we use. It stores our table.
-base::subtle::Atomic32 g_native_tls_key =
-    PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES;
-
-// The OS TLS slot has three states:
-//   * kUninitialized: Any call to Slot::Get()/Set() will create the base
-//     per-thread TLS state. On POSIX, kUninitialized must be 0.
-//   * [Memory Address]: Raw pointer to the base per-thread TLS state.
-//   * kDestroyed: The base per-thread TLS state has been freed.
-//
-// Final States:
-//   * Windows: kDestroyed. Windows does not iterate through the OS TLS to clean
-//     up the values.
-//   * POSIX: kUninitialized. POSIX iterates through TLS until all slots contain
-//     nullptr.
-//
-// More details on this design:
-//   We need some type of thread-local state to indicate that the TLS system has
-//   been destroyed. To do so, we leverage the multi-pass nature of destruction
-//   of pthread_key.
-//
-//    a) After destruction of TLS system, we set the pthread_key to a sentinel
-//       kDestroyed.
-//    b) All calls to Slot::Get() DCHECK that the state is not kDestroyed, and
-//       any system which might potentially invoke Slot::Get() after destruction
-//       of TLS must check ThreadLocalStorage::ThreadIsBeingDestroyed().
-//    c) After a full pass of the pthread_keys, on the next invocation of
-//       ConstructTlsVector(), we'll then set the key to nullptr.
-//    d) At this stage, the TLS system is back in its uninitialized state.
-//    e) If in the second pass of destruction of pthread_keys something were to
-//       re-initialize TLS [this should never happen! Since the only code which
-//       uses Chrome TLS is Chrome controlled, we should really be striving for
-//       single-pass destruction], then TLS will be re-initialized and then go
-//       through the 2-pass destruction system again. Everything should just
-//       work (TM).
-
-// The consumers of kUninitialized and kDestroyed expect void*, since that's
-// what the API exposes on both POSIX and Windows.
-void* const kUninitialized = nullptr;
-
-// A sentinel value to indicate that the TLS system has been destroyed.
-void* const kDestroyed = reinterpret_cast<void*>(1);
-
-// The maximum number of slots in our thread local storage stack.
-constexpr int kThreadLocalStorageSize = 256;
-
-enum TlsStatus {
-  FREE,
-  IN_USE,
-};
-
-struct TlsMetadata {
-  TlsStatus status;
-  base::ThreadLocalStorage::TLSDestructorFunc destructor;
-  uint32_t version;
-};
-
-struct TlsVectorEntry {
-  void* data;
-  uint32_t version;
-};
-
-// This lock isn't needed until after we've constructed the per-thread TLS
-// vector, so it's safe to use.
-base::Lock* GetTLSMetadataLock() {
-  static auto* lock = new base::Lock();
-  return lock;
-}
-TlsMetadata g_tls_metadata[kThreadLocalStorageSize];
-size_t g_last_assigned_slot = 0;
-
-// The maximum number of times to try to clear slots by calling destructors.
-// Use pthread naming convention for clarity.
-constexpr int kMaxDestructorIterations = kThreadLocalStorageSize;
-
-// This function is called to initialize our entire Chromium TLS system.
-// It may be called very early, and we need to complete most all of the setup
-// (initialization) before calling *any* memory allocator functions, which may
-// recursively depend on this initialization.
-// As a result, we use Atomics, and avoid anything (like a singleton) that might
-// require memory allocations.
-TlsVectorEntry* ConstructTlsVector() {
-  PlatformThreadLocalStorage::TLSKey key =
-      base::subtle::NoBarrier_Load(&g_native_tls_key);
-  if (key == PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES) {
-    CHECK(PlatformThreadLocalStorage::AllocTLS(&key));
-
-    // The TLS_KEY_OUT_OF_INDEXES is used to find out whether the key is set or
-    // not in NoBarrier_CompareAndSwap, but Posix doesn't have invalid key, we
-    // define an almost impossible value be it.
-    // If we really get TLS_KEY_OUT_OF_INDEXES as value of key, just alloc
-    // another TLS slot.
-    if (key == PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES) {
-      PlatformThreadLocalStorage::TLSKey tmp = key;
-      CHECK(PlatformThreadLocalStorage::AllocTLS(&key) &&
-            key != PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES);
-      PlatformThreadLocalStorage::FreeTLS(tmp);
-    }
-    // Atomically test-and-set the tls_key. If the key is
-    // TLS_KEY_OUT_OF_INDEXES, go ahead and set it. Otherwise, do nothing, as
-    // another thread already did our dirty work.
-    if (PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES !=
-        static_cast<PlatformThreadLocalStorage::TLSKey>(
-            base::subtle::NoBarrier_CompareAndSwap(
-                &g_native_tls_key,
-                PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES, key))) {
-      // We've been shortcut. Another thread replaced g_native_tls_key first so
-      // we need to destroy our index and use the one the other thread got
-      // first.
-      PlatformThreadLocalStorage::FreeTLS(key);
-      key = base::subtle::NoBarrier_Load(&g_native_tls_key);
-    }
-  }
-  CHECK_EQ(PlatformThreadLocalStorage::GetTLSValue(key), kUninitialized);
-
-  // Some allocators, such as TCMalloc, make use of thread local storage. As a
-  // result, any attempt to call new (or malloc) will lazily cause such a system
-  // to initialize, which will include registering for a TLS key. If we are not
-  // careful here, then that request to create a key will call new back, and
-  // we'll have an infinite loop. We avoid that as follows: Use a stack
-  // allocated vector, so that we don't have dependence on our allocator until
-  // our service is in place. (i.e., don't even call new until after we're
-  // setup)
-  TlsVectorEntry stack_allocated_tls_data[kThreadLocalStorageSize];
-  memset(stack_allocated_tls_data, 0, sizeof(stack_allocated_tls_data));
-  // Ensure that any rentrant calls change the temp version.
-  PlatformThreadLocalStorage::SetTLSValue(key, stack_allocated_tls_data);
-
-  // Allocate an array to store our data.
-  TlsVectorEntry* tls_data = new TlsVectorEntry[kThreadLocalStorageSize];
-  memcpy(tls_data, stack_allocated_tls_data, sizeof(stack_allocated_tls_data));
-  PlatformThreadLocalStorage::SetTLSValue(key, tls_data);
-  return tls_data;
-}
-
-void OnThreadExitInternal(TlsVectorEntry* tls_data) {
-  // This branch is for POSIX, where this function is called twice. The first
-  // pass calls dtors and sets state to kDestroyed. The second pass sets
-  // kDestroyed to kUninitialized.
-  if (tls_data == kDestroyed) {
-    PlatformThreadLocalStorage::TLSKey key =
-        base::subtle::NoBarrier_Load(&g_native_tls_key);
-    PlatformThreadLocalStorage::SetTLSValue(key, kUninitialized);
-    return;
-  }
-
-  DCHECK(tls_data);
-  // Some allocators, such as TCMalloc, use TLS. As a result, when a thread
-  // terminates, one of the destructor calls we make may be to shut down an
-  // allocator. We have to be careful that after we've shutdown all of the known
-  // destructors (perchance including an allocator), that we don't call the
-  // allocator and cause it to resurrect itself (with no possibly destructor
-  // call to follow). We handle this problem as follows: Switch to using a stack
-  // allocated vector, so that we don't have dependence on our allocator after
-  // we have called all g_tls_metadata destructors. (i.e., don't even call
-  // delete[] after we're done with destructors.)
-  TlsVectorEntry stack_allocated_tls_data[kThreadLocalStorageSize];
-  memcpy(stack_allocated_tls_data, tls_data, sizeof(stack_allocated_tls_data));
-  // Ensure that any re-entrant calls change the temp version.
-  PlatformThreadLocalStorage::TLSKey key =
-      base::subtle::NoBarrier_Load(&g_native_tls_key);
-  PlatformThreadLocalStorage::SetTLSValue(key, stack_allocated_tls_data);
-  delete[] tls_data;  // Our last dependence on an allocator.
-
-  // Snapshot the TLS Metadata so we don't have to lock on every access.
-  TlsMetadata tls_metadata[kThreadLocalStorageSize];
-  {
-    base::AutoLock auto_lock(*GetTLSMetadataLock());
-    memcpy(tls_metadata, g_tls_metadata, sizeof(g_tls_metadata));
-  }
-
-  int remaining_attempts = kMaxDestructorIterations;
-  bool need_to_scan_destructors = true;
-  while (need_to_scan_destructors) {
-    need_to_scan_destructors = false;
-    // Try to destroy the first-created-slot (which is slot 1) in our last
-    // destructor call. That user was able to function, and define a slot with
-    // no other services running, so perhaps it is a basic service (like an
-    // allocator) and should also be destroyed last. If we get the order wrong,
-    // then we'll iterate several more times, so it is really not that critical
-    // (but it might help).
-    for (int slot = 0; slot < kThreadLocalStorageSize ; ++slot) {
-      void* tls_value = stack_allocated_tls_data[slot].data;
-      if (!tls_value || tls_metadata[slot].status == TlsStatus::FREE ||
-          stack_allocated_tls_data[slot].version != tls_metadata[slot].version)
-        continue;
-
-      base::ThreadLocalStorage::TLSDestructorFunc destructor =
-          tls_metadata[slot].destructor;
-      if (!destructor)
-        continue;
-      stack_allocated_tls_data[slot].data = nullptr;  // pre-clear the slot.
-      destructor(tls_value);
-      // Any destructor might have called a different service, which then set a
-      // different slot to a non-null value. Hence we need to check the whole
-      // vector again. This is a pthread standard.
-      need_to_scan_destructors = true;
-    }
-    if (--remaining_attempts <= 0) {
-      NOTREACHED();  // Destructors might not have been called.
-      break;
-    }
-  }
-
-  // Remove our stack allocated vector.
-  PlatformThreadLocalStorage::SetTLSValue(key, kDestroyed);
-}
-
-}  // namespace
-
-namespace base {
-
-namespace internal {
-
-#if defined(OS_WIN)
-void PlatformThreadLocalStorage::OnThreadExit() {
-  PlatformThreadLocalStorage::TLSKey key =
-      base::subtle::NoBarrier_Load(&g_native_tls_key);
-  if (key == PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES)
-    return;
-  void *tls_data = GetTLSValue(key);
-
-  // On Windows, thread destruction callbacks are only invoked once per module,
-  // so there should be no way that this could be invoked twice.
-  DCHECK_NE(tls_data, kDestroyed);
-
-  // Maybe we have never initialized TLS for this thread.
-  if (tls_data == kUninitialized)
-    return;
-  OnThreadExitInternal(static_cast<TlsVectorEntry*>(tls_data));
-}
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
-void PlatformThreadLocalStorage::OnThreadExit(void* value) {
-  OnThreadExitInternal(static_cast<TlsVectorEntry*>(value));
-}
-#endif  // defined(OS_WIN)
-
-}  // namespace internal
-
-bool ThreadLocalStorage::HasBeenDestroyed() {
-  PlatformThreadLocalStorage::TLSKey key =
-      base::subtle::NoBarrier_Load(&g_native_tls_key);
-  if (key == PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES)
-    return false;
-  return PlatformThreadLocalStorage::GetTLSValue(key) == kDestroyed;
-}
-
-void ThreadLocalStorage::Slot::Initialize(TLSDestructorFunc destructor) {
-  PlatformThreadLocalStorage::TLSKey key =
-      base::subtle::NoBarrier_Load(&g_native_tls_key);
-  if (key == PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES ||
-      PlatformThreadLocalStorage::GetTLSValue(key) == kUninitialized) {
-    ConstructTlsVector();
-  }
-
-  // Grab a new slot.
-  {
-    base::AutoLock auto_lock(*GetTLSMetadataLock());
-    for (int i = 0; i < kThreadLocalStorageSize; ++i) {
-      // Tracking the last assigned slot is an attempt to find the next
-      // available slot within one iteration. Under normal usage, slots remain
-      // in use for the lifetime of the process (otherwise before we reclaimed
-      // slots, we would have run out of slots). This makes it highly likely the
-      // next slot is going to be a free slot.
-      size_t slot_candidate =
-          (g_last_assigned_slot + 1 + i) % kThreadLocalStorageSize;
-      if (g_tls_metadata[slot_candidate].status == TlsStatus::FREE) {
-        g_tls_metadata[slot_candidate].status = TlsStatus::IN_USE;
-        g_tls_metadata[slot_candidate].destructor = destructor;
-        g_last_assigned_slot = slot_candidate;
-        DCHECK_EQ(kInvalidSlotValue, slot_);
-        slot_ = slot_candidate;
-        version_ = g_tls_metadata[slot_candidate].version;
-        break;
-      }
-    }
-  }
-  CHECK_NE(slot_, kInvalidSlotValue);
-  CHECK_LT(slot_, kThreadLocalStorageSize);
-}
-
-void ThreadLocalStorage::Slot::Free() {
-  DCHECK_NE(slot_, kInvalidSlotValue);
-  DCHECK_LT(slot_, kThreadLocalStorageSize);
-  {
-    base::AutoLock auto_lock(*GetTLSMetadataLock());
-    g_tls_metadata[slot_].status = TlsStatus::FREE;
-    g_tls_metadata[slot_].destructor = nullptr;
-    ++(g_tls_metadata[slot_].version);
-  }
-  slot_ = kInvalidSlotValue;
-}
-
-void* ThreadLocalStorage::Slot::Get() const {
-  TlsVectorEntry* tls_data = static_cast<TlsVectorEntry*>(
-      PlatformThreadLocalStorage::GetTLSValue(
-          base::subtle::NoBarrier_Load(&g_native_tls_key)));
-  DCHECK_NE(tls_data, kDestroyed);
-  if (!tls_data)
-    return nullptr;
-  DCHECK_NE(slot_, kInvalidSlotValue);
-  DCHECK_LT(slot_, kThreadLocalStorageSize);
-  // Version mismatches means this slot was previously freed.
-  if (tls_data[slot_].version != version_)
-    return nullptr;
-  return tls_data[slot_].data;
-}
-
-void ThreadLocalStorage::Slot::Set(void* value) {
-  TlsVectorEntry* tls_data = static_cast<TlsVectorEntry*>(
-      PlatformThreadLocalStorage::GetTLSValue(
-          base::subtle::NoBarrier_Load(&g_native_tls_key)));
-  DCHECK_NE(tls_data, kDestroyed);
-  if (!tls_data)
-    tls_data = ConstructTlsVector();
-  DCHECK_NE(slot_, kInvalidSlotValue);
-  DCHECK_LT(slot_, kThreadLocalStorageSize);
-  tls_data[slot_].data = value;
-  tls_data[slot_].version = version_;
-}
-
-ThreadLocalStorage::Slot::Slot(TLSDestructorFunc destructor) {
-  Initialize(destructor);
-}
-
-ThreadLocalStorage::Slot::~Slot() {
-  Free();
-}
-
-}  // namespace base
diff --git a/base/threading/thread_local_storage.h b/base/threading/thread_local_storage.h
deleted file mode 100644
index f9c7e98..0000000
--- a/base/threading/thread_local_storage.h
+++ /dev/null
@@ -1,167 +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_THREADING_THREAD_LOCAL_STORAGE_H_
-#define BASE_THREADING_THREAD_LOCAL_STORAGE_H_
-
-#include <stdint.h>
-
-#include "base/atomicops.h"
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "build_config.h"
-
-#if defined(OS_WIN)
-#include "base/win/windows_types.h"
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
-#include <pthread.h>
-#endif
-
-namespace heap_profiling {
-class ScopedAllowLogging;
-}  // namespace heap_profiling
-
-namespace base {
-
-class SamplingHeapProfiler;
-
-namespace trace_event {
-class MallocDumpProvider;
-}  // namespace trace_event
-
-namespace internal {
-
-class ThreadLocalStorageTestInternal;
-
-// WARNING: You should *NOT* use this class directly.
-// PlatformThreadLocalStorage is a low-level abstraction of the OS's TLS
-// interface. Instead, you should use one of the following:
-// * ThreadLocalBoolean (from thread_local.h) for booleans.
-// * ThreadLocalPointer (from thread_local.h) for pointers.
-// * ThreadLocalStorage::StaticSlot/Slot for more direct control of the slot.
-class BASE_EXPORT PlatformThreadLocalStorage {
- public:
-
-#if defined(OS_WIN)
-  typedef unsigned long TLSKey;
-  enum : unsigned { TLS_KEY_OUT_OF_INDEXES = TLS_OUT_OF_INDEXES };
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
-  typedef pthread_key_t TLSKey;
-  // The following is a "reserved key" which is used in our generic Chromium
-  // ThreadLocalStorage implementation.  We expect that an OS will not return
-  // such a key, but if it is returned (i.e., the OS tries to allocate it) we
-  // will just request another key.
-  enum { TLS_KEY_OUT_OF_INDEXES = 0x7FFFFFFF };
-#endif
-
-  // The following methods need to be supported on each OS platform, so that
-  // the Chromium ThreadLocalStore functionality can be constructed.
-  // Chromium will use these methods to acquire a single OS slot, and then use
-  // that to support a much larger number of Chromium slots (independent of the
-  // OS restrictions).
-  // The following returns true if it successfully is able to return an OS
-  // key in |key|.
-  static bool AllocTLS(TLSKey* key);
-  // Note: FreeTLS() doesn't have to be called, it is fine with this leak, OS
-  // might not reuse released slot, you might just reset the TLS value with
-  // SetTLSValue().
-  static void FreeTLS(TLSKey key);
-  static void SetTLSValue(TLSKey key, void* value);
-  static void* GetTLSValue(TLSKey key) {
-#if defined(OS_WIN)
-    return TlsGetValue(key);
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
-    return pthread_getspecific(key);
-#endif
-  }
-
-  // Each platform (OS implementation) is required to call this method on each
-  // terminating thread when the thread is about to terminate.  This method
-  // will then call all registered destructors for slots in Chromium
-  // ThreadLocalStorage, until there are no slot values remaining as having
-  // been set on this thread.
-  // Destructors may end up being called multiple times on a terminating
-  // thread, as other destructors may re-set slots that were previously
-  // destroyed.
-#if defined(OS_WIN)
-  // Since Windows which doesn't support TLS destructor, the implementation
-  // should use GetTLSValue() to retrieve the value of TLS slot.
-  static void OnThreadExit();
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
-  // |Value| is the data stored in TLS slot, The implementation can't use
-  // GetTLSValue() to retrieve the value of slot as it has already been reset
-  // in Posix.
-  static void OnThreadExit(void* value);
-#endif
-};
-
-}  // namespace internal
-
-// Wrapper for thread local storage.  This class doesn't do much except provide
-// an API for portability.
-class BASE_EXPORT ThreadLocalStorage {
- public:
-  // Prototype for the TLS destructor function, which can be optionally used to
-  // cleanup thread local storage on thread exit.  'value' is the data that is
-  // stored in thread local storage.
-  typedef void (*TLSDestructorFunc)(void* value);
-
-  // A key representing one value stored in TLS. Use as a class member or a
-  // local variable. If you need a static storage duration variable, use the
-  // following pattern with a NoDestructor<Slot>:
-  // void MyDestructorFunc(void* value);
-  // ThreadLocalStorage::Slot& ImportantContentTLS() {
-  //   static NoDestructor<ThreadLocalStorage::Slot> important_content_tls(
-  //       &MyDestructorFunc);
-  //   return *important_content_tls;
-  // }
-  class BASE_EXPORT Slot final {
-   public:
-    // |destructor| is a pointer to a function to perform per-thread cleanup of
-    // this object.  If set to nullptr, no cleanup is done for this TLS slot.
-    explicit Slot(TLSDestructorFunc destructor = nullptr);
-    // If a destructor was set for this slot, removes the destructor so that
-    // remaining threads exiting will not free data.
-    ~Slot();
-
-    // Get the thread-local value stored in slot 'slot'.
-    // Values are guaranteed to initially be zero.
-    void* Get() const;
-
-    // Set the thread-local value stored in slot 'slot' to
-    // value 'value'.
-    void Set(void* value);
-
-   private:
-    void Initialize(TLSDestructorFunc destructor);
-    void Free();
-
-    static constexpr int kInvalidSlotValue = -1;
-    int slot_ = kInvalidSlotValue;
-    uint32_t version_ = 0;
-
-    DISALLOW_COPY_AND_ASSIGN(Slot);
-  };
-
- private:
-  // In most cases, most callers should not need access to HasBeenDestroyed().
-  // If you are working in code that runs during thread destruction, contact the
-  // base OWNERs for advice and then make a friend request.
-  //
-  // Returns |true| if Chrome's implementation of TLS has been destroyed during
-  // thread destruction. Attempting to call Slot::Get() during destruction is
-  // disallowed and will hit a DCHECK. Any code that relies on TLS during thread
-  // destruction must first check this method before calling Slot::Get().
-  friend class base::SamplingHeapProfiler;
-  friend class base::internal::ThreadLocalStorageTestInternal;
-  friend class base::trace_event::MallocDumpProvider;
-  friend class heap_profiling::ScopedAllowLogging;
-  static bool HasBeenDestroyed();
-
-  DISALLOW_COPY_AND_ASSIGN(ThreadLocalStorage);
-};
-
-}  // namespace base
-
-#endif  // BASE_THREADING_THREAD_LOCAL_STORAGE_H_
diff --git a/base/threading/thread_local_storage_posix.cc b/base/threading/thread_local_storage_posix.cc
deleted file mode 100644
index 89edeee..0000000
--- a/base/threading/thread_local_storage_posix.cc
+++ /dev/null
@@ -1,30 +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 "base/threading/thread_local_storage.h"
-
-#include "base/logging.h"
-
-namespace base {
-
-namespace internal {
-
-bool PlatformThreadLocalStorage::AllocTLS(TLSKey* key) {
-  return !pthread_key_create(key,
-      base::internal::PlatformThreadLocalStorage::OnThreadExit);
-}
-
-void PlatformThreadLocalStorage::FreeTLS(TLSKey key) {
-  int ret = pthread_key_delete(key);
-  DCHECK_EQ(ret, 0);
-}
-
-void PlatformThreadLocalStorage::SetTLSValue(TLSKey key, void* value) {
-  int ret = pthread_setspecific(key, value);
-  DCHECK_EQ(ret, 0);
-}
-
-}  // namespace internal
-
-}  // namespace base
diff --git a/base/threading/thread_local_storage_win.cc b/base/threading/thread_local_storage_win.cc
deleted file mode 100644
index a9aec31..0000000
--- a/base/threading/thread_local_storage_win.cc
+++ /dev/null
@@ -1,107 +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 "base/threading/thread_local_storage.h"
-
-#include <windows.h>
-
-#include "base/logging.h"
-
-namespace base {
-
-namespace internal {
-
-bool PlatformThreadLocalStorage::AllocTLS(TLSKey* key) {
-  TLSKey value = TlsAlloc();
-  if (value != TLS_OUT_OF_INDEXES) {
-    *key = value;
-    return true;
-  }
-  return false;
-}
-
-void PlatformThreadLocalStorage::FreeTLS(TLSKey key) {
-  BOOL ret = TlsFree(key);
-  DCHECK(ret);
-}
-
-void PlatformThreadLocalStorage::SetTLSValue(TLSKey key, void* value) {
-  BOOL ret = TlsSetValue(key, value);
-  DCHECK(ret);
-}
-
-}  // namespace internal
-
-}  // namespace base
-
-// Thread Termination Callbacks.
-// Windows doesn't support a per-thread destructor with its
-// TLS primitives.  So, we build it manually by inserting a
-// function to be called on each thread's exit.
-// This magic is from http://www.codeproject.com/threads/tls.asp
-// and it works for VC++ 7.0 and later.
-
-// Force a reference to _tls_used to make the linker create the TLS directory
-// if it's not already there.  (e.g. if __declspec(thread) is not used).
-// Force a reference to p_thread_callback_base to prevent whole program
-// optimization from discarding the variable.
-#ifdef _WIN64
-
-#pragma comment(linker, "/INCLUDE:_tls_used")
-#pragma comment(linker, "/INCLUDE:p_thread_callback_base")
-
-#else  // _WIN64
-
-#pragma comment(linker, "/INCLUDE:__tls_used")
-#pragma comment(linker, "/INCLUDE:_p_thread_callback_base")
-
-#endif  // _WIN64
-
-// Static callback function to call with each thread termination.
-void NTAPI OnThreadExit(PVOID module, DWORD reason, PVOID reserved) {
-  // On XP SP0 & SP1, the DLL_PROCESS_ATTACH is never seen. It is sent on SP2+
-  // and on W2K and W2K3. So don't assume it is sent.
-  if (DLL_THREAD_DETACH == reason || DLL_PROCESS_DETACH == reason)
-    base::internal::PlatformThreadLocalStorage::OnThreadExit();
-}
-
-// .CRT$XLA to .CRT$XLZ is an array of PIMAGE_TLS_CALLBACK pointers that are
-// called automatically by the OS loader code (not the CRT) when the module is
-// loaded and on thread creation. They are NOT called if the module has been
-// loaded by a LoadLibrary() call. It must have implicitly been loaded at
-// process startup.
-// By implicitly loaded, I mean that it is directly referenced by the main EXE
-// or by one of its dependent DLLs. Delay-loaded DLL doesn't count as being
-// implicitly loaded.
-//
-// See VC\crt\src\tlssup.c for reference.
-
-// extern "C" suppresses C++ name mangling so we know the symbol name for the
-// linker /INCLUDE:symbol pragma above.
-extern "C" {
-// The linker must not discard p_thread_callback_base.  (We force a reference
-// to this variable with a linker /INCLUDE:symbol pragma to ensure that.) If
-// this variable is discarded, the OnThreadExit function will never be called.
-#ifdef _WIN64
-
-// .CRT section is merged with .rdata on x64 so it must be constant data.
-#pragma const_seg(".CRT$XLB")
-// When defining a const variable, it must have external linkage to be sure the
-// linker doesn't discard it.
-extern const PIMAGE_TLS_CALLBACK p_thread_callback_base;
-const PIMAGE_TLS_CALLBACK p_thread_callback_base = OnThreadExit;
-
-// Reset the default section.
-#pragma const_seg()
-
-#else  // _WIN64
-
-#pragma data_seg(".CRT$XLB")
-PIMAGE_TLS_CALLBACK p_thread_callback_base = OnThreadExit;
-
-// Reset the default section.
-#pragma data_seg()
-
-#endif  // _WIN64
-}  // extern "C"
diff --git a/base/threading/thread_perftest.cc b/base/threading/thread_perftest.cc
deleted file mode 100644
index 272420e..0000000
--- a/base/threading/thread_perftest.cc
+++ /dev/null
@@ -1,318 +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 <stddef.h>
-
-#include <memory>
-#include <vector>
-
-#include "base/base_switches.h"
-#include "base/bind.h"
-#include "base/command_line.h"
-#include "base/location.h"
-#include "base/memory/ptr_util.h"
-#include "base/message_loop/message_loop.h"
-#include "base/single_thread_task_runner.h"
-#include "base/strings/stringprintf.h"
-#include "base/synchronization/condition_variable.h"
-#include "base/synchronization/lock.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/threading/thread.h"
-#include "base/time/time.h"
-#include "build_config.h"
-#include "testing/gtest/include/gtest/gtest.h"
-#include "testing/perf/perf_test.h"
-
-#if defined(OS_POSIX)
-#include <pthread.h>
-#endif
-
-namespace base {
-
-namespace {
-
-const int kNumRuns = 100000;
-
-// Base class for a threading perf-test. This sets up some threads for the
-// test and measures the clock-time in addition to time spent on each thread.
-class ThreadPerfTest : public testing::Test {
- public:
-  ThreadPerfTest()
-      : done_(WaitableEvent::ResetPolicy::AUTOMATIC,
-              WaitableEvent::InitialState::NOT_SIGNALED) {}
-
-  // To be implemented by each test. Subclass must uses threads_ such that
-  // their cpu-time can be measured. Test must return from PingPong() _and_
-  // call FinishMeasurement from any thread to complete the test.
-  virtual void Init() {
-    if (ThreadTicks::IsSupported())
-      ThreadTicks::WaitUntilInitialized();
-  }
-  virtual void PingPong(int hops) = 0;
-  virtual void Reset() {}
-
-  void TimeOnThread(base::ThreadTicks* ticks, base::WaitableEvent* done) {
-    *ticks = base::ThreadTicks::Now();
-    done->Signal();
-  }
-
-  base::ThreadTicks ThreadNow(const base::Thread& thread) {
-    base::WaitableEvent done(WaitableEvent::ResetPolicy::AUTOMATIC,
-                             WaitableEvent::InitialState::NOT_SIGNALED);
-    base::ThreadTicks ticks;
-    thread.task_runner()->PostTask(
-        FROM_HERE, base::BindOnce(&ThreadPerfTest::TimeOnThread,
-                                  base::Unretained(this), &ticks, &done));
-    done.Wait();
-    return ticks;
-  }
-
-  void RunPingPongTest(const std::string& name, unsigned num_threads) {
-    // Create threads and collect starting cpu-time for each thread.
-    std::vector<base::ThreadTicks> thread_starts;
-    while (threads_.size() < num_threads) {
-      threads_.push_back(std::make_unique<base::Thread>("PingPonger"));
-      threads_.back()->Start();
-      if (base::ThreadTicks::IsSupported())
-        thread_starts.push_back(ThreadNow(*threads_.back()));
-    }
-
-    Init();
-
-    base::TimeTicks start = base::TimeTicks::Now();
-    PingPong(kNumRuns);
-    done_.Wait();
-    base::TimeTicks end = base::TimeTicks::Now();
-
-    // Gather the cpu-time spent on each thread. This does one extra tasks,
-    // but that should be in the noise given enough runs.
-    base::TimeDelta thread_time;
-    while (threads_.size()) {
-      if (base::ThreadTicks::IsSupported()) {
-        thread_time += ThreadNow(*threads_.back()) - thread_starts.back();
-        thread_starts.pop_back();
-      }
-      threads_.pop_back();
-    }
-
-    Reset();
-
-    double num_runs = static_cast<double>(kNumRuns);
-    double us_per_task_clock = (end - start).InMicroseconds() / num_runs;
-    double us_per_task_cpu = thread_time.InMicroseconds() / num_runs;
-
-    // Clock time per task.
-    perf_test::PrintResult(
-        "task", "", name + "_time ", us_per_task_clock, "us/hop", true);
-
-    // Total utilization across threads if available (likely higher).
-    if (base::ThreadTicks::IsSupported()) {
-      perf_test::PrintResult(
-          "task", "", name + "_cpu ", us_per_task_cpu, "us/hop", true);
-    }
-  }
-
- protected:
-  void FinishMeasurement() { done_.Signal(); }
-  std::vector<std::unique_ptr<base::Thread>> threads_;
-
- private:
-  base::WaitableEvent done_;
-};
-
-// Class to test task performance by posting empty tasks back and forth.
-class TaskPerfTest : public ThreadPerfTest {
-  base::Thread* NextThread(int count) {
-    return threads_[count % threads_.size()].get();
-  }
-
-  void PingPong(int hops) override {
-    if (!hops) {
-      FinishMeasurement();
-      return;
-    }
-    NextThread(hops)->task_runner()->PostTask(
-        FROM_HERE, base::BindOnce(&ThreadPerfTest::PingPong,
-                                  base::Unretained(this), hops - 1));
-  }
-};
-
-// This tries to test the 'best-case' as well as the 'worst-case' task posting
-// performance. The best-case keeps one thread alive such that it never yeilds,
-// while the worse-case forces a context switch for every task. Four threads are
-// used to ensure the threads do yeild (with just two it might be possible for
-// both threads to stay awake if they can signal each other fast enough).
-TEST_F(TaskPerfTest, TaskPingPong) {
-  RunPingPongTest("1_Task_Threads", 1);
-  RunPingPongTest("4_Task_Threads", 4);
-}
-
-
-// Same as above, but add observers to test their perf impact.
-class MessageLoopObserver : public base::MessageLoop::TaskObserver {
- public:
-  void WillProcessTask(const base::PendingTask& pending_task) override {}
-  void DidProcessTask(const base::PendingTask& pending_task) override {}
-};
-MessageLoopObserver message_loop_observer;
-
-class TaskObserverPerfTest : public TaskPerfTest {
- public:
-  void Init() override {
-    TaskPerfTest::Init();
-    for (size_t i = 0; i < threads_.size(); i++) {
-      threads_[i]->message_loop()->AddTaskObserver(&message_loop_observer);
-    }
-  }
-};
-
-TEST_F(TaskObserverPerfTest, TaskPingPong) {
-  RunPingPongTest("1_Task_Threads_With_Observer", 1);
-  RunPingPongTest("4_Task_Threads_With_Observer", 4);
-}
-
-// Class to test our WaitableEvent performance by signaling back and fort.
-// WaitableEvent is templated so we can also compare with other versions.
-template <typename WaitableEventType>
-class EventPerfTest : public ThreadPerfTest {
- public:
-  void Init() override {
-    for (size_t i = 0; i < threads_.size(); i++) {
-      events_.push_back(std::make_unique<WaitableEventType>(
-          WaitableEvent::ResetPolicy::AUTOMATIC,
-          WaitableEvent::InitialState::NOT_SIGNALED));
-    }
-  }
-
-  void Reset() override { events_.clear(); }
-
-  void WaitAndSignalOnThread(size_t event) {
-    size_t next_event = (event + 1) % events_.size();
-    int my_hops = 0;
-    do {
-      events_[event]->Wait();
-      my_hops = --remaining_hops_;  // We own 'hops' between Wait and Signal.
-      events_[next_event]->Signal();
-    } while (my_hops > 0);
-    // Once we are done, all threads will signal as hops passes zero.
-    // We only signal completion once, on the thread that reaches zero.
-    if (!my_hops)
-      FinishMeasurement();
-  }
-
-  void PingPong(int hops) override {
-    remaining_hops_ = hops;
-    for (size_t i = 0; i < threads_.size(); i++) {
-      threads_[i]->task_runner()->PostTask(
-          FROM_HERE, base::BindOnce(&EventPerfTest::WaitAndSignalOnThread,
-                                    base::Unretained(this), i));
-    }
-
-    // Kick off the Signal ping-ponging.
-    events_.front()->Signal();
-  }
-
-  int remaining_hops_;
-  std::vector<std::unique_ptr<WaitableEventType>> events_;
-};
-
-// Similar to the task posting test, this just tests similar functionality
-// using WaitableEvents. We only test four threads (worst-case), but we
-// might want to craft a way to test the best-case (where the thread doesn't
-// end up blocking because the event is already signalled).
-typedef EventPerfTest<base::WaitableEvent> WaitableEventThreadPerfTest;
-TEST_F(WaitableEventThreadPerfTest, EventPingPong) {
-  RunPingPongTest("4_WaitableEvent_Threads", 4);
-}
-
-// Build a minimal event using ConditionVariable.
-class ConditionVariableEvent {
- public:
-  ConditionVariableEvent(WaitableEvent::ResetPolicy reset_policy,
-                         WaitableEvent::InitialState initial_state)
-      : cond_(&lock_), signaled_(false) {
-    DCHECK_EQ(WaitableEvent::ResetPolicy::AUTOMATIC, reset_policy);
-    DCHECK_EQ(WaitableEvent::InitialState::NOT_SIGNALED, initial_state);
-  }
-
-  void Signal() {
-    {
-      base::AutoLock scoped_lock(lock_);
-      signaled_ = true;
-    }
-    cond_.Signal();
-  }
-
-  void Wait() {
-    base::AutoLock scoped_lock(lock_);
-    while (!signaled_)
-      cond_.Wait();
-    signaled_ = false;
-  }
-
- private:
-  base::Lock lock_;
-  base::ConditionVariable cond_;
-  bool signaled_;
-};
-
-// This is meant to test the absolute minimal context switching time
-// using our own base synchronization code.
-typedef EventPerfTest<ConditionVariableEvent> ConditionVariablePerfTest;
-TEST_F(ConditionVariablePerfTest, EventPingPong) {
-  RunPingPongTest("4_ConditionVariable_Threads", 4);
-}
-#if defined(OS_POSIX)
-
-// Absolutely 100% minimal posix waitable event. If there is a better/faster
-// way to force a context switch, we should use that instead.
-class PthreadEvent {
- public:
-  PthreadEvent(WaitableEvent::ResetPolicy reset_policy,
-               WaitableEvent::InitialState initial_state) {
-    DCHECK_EQ(WaitableEvent::ResetPolicy::AUTOMATIC, reset_policy);
-    DCHECK_EQ(WaitableEvent::InitialState::NOT_SIGNALED, initial_state);
-    pthread_mutex_init(&mutex_, nullptr);
-    pthread_cond_init(&cond_, nullptr);
-    signaled_ = false;
-  }
-
-  ~PthreadEvent() {
-    pthread_cond_destroy(&cond_);
-    pthread_mutex_destroy(&mutex_);
-  }
-
-  void Signal() {
-    pthread_mutex_lock(&mutex_);
-    signaled_ = true;
-    pthread_mutex_unlock(&mutex_);
-    pthread_cond_signal(&cond_);
-  }
-
-  void Wait() {
-    pthread_mutex_lock(&mutex_);
-    while (!signaled_)
-      pthread_cond_wait(&cond_, &mutex_);
-    signaled_ = false;
-    pthread_mutex_unlock(&mutex_);
-  }
-
- private:
-  bool signaled_;
-  pthread_mutex_t mutex_;
-  pthread_cond_t cond_;
-};
-
-// This is meant to test the absolute minimal context switching time.
-// If there is any faster way to do this we should substitute it in.
-typedef EventPerfTest<PthreadEvent> PthreadEventPerfTest;
-TEST_F(PthreadEventPerfTest, EventPingPong) {
-  RunPingPongTest("4_PthreadCondVar_Threads", 4);
-}
-
-#endif
-
-}  // namespace
-
-}  // namespace base
diff --git a/base/threading/thread_restrictions.cc b/base/threading/thread_restrictions.cc
deleted file mode 100644
index 633bcb2..0000000
--- a/base/threading/thread_restrictions.cc
+++ /dev/null
@@ -1,176 +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 "base/threading/thread_restrictions.h"
-
-#if DCHECK_IS_ON()
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/threading/thread_local.h"
-
-namespace base {
-
-namespace {
-
-LazyInstance<ThreadLocalBoolean>::Leaky g_blocking_disallowed =
-    LAZY_INSTANCE_INITIALIZER;
-
-LazyInstance<ThreadLocalBoolean>::Leaky
-    g_singleton_disallowed = LAZY_INSTANCE_INITIALIZER;
-
-LazyInstance<ThreadLocalBoolean>::Leaky g_base_sync_primitives_disallowed =
-    LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace
-
-void AssertBlockingAllowed() {
-  DCHECK(!g_blocking_disallowed.Get().Get())
-      << "Function marked as blocking was called from a scope that disallows "
-         "blocking! If this task is running inside the TaskScheduler, it needs "
-         "to have MayBlock() in its TaskTraits. Otherwise, consider making "
-         "this blocking work asynchronous or, as a last resort, you may use "
-         "ScopedAllowBlocking in a narrow scope.";
-}
-
-void DisallowBlocking() {
-  g_blocking_disallowed.Get().Set(true);
-}
-
-ScopedDisallowBlocking::ScopedDisallowBlocking()
-    : was_disallowed_(g_blocking_disallowed.Get().Get()) {
-  g_blocking_disallowed.Get().Set(true);
-}
-
-ScopedDisallowBlocking::~ScopedDisallowBlocking() {
-  DCHECK(g_blocking_disallowed.Get().Get());
-  g_blocking_disallowed.Get().Set(was_disallowed_);
-}
-
-ScopedAllowBlocking::ScopedAllowBlocking()
-    : was_disallowed_(g_blocking_disallowed.Get().Get()) {
-  g_blocking_disallowed.Get().Set(false);
-}
-
-ScopedAllowBlocking::~ScopedAllowBlocking() {
-  DCHECK(!g_blocking_disallowed.Get().Get());
-  g_blocking_disallowed.Get().Set(was_disallowed_);
-}
-
-void DisallowBaseSyncPrimitives() {
-  g_base_sync_primitives_disallowed.Get().Set(true);
-}
-
-ScopedAllowBaseSyncPrimitives::ScopedAllowBaseSyncPrimitives()
-    : was_disallowed_(g_base_sync_primitives_disallowed.Get().Get()) {
-  DCHECK(!g_blocking_disallowed.Get().Get())
-      << "To allow //base sync primitives in a scope where blocking is "
-         "disallowed use ScopedAllowBaseSyncPrimitivesOutsideBlockingScope.";
-  g_base_sync_primitives_disallowed.Get().Set(false);
-}
-
-ScopedAllowBaseSyncPrimitives::~ScopedAllowBaseSyncPrimitives() {
-  DCHECK(!g_base_sync_primitives_disallowed.Get().Get());
-  g_base_sync_primitives_disallowed.Get().Set(was_disallowed_);
-}
-
-ScopedAllowBaseSyncPrimitivesOutsideBlockingScope::
-    ScopedAllowBaseSyncPrimitivesOutsideBlockingScope()
-    : was_disallowed_(g_base_sync_primitives_disallowed.Get().Get()) {
-  g_base_sync_primitives_disallowed.Get().Set(false);
-}
-
-ScopedAllowBaseSyncPrimitivesOutsideBlockingScope::
-    ~ScopedAllowBaseSyncPrimitivesOutsideBlockingScope() {
-  DCHECK(!g_base_sync_primitives_disallowed.Get().Get());
-  g_base_sync_primitives_disallowed.Get().Set(was_disallowed_);
-}
-
-ScopedAllowBaseSyncPrimitivesForTesting::
-    ScopedAllowBaseSyncPrimitivesForTesting()
-    : was_disallowed_(g_base_sync_primitives_disallowed.Get().Get()) {
-  g_base_sync_primitives_disallowed.Get().Set(false);
-}
-
-ScopedAllowBaseSyncPrimitivesForTesting::
-    ~ScopedAllowBaseSyncPrimitivesForTesting() {
-  DCHECK(!g_base_sync_primitives_disallowed.Get().Get());
-  g_base_sync_primitives_disallowed.Get().Set(was_disallowed_);
-}
-
-namespace internal {
-
-void AssertBaseSyncPrimitivesAllowed() {
-  DCHECK(!g_base_sync_primitives_disallowed.Get().Get())
-      << "Waiting on a //base sync primitive is not allowed on this thread to "
-         "prevent jank and deadlock. If waiting on a //base sync primitive is "
-         "unavoidable, do it within the scope of a "
-         "ScopedAllowBaseSyncPrimitives. If in a test, "
-         "use ScopedAllowBaseSyncPrimitivesForTesting.";
-}
-
-void ResetThreadRestrictionsForTesting() {
-  g_blocking_disallowed.Get().Set(false);
-  g_singleton_disallowed.Get().Set(false);
-  g_base_sync_primitives_disallowed.Get().Set(false);
-}
-
-}  // namespace internal
-
-ThreadRestrictions::ScopedAllowIO::ScopedAllowIO()
-    : was_allowed_(SetIOAllowed(true)) {}
-
-ThreadRestrictions::ScopedAllowIO::~ScopedAllowIO() {
-  SetIOAllowed(was_allowed_);
-}
-
-// static
-bool ThreadRestrictions::SetIOAllowed(bool allowed) {
-  bool previous_disallowed = g_blocking_disallowed.Get().Get();
-  g_blocking_disallowed.Get().Set(!allowed);
-  return !previous_disallowed;
-}
-
-// static
-bool ThreadRestrictions::SetSingletonAllowed(bool allowed) {
-  bool previous_disallowed = g_singleton_disallowed.Get().Get();
-  g_singleton_disallowed.Get().Set(!allowed);
-  return !previous_disallowed;
-}
-
-// static
-void ThreadRestrictions::AssertSingletonAllowed() {
-  if (g_singleton_disallowed.Get().Get()) {
-    NOTREACHED() << "LazyInstance/Singleton is not allowed to be used on this "
-                 << "thread.  Most likely it's because this thread is not "
-                 << "joinable (or the current task is running with "
-                 << "TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN semantics), so "
-                 << "AtExitManager may have deleted the object on shutdown, "
-                 << "leading to a potential shutdown crash. If you need to use "
-                 << "the object from this context, it'll have to be updated to "
-                 << "use Leaky traits.";
-  }
-}
-
-// static
-void ThreadRestrictions::DisallowWaiting() {
-  DisallowBaseSyncPrimitives();
-}
-
-bool ThreadRestrictions::SetWaitAllowed(bool allowed) {
-  bool previous_disallowed = g_base_sync_primitives_disallowed.Get().Get();
-  g_base_sync_primitives_disallowed.Get().Set(!allowed);
-  return !previous_disallowed;
-}
-
-ThreadRestrictions::ScopedAllowWait::ScopedAllowWait()
-    : was_allowed_(SetWaitAllowed(true)) {}
-
-ThreadRestrictions::ScopedAllowWait::~ScopedAllowWait() {
-  SetWaitAllowed(was_allowed_);
-}
-
-}  // namespace base
-
-#endif  // DCHECK_IS_ON()
diff --git a/base/threading/thread_restrictions.h b/base/threading/thread_restrictions.h
deleted file mode 100644
index 57f2f21..0000000
--- a/base/threading/thread_restrictions.h
+++ /dev/null
@@ -1,506 +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_THREADING_THREAD_RESTRICTIONS_H_
-#define BASE_THREADING_THREAD_RESTRICTIONS_H_
-
-#include "base/base_export.h"
-#include "base/gtest_prod_util.h"
-#include "base/logging.h"
-#include "base/macros.h"
-
-class BrowserProcessImpl;
-class HistogramSynchronizer;
-class NativeBackendKWallet;
-class KeyStorageLinux;
-
-namespace android_webview {
-class AwFormDatabaseService;
-class CookieManager;
-class ScopedAllowInitGLBindings;
-}
-
-namespace cc {
-class CompletionEvent;
-class SingleThreadTaskGraphRunner;
-}
-namespace chromeos {
-class BlockingMethodCaller;
-namespace system {
-class StatisticsProviderImpl;
-}
-}
-namespace chrome_browser_net {
-class Predictor;
-}
-namespace content {
-class BrowserGpuChannelHostFactory;
-class BrowserGpuMemoryBufferManager;
-class BrowserMainLoop;
-class BrowserProcessSubThread;
-class BrowserShutdownProfileDumper;
-class BrowserSurfaceViewManager;
-class BrowserTestBase;
-class CategorizedWorkerPool;
-class NestedMessagePumpAndroid;
-class ScopedAllowWaitForAndroidLayoutTests;
-class ScopedAllowWaitForDebugURL;
-class SessionStorageDatabase;
-class SoftwareOutputDeviceMus;
-class SynchronousCompositor;
-class SynchronousCompositorHost;
-class SynchronousCompositorSyncCallBridge;
-class TextInputClientMac;
-}  // namespace content
-namespace cronet {
-class CronetPrefsManager;
-class CronetURLRequestContext;
-}  // namespace cronet
-namespace dbus {
-class Bus;
-}
-namespace disk_cache {
-class BackendImpl;
-class InFlightIO;
-}
-namespace functions {
-class ExecScriptScopedAllowBaseSyncPrimitives;
-}
-namespace gpu {
-class GpuChannelHost;
-}
-namespace leveldb {
-class LevelDBMojoProxy;
-}
-namespace media {
-class AudioInputDevice;
-class BlockingUrlProtocol;
-}
-namespace midi {
-class TaskService;  // https://crbug.com/796830
-}
-namespace mojo {
-class CoreLibraryInitializer;
-class SyncCallRestrictions;
-namespace edk {
-class ScopedIPCSupport;
-}
-}
-namespace rlz_lib {
-class FinancialPing;
-}
-namespace ui {
-class CommandBufferClientImpl;
-class CommandBufferLocal;
-class GpuState;
-class MaterialDesignController;
-}
-namespace net {
-class MultiThreadedCertVerifierScopedAllowBaseSyncPrimitives;
-class NetworkChangeNotifierMac;
-namespace internal {
-class AddressTrackerLinux;
-}
-}
-
-namespace remoting {
-class AutoThread;
-}
-
-namespace resource_coordinator {
-class TabManagerDelegate;
-}
-
-namespace service_manager {
-class ServiceProcessLauncher;
-}
-
-namespace shell_integration {
-class LaunchXdgUtilityScopedAllowBaseSyncPrimitives;
-}
-
-namespace ui {
-class WindowResizeHelperMac;
-}
-
-namespace views {
-class ScreenMus;
-}
-
-namespace viz {
-class ServerGpuMemoryBufferManager;
-}
-
-namespace webrtc {
-class DesktopConfigurationMonitor;
-}
-
-namespace base {
-
-namespace android {
-class JavaHandlerThread;
-}
-
-namespace internal {
-class TaskTracker;
-}
-
-class GetAppOutputScopedAllowBaseSyncPrimitives;
-class SimpleThread;
-class StackSamplingProfiler;
-class Thread;
-class ThreadTestHelper;
-
-#if DCHECK_IS_ON()
-#define INLINE_IF_DCHECK_IS_OFF BASE_EXPORT
-#define EMPTY_BODY_IF_DCHECK_IS_OFF
-#else
-#define INLINE_IF_DCHECK_IS_OFF inline
-#define EMPTY_BODY_IF_DCHECK_IS_OFF \
-  {}
-#endif
-
-// A "blocking call" refers to any call that causes the calling thread to wait
-// off-CPU. It includes but is not limited to calls that wait on synchronous
-// file I/O operations: read or write a file from disk, interact with a pipe or
-// a socket, rename or delete a file, enumerate files in a directory, etc.
-// Acquiring a low contention lock is not considered a blocking call.
-
-// Asserts that blocking calls are allowed in the current scope.
-//
-// Style tip: It's best if you put AssertBlockingAllowed() checks as close to
-// the blocking call as possible. For example:
-//
-// void ReadFile() {
-//   PreWork();
-//
-//   base::AssertBlockingAllowed();
-//   fopen(...);
-//
-//   PostWork();
-// }
-//
-// void Bar() {
-//   ReadFile();
-// }
-//
-// void Foo() {
-//   Bar();
-// }
-INLINE_IF_DCHECK_IS_OFF void AssertBlockingAllowed()
-    EMPTY_BODY_IF_DCHECK_IS_OFF;
-
-// Disallows blocking on the current thread.
-INLINE_IF_DCHECK_IS_OFF void DisallowBlocking() EMPTY_BODY_IF_DCHECK_IS_OFF;
-
-// Disallows blocking calls within its scope.
-class BASE_EXPORT ScopedDisallowBlocking {
- public:
-  ScopedDisallowBlocking() EMPTY_BODY_IF_DCHECK_IS_OFF;
-  ~ScopedDisallowBlocking() EMPTY_BODY_IF_DCHECK_IS_OFF;
-
- private:
-#if DCHECK_IS_ON()
-  const bool was_disallowed_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedDisallowBlocking);
-};
-
-// ScopedAllowBlocking(ForTesting) allow blocking calls within a scope where
-// they are normally disallowed.
-//
-// Avoid using this. Prefer making blocking calls from tasks posted to
-// base::TaskScheduler with base::MayBlock().
-class BASE_EXPORT ScopedAllowBlocking {
- private:
-  // This can only be instantiated by friends. Use ScopedAllowBlockingForTesting
-  // in unit tests to avoid the friend requirement.
-  FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest, ScopedAllowBlocking);
-  friend class android_webview::ScopedAllowInitGLBindings;
-  friend class content::BrowserProcessSubThread;
-  friend class cronet::CronetPrefsManager;
-  friend class cronet::CronetURLRequestContext;
-  friend class media::AudioInputDevice;
-  friend class mojo::CoreLibraryInitializer;
-  friend class resource_coordinator::TabManagerDelegate;  // crbug.com/778703
-  friend class ui::MaterialDesignController;
-  friend class ScopedAllowBlockingForTesting;
-  friend class StackSamplingProfiler;
-
-  ScopedAllowBlocking() EMPTY_BODY_IF_DCHECK_IS_OFF;
-  ~ScopedAllowBlocking() EMPTY_BODY_IF_DCHECK_IS_OFF;
-
-#if DCHECK_IS_ON()
-  const bool was_disallowed_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedAllowBlocking);
-};
-
-class ScopedAllowBlockingForTesting {
- public:
-  ScopedAllowBlockingForTesting() {}
-  ~ScopedAllowBlockingForTesting() {}
-
- private:
-#if DCHECK_IS_ON()
-  ScopedAllowBlocking scoped_allow_blocking_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedAllowBlockingForTesting);
-};
-
-// "Waiting on a //base sync primitive" refers to calling one of these methods:
-// - base::WaitableEvent::*Wait*
-// - base::ConditionVariable::*Wait*
-// - base::Process::WaitForExit*
-
-// Disallows waiting on a //base sync primitive on the current thread.
-INLINE_IF_DCHECK_IS_OFF void DisallowBaseSyncPrimitives()
-    EMPTY_BODY_IF_DCHECK_IS_OFF;
-
-// ScopedAllowBaseSyncPrimitives(ForTesting)(OutsideBlockingScope) allow waiting
-// on a //base sync primitive within a scope where this is normally disallowed.
-//
-// Avoid using this.
-//
-// Instead of waiting on a WaitableEvent or a ConditionVariable, put the work
-// that should happen after the wait in a callback and post that callback from
-// where the WaitableEvent or ConditionVariable would have been signaled. If
-// something needs to be scheduled after many tasks have executed, use
-// base::BarrierClosure.
-//
-// On Windows, join processes asynchronously using base::win::ObjectWatcher.
-
-// This can only be used in a scope where blocking is allowed.
-class BASE_EXPORT ScopedAllowBaseSyncPrimitives {
- private:
-  // This can only be instantiated by friends. Use
-  // ScopedAllowBaseSyncPrimitivesForTesting in unit tests to avoid the friend
-  // requirement.
-  FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest,
-                           ScopedAllowBaseSyncPrimitives);
-  FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest,
-                           ScopedAllowBaseSyncPrimitivesResetsState);
-  FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest,
-                           ScopedAllowBaseSyncPrimitivesWithBlockingDisallowed);
-  friend class base::GetAppOutputScopedAllowBaseSyncPrimitives;
-  friend class content::BrowserProcessSubThread;
-  friend class content::SessionStorageDatabase;
-  friend class functions::ExecScriptScopedAllowBaseSyncPrimitives;
-  friend class leveldb::LevelDBMojoProxy;
-  friend class media::BlockingUrlProtocol;
-  friend class net::MultiThreadedCertVerifierScopedAllowBaseSyncPrimitives;
-  friend class rlz_lib::FinancialPing;
-  friend class shell_integration::LaunchXdgUtilityScopedAllowBaseSyncPrimitives;
-  friend class webrtc::DesktopConfigurationMonitor;
-
-  ScopedAllowBaseSyncPrimitives() EMPTY_BODY_IF_DCHECK_IS_OFF;
-  ~ScopedAllowBaseSyncPrimitives() EMPTY_BODY_IF_DCHECK_IS_OFF;
-
-#if DCHECK_IS_ON()
-  const bool was_disallowed_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedAllowBaseSyncPrimitives);
-};
-
-// This can be used in a scope where blocking is disallowed.
-class BASE_EXPORT ScopedAllowBaseSyncPrimitivesOutsideBlockingScope {
- private:
-  // This can only be instantiated by friends. Use
-  // ScopedAllowBaseSyncPrimitivesForTesting in unit tests to avoid the friend
-  // requirement.
-  FRIEND_TEST_ALL_PREFIXES(ThreadRestrictionsTest,
-                           ScopedAllowBaseSyncPrimitivesOutsideBlockingScope);
-  FRIEND_TEST_ALL_PREFIXES(
-      ThreadRestrictionsTest,
-      ScopedAllowBaseSyncPrimitivesOutsideBlockingScopeResetsState);
-  friend class ::KeyStorageLinux;
-  friend class content::SynchronousCompositor;
-  friend class content::SynchronousCompositorHost;
-  friend class content::SynchronousCompositorSyncCallBridge;
-  friend class midi::TaskService;  // https://crbug.com/796830
-  // Not used in production yet, https://crbug.com/844078.
-  friend class service_manager::ServiceProcessLauncher;
-
-  ScopedAllowBaseSyncPrimitivesOutsideBlockingScope()
-      EMPTY_BODY_IF_DCHECK_IS_OFF;
-  ~ScopedAllowBaseSyncPrimitivesOutsideBlockingScope()
-      EMPTY_BODY_IF_DCHECK_IS_OFF;
-
-#if DCHECK_IS_ON()
-  const bool was_disallowed_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedAllowBaseSyncPrimitivesOutsideBlockingScope);
-};
-
-// This can be used in tests without being a friend of
-// ScopedAllowBaseSyncPrimitives(OutsideBlockingScope).
-class BASE_EXPORT ScopedAllowBaseSyncPrimitivesForTesting {
- public:
-  ScopedAllowBaseSyncPrimitivesForTesting() EMPTY_BODY_IF_DCHECK_IS_OFF;
-  ~ScopedAllowBaseSyncPrimitivesForTesting() EMPTY_BODY_IF_DCHECK_IS_OFF;
-
- private:
-#if DCHECK_IS_ON()
-  const bool was_disallowed_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedAllowBaseSyncPrimitivesForTesting);
-};
-
-namespace internal {
-
-// Asserts that waiting on a //base sync primitive is allowed in the current
-// scope.
-INLINE_IF_DCHECK_IS_OFF void AssertBaseSyncPrimitivesAllowed()
-    EMPTY_BODY_IF_DCHECK_IS_OFF;
-
-// Resets all thread restrictions on the current thread.
-INLINE_IF_DCHECK_IS_OFF void ResetThreadRestrictionsForTesting()
-    EMPTY_BODY_IF_DCHECK_IS_OFF;
-
-}  // namespace internal
-
-class BASE_EXPORT ThreadRestrictions {
- public:
-  // Constructing a ScopedAllowIO temporarily allows IO for the current
-  // thread.  Doing this is almost certainly always incorrect.
-  //
-  // DEPRECATED. Use ScopedAllowBlocking(ForTesting).
-  class BASE_EXPORT ScopedAllowIO {
-   public:
-    ScopedAllowIO() EMPTY_BODY_IF_DCHECK_IS_OFF;
-    ~ScopedAllowIO() EMPTY_BODY_IF_DCHECK_IS_OFF;
-
-   private:
-#if DCHECK_IS_ON()
-    const bool was_allowed_;
-#endif
-
-    DISALLOW_COPY_AND_ASSIGN(ScopedAllowIO);
-  };
-
-#if DCHECK_IS_ON()
-  // Set whether the current thread to make IO calls.
-  // Threads start out in the *allowed* state.
-  // Returns the previous value.
-  //
-  // DEPRECATED. Use ScopedAllowBlocking(ForTesting) or ScopedDisallowBlocking.
-  static bool SetIOAllowed(bool allowed);
-
-  // Set whether the current thread can use singletons.  Returns the previous
-  // value.
-  static bool SetSingletonAllowed(bool allowed);
-
-  // Check whether the current thread is allowed to use singletons (Singleton /
-  // LazyInstance).  DCHECKs if not.
-  static void AssertSingletonAllowed();
-
-  // Disable waiting on the current thread. Threads start out in the *allowed*
-  // state. Returns the previous value.
-  //
-  // DEPRECATED. Use DisallowBaseSyncPrimitives.
-  static void DisallowWaiting();
-#else
-  // Inline the empty definitions of these functions so that they can be
-  // compiled out.
-  static bool SetIOAllowed(bool allowed) { return true; }
-  static bool SetSingletonAllowed(bool allowed) { return true; }
-  static void AssertSingletonAllowed() {}
-  static void DisallowWaiting() {}
-#endif
-
- private:
-  // DO NOT ADD ANY OTHER FRIEND STATEMENTS, talk to jam or brettw first.
-  // BEGIN ALLOWED USAGE.
-  friend class android_webview::AwFormDatabaseService;
-  friend class android_webview::CookieManager;
-  friend class base::StackSamplingProfiler;
-  friend class content::BrowserMainLoop;
-  friend class content::BrowserShutdownProfileDumper;
-  friend class content::BrowserSurfaceViewManager;
-  friend class content::BrowserTestBase;
-  friend class content::NestedMessagePumpAndroid;
-  friend class content::ScopedAllowWaitForAndroidLayoutTests;
-  friend class content::ScopedAllowWaitForDebugURL;
-  friend class ::HistogramSynchronizer;
-  friend class internal::TaskTracker;
-  friend class cc::CompletionEvent;
-  friend class cc::SingleThreadTaskGraphRunner;
-  friend class content::CategorizedWorkerPool;
-  friend class remoting::AutoThread;
-  friend class ui::WindowResizeHelperMac;
-  friend class MessagePumpDefault;
-  friend class SimpleThread;
-  friend class Thread;
-  friend class ThreadTestHelper;
-  friend class PlatformThread;
-  friend class android::JavaHandlerThread;
-  friend class mojo::SyncCallRestrictions;
-  friend class mojo::edk::ScopedIPCSupport;
-  friend class ui::CommandBufferClientImpl;
-  friend class ui::CommandBufferLocal;
-  friend class ui::GpuState;
-
-  // END ALLOWED USAGE.
-  // BEGIN USAGE THAT NEEDS TO BE FIXED.
-  friend class ::chromeos::BlockingMethodCaller;  // http://crbug.com/125360
-  friend class ::chromeos::system::StatisticsProviderImpl;  // http://crbug.com/125385
-  friend class chrome_browser_net::Predictor;     // http://crbug.com/78451
-  friend class
-      content::BrowserGpuChannelHostFactory;      // http://crbug.com/125248
-  friend class
-      content::BrowserGpuMemoryBufferManager;     // http://crbug.com/420368
-  friend class content::TextInputClientMac;       // http://crbug.com/121917
-  friend class dbus::Bus;                         // http://crbug.com/125222
-  friend class disk_cache::BackendImpl;           // http://crbug.com/74623
-  friend class disk_cache::InFlightIO;            // http://crbug.com/74623
-  friend class gpu::GpuChannelHost;               // http://crbug.com/125264
-  friend class net::internal::AddressTrackerLinux;  // http://crbug.com/125097
-  friend class net::NetworkChangeNotifierMac;     // http://crbug.com/125097
-  friend class ::BrowserProcessImpl;              // http://crbug.com/125207
-  friend class ::NativeBackendKWallet;            // http://crbug.com/125331
-#if !defined(OFFICIAL_BUILD)
-  friend class content::SoftwareOutputDeviceMus;  // Interim non-production code
-#endif
-  friend class views::ScreenMus;
-  friend class viz::ServerGpuMemoryBufferManager;
-// END USAGE THAT NEEDS TO BE FIXED.
-
-#if DCHECK_IS_ON()
-  // DEPRECATED. Use ScopedAllowBaseSyncPrimitives.
-  static bool SetWaitAllowed(bool allowed);
-#else
-  static bool SetWaitAllowed(bool allowed) { return true; }
-#endif
-
-  // Constructing a ScopedAllowWait temporarily allows waiting on the current
-  // thread.  Doing this is almost always incorrect, which is why we limit who
-  // can use this through friend. If you find yourself needing to use this, find
-  // another way. Talk to jam or brettw.
-  //
-  // DEPRECATED. Use ScopedAllowBaseSyncPrimitives.
-  class BASE_EXPORT ScopedAllowWait {
-   public:
-    ScopedAllowWait() EMPTY_BODY_IF_DCHECK_IS_OFF;
-    ~ScopedAllowWait() EMPTY_BODY_IF_DCHECK_IS_OFF;
-
-   private:
-#if DCHECK_IS_ON()
-    const bool was_allowed_;
-#endif
-
-    DISALLOW_COPY_AND_ASSIGN(ScopedAllowWait);
-  };
-
-  DISALLOW_IMPLICIT_CONSTRUCTORS(ThreadRestrictions);
-};
-
-}  // namespace base
-
-#endif  // BASE_THREADING_THREAD_RESTRICTIONS_H_
diff --git a/base/threading/thread_task_runner_handle.cc b/base/threading/thread_task_runner_handle.cc
deleted file mode 100644
index 314b303..0000000
--- a/base/threading/thread_task_runner_handle.cc
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright 2016 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/threading/thread_task_runner_handle.h"
-
-#include <utility>
-
-#include "base/bind.h"
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/memory/ptr_util.h"
-#include "base/run_loop.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-#include "base/threading/thread_local.h"
-
-namespace base {
-
-namespace {
-
-base::LazyInstance<base::ThreadLocalPointer<ThreadTaskRunnerHandle>>::Leaky
-    thread_task_runner_tls = LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace
-
-// static
-scoped_refptr<SingleThreadTaskRunner> ThreadTaskRunnerHandle::Get() {
-  ThreadTaskRunnerHandle* current = thread_task_runner_tls.Pointer()->Get();
-  CHECK(current) << "Error: This caller requires a single-threaded context "
-                    "(i.e. the current task needs to run from a "
-                    "SingleThreadTaskRunner).";
-  return current->task_runner_;
-}
-
-// static
-bool ThreadTaskRunnerHandle::IsSet() {
-  return !!thread_task_runner_tls.Pointer()->Get();
-}
-
-// static
-ScopedClosureRunner ThreadTaskRunnerHandle::OverrideForTesting(
-    scoped_refptr<SingleThreadTaskRunner> overriding_task_runner) {
-  // OverrideForTesting() is not compatible with a SequencedTaskRunnerHandle
-  // being set (but SequencedTaskRunnerHandle::IsSet() includes
-  // ThreadTaskRunnerHandle::IsSet() so that's discounted as the only valid
-  // excuse for it to be true). Sadly this means that tests that merely need a
-  // SequencedTaskRunnerHandle on their main thread can be forced to use a
-  // ThreadTaskRunnerHandle if they're also using test task runners (that
-  // OverrideForTesting() when running their tasks from said main thread). To
-  // solve this: sequence_task_runner_handle.cc and thread_task_runner_handle.cc
-  // would have to be merged into a single impl file and share TLS state. This
-  // was deemed unecessary for now as most tests should use higher level
-  // constructs and not have to instantiate task runner handles on their own.
-  DCHECK(!SequencedTaskRunnerHandle::IsSet() || IsSet());
-
-  if (!IsSet()) {
-    auto top_level_ttrh = std::make_unique<ThreadTaskRunnerHandle>(
-        std::move(overriding_task_runner));
-    return ScopedClosureRunner(base::BindOnce(
-        [](std::unique_ptr<ThreadTaskRunnerHandle> ttrh_to_release) {},
-        std::move(top_level_ttrh)));
-  }
-
-  ThreadTaskRunnerHandle* ttrh = thread_task_runner_tls.Pointer()->Get();
-  // Swap the two (and below bind |overriding_task_runner|, which is now the
-  // previous one, as the |task_runner_to_restore|).
-  ttrh->task_runner_.swap(overriding_task_runner);
-
-  auto no_running_during_override =
-      std::make_unique<RunLoop::ScopedDisallowRunningForTesting>();
-
-  return ScopedClosureRunner(base::BindOnce(
-      [](scoped_refptr<SingleThreadTaskRunner> task_runner_to_restore,
-         SingleThreadTaskRunner* expected_task_runner_before_restore,
-         std::unique_ptr<RunLoop::ScopedDisallowRunningForTesting>
-             no_running_during_override) {
-        ThreadTaskRunnerHandle* ttrh = thread_task_runner_tls.Pointer()->Get();
-
-        DCHECK_EQ(expected_task_runner_before_restore, ttrh->task_runner_.get())
-            << "Nested overrides must expire their ScopedClosureRunners "
-               "in LIFO order.";
-
-        ttrh->task_runner_.swap(task_runner_to_restore);
-      },
-      std::move(overriding_task_runner),
-      base::Unretained(ttrh->task_runner_.get()),
-      std::move(no_running_during_override)));
-}
-
-ThreadTaskRunnerHandle::ThreadTaskRunnerHandle(
-    scoped_refptr<SingleThreadTaskRunner> task_runner)
-    : task_runner_(std::move(task_runner)) {
-  DCHECK(task_runner_->BelongsToCurrentThread());
-  // No SequencedTaskRunnerHandle (which includes ThreadTaskRunnerHandles)
-  // should already be set for this thread.
-  DCHECK(!SequencedTaskRunnerHandle::IsSet());
-  thread_task_runner_tls.Pointer()->Set(this);
-}
-
-ThreadTaskRunnerHandle::~ThreadTaskRunnerHandle() {
-  DCHECK(task_runner_->BelongsToCurrentThread());
-  DCHECK_EQ(thread_task_runner_tls.Pointer()->Get(), this);
-  thread_task_runner_tls.Pointer()->Set(nullptr);
-}
-
-}  // namespace base
diff --git a/base/threading/thread_task_runner_handle.h b/base/threading/thread_task_runner_handle.h
deleted file mode 100644
index f6b71d7..0000000
--- a/base/threading/thread_task_runner_handle.h
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright 2016 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_THREADING_THREAD_TASK_RUNNER_HANDLE_H_
-#define BASE_THREADING_THREAD_TASK_RUNNER_HANDLE_H_
-
-#include "base/base_export.h"
-#include "base/callback_helpers.h"
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/single_thread_task_runner.h"
-
-namespace base {
-
-// ThreadTaskRunnerHandle stores a reference to a thread's TaskRunner
-// in thread-local storage.  Callers can then retrieve the TaskRunner
-// for the current thread by calling ThreadTaskRunnerHandle::Get().
-// At most one TaskRunner may be bound to each thread at a time.
-// Prefer SequencedTaskRunnerHandle to this unless thread affinity is required.
-class BASE_EXPORT ThreadTaskRunnerHandle {
- public:
-  // Gets the SingleThreadTaskRunner for the current thread.
-  static scoped_refptr<SingleThreadTaskRunner> Get();
-
-  // Returns true if the SingleThreadTaskRunner is already created for
-  // the current thread.
-  static bool IsSet();
-
-  // Overrides ThreadTaskRunnerHandle::Get()'s |task_runner_| to point at
-  // |overriding_task_runner| until the returned ScopedClosureRunner goes out of
-  // scope (instantiates a ThreadTaskRunnerHandle for that scope if |!IsSet()|).
-  // Nested overrides are allowed but callers must ensure the
-  // ScopedClosureRunners expire in LIFO (stack) order. Note: nesting
-  // ThreadTaskRunnerHandles isn't generally desired but it's useful in unit
-  // tests where multiple task runners can share the main thread for simplicity
-  // and determinism.
-  static ScopedClosureRunner OverrideForTesting(
-      scoped_refptr<SingleThreadTaskRunner> overriding_task_runner)
-      WARN_UNUSED_RESULT;
-
-  // Binds |task_runner| to the current thread. |task_runner| must belong
-  // to the current thread for this to succeed.
-  explicit ThreadTaskRunnerHandle(
-      scoped_refptr<SingleThreadTaskRunner> task_runner);
-  ~ThreadTaskRunnerHandle();
-
- private:
-  scoped_refptr<SingleThreadTaskRunner> task_runner_;
-
-  DISALLOW_COPY_AND_ASSIGN(ThreadTaskRunnerHandle);
-};
-
-}  // namespace base
-
-#endif  // BASE_THREADING_THREAD_TASK_RUNNER_HANDLE_H_
diff --git a/base/threading/watchdog.cc b/base/threading/watchdog.cc
deleted file mode 100644
index d214bb2..0000000
--- a/base/threading/watchdog.cc
+++ /dev/null
@@ -1,185 +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 "base/threading/watchdog.h"
-
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-
-namespace {
-
-// When the debugger breaks (when we alarm), all the other alarms that are
-// armed will expire (also alarm).  To diminish this effect, we track any
-// delay due to debugger breaks, and we *try* to adjust the effective start
-// time of other alarms to step past the debugging break.
-// Without this safety net, any alarm will typically trigger a host of follow
-// on alarms from callers that specify old times.
-
-struct StaticData {
-  // Lock for access of static data...
-  Lock lock;
-
-  // When did we last alarm and get stuck (for a while) in a debugger?
-  TimeTicks last_debugged_alarm_time;
-
-  // How long did we sit on a break in the debugger?
-  TimeDelta last_debugged_alarm_delay;
-};
-
-StaticData* GetStaticData() {
-  static auto* static_data = new StaticData();
-  return static_data;
-}
-
-}  // namespace
-
-// Start thread running in a Disarmed state.
-Watchdog::Watchdog(const TimeDelta& duration,
-                   const std::string& thread_watched_name,
-                   bool enabled)
-  : enabled_(enabled),
-    lock_(),
-    condition_variable_(&lock_),
-    state_(DISARMED),
-    duration_(duration),
-    thread_watched_name_(thread_watched_name),
-    delegate_(this) {
-  if (!enabled_)
-    return;  // Don't start thread, or doing anything really.
-  enabled_ = PlatformThread::Create(0,  // Default stack size.
-                                    &delegate_,
-                                    &handle_);
-  DCHECK(enabled_);
-}
-
-// Notify watchdog thread, and wait for it to finish up.
-Watchdog::~Watchdog() {
-  if (!enabled_)
-    return;
-  if (!IsJoinable())
-    Cleanup();
-  condition_variable_.Signal();
-  PlatformThread::Join(handle_);
-}
-
-void Watchdog::Cleanup() {
-  if (!enabled_)
-    return;
-  {
-    AutoLock lock(lock_);
-    state_ = SHUTDOWN;
-  }
-  condition_variable_.Signal();
-}
-
-bool Watchdog::IsJoinable() {
-  if (!enabled_)
-    return true;
-  AutoLock lock(lock_);
-  return (state_ == JOINABLE);
-}
-
-void Watchdog::Arm() {
-  ArmAtStartTime(TimeTicks::Now());
-}
-
-void Watchdog::ArmSomeTimeDeltaAgo(const TimeDelta& time_delta) {
-  ArmAtStartTime(TimeTicks::Now() - time_delta);
-}
-
-// Start clock for watchdog.
-void Watchdog::ArmAtStartTime(const TimeTicks start_time) {
-  {
-    AutoLock lock(lock_);
-    start_time_ = start_time;
-    state_ = ARMED;
-  }
-  // Force watchdog to wake up, and go to sleep with the timer ticking with the
-  // proper duration.
-  condition_variable_.Signal();
-}
-
-// Disable watchdog so that it won't do anything when time expires.
-void Watchdog::Disarm() {
-  AutoLock lock(lock_);
-  state_ = DISARMED;
-  // We don't need to signal, as the watchdog will eventually wake up, and it
-  // will check its state and time, and act accordingly.
-}
-
-void Watchdog::Alarm() {
-}
-
-//------------------------------------------------------------------------------
-// Internal private methods that the watchdog thread uses.
-
-void Watchdog::ThreadDelegate::ThreadMain() {
-  SetThreadName();
-  TimeDelta remaining_duration;
-  StaticData* static_data = GetStaticData();
-  while (1) {
-    AutoLock lock(watchdog_->lock_);
-    while (DISARMED == watchdog_->state_)
-      watchdog_->condition_variable_.Wait();
-    if (SHUTDOWN == watchdog_->state_) {
-      watchdog_->state_ = JOINABLE;
-      return;
-    }
-    DCHECK(ARMED == watchdog_->state_);
-    remaining_duration = watchdog_->duration_ -
-        (TimeTicks::Now() - watchdog_->start_time_);
-    if (remaining_duration.InMilliseconds() > 0) {
-      // Spurios wake?  Timer drifts?  Go back to sleep for remaining time.
-      watchdog_->condition_variable_.TimedWait(remaining_duration);
-      continue;
-    }
-    // We overslept, so this seems like a real alarm.
-    // Watch out for a user that stopped the debugger on a different alarm!
-    {
-      AutoLock static_lock(static_data->lock);
-      if (static_data->last_debugged_alarm_time > watchdog_->start_time_) {
-        // False alarm: we started our clock before the debugger break (last
-        // alarm time).
-        watchdog_->start_time_ += static_data->last_debugged_alarm_delay;
-        if (static_data->last_debugged_alarm_time > watchdog_->start_time_)
-          // Too many alarms must have taken place.
-          watchdog_->state_ = DISARMED;
-        continue;
-      }
-    }
-    watchdog_->state_ = DISARMED;  // Only alarm at most once.
-    TimeTicks last_alarm_time = TimeTicks::Now();
-    {
-      AutoUnlock unlock(watchdog_->lock_);
-      watchdog_->Alarm();  // Set a break point here to debug on alarms.
-    }
-    TimeDelta last_alarm_delay = TimeTicks::Now() - last_alarm_time;
-    if (last_alarm_delay <= TimeDelta::FromMilliseconds(2))
-      continue;
-    // Ignore race of two alarms/breaks going off at roughly the same time.
-    AutoLock static_lock(static_data->lock);
-    // This was a real debugger break.
-    static_data->last_debugged_alarm_time = last_alarm_time;
-    static_data->last_debugged_alarm_delay = last_alarm_delay;
-  }
-}
-
-void Watchdog::ThreadDelegate::SetThreadName() const {
-  std::string name = watchdog_->thread_watched_name_ + " Watchdog";
-  PlatformThread::SetName(name);
-}
-
-// static
-void Watchdog::ResetStaticData() {
-  StaticData* static_data = GetStaticData();
-  AutoLock lock(static_data->lock);
-  // See https://crbug.com/734232 for why this cannot be zero-initialized.
-  static_data->last_debugged_alarm_time = TimeTicks::Min();
-  static_data->last_debugged_alarm_delay = TimeDelta();
-}
-
-}  // namespace base
diff --git a/base/threading/watchdog.h b/base/threading/watchdog.h
deleted file mode 100644
index f806984..0000000
--- a/base/threading/watchdog.h
+++ /dev/null
@@ -1,96 +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.
-
-// The Watchdog class creates a second thread that can Alarm if a specific
-// duration of time passes without proper attention.  The duration of time is
-// specified at construction time.  The Watchdog may be used many times by
-// simply calling Arm() (to start timing) and Disarm() (to reset the timer).
-// The Watchdog is typically used under a debugger, where the stack traces on
-// other threads can be examined if/when the Watchdog alarms.
-
-// Some watchdogs will be enabled or disabled via command line switches. To
-// facilitate such code, an "enabled" argument for the constuctor can be used
-// to permanently disable the watchdog.  Disabled watchdogs don't even spawn
-// a second thread, and their methods call (Arm() and Disarm()) return very
-// quickly.
-
-#ifndef BASE_THREADING_WATCHDOG_H_
-#define BASE_THREADING_WATCHDOG_H_
-
-#include <string>
-
-#include "base/base_export.h"
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/synchronization/condition_variable.h"
-#include "base/synchronization/lock.h"
-#include "base/threading/platform_thread.h"
-#include "base/time/time.h"
-
-namespace base {
-
-class BASE_EXPORT Watchdog {
- public:
-  // Constructor specifies how long the Watchdog will wait before alarming.
-  Watchdog(const TimeDelta& duration,
-           const std::string& thread_watched_name,
-           bool enabled);
-  virtual ~Watchdog();
-
-  // Notify watchdog thread to finish up. Sets the state_ to SHUTDOWN.
-  void Cleanup();
-
-  // Returns true if we state_ is JOINABLE (which indicates that Watchdog has
-  // exited).
-  bool IsJoinable();
-
-  // Start timing, and alarm when time expires (unless we're disarm()ed.)
-  void Arm();  // Arm  starting now.
-  void ArmSomeTimeDeltaAgo(const TimeDelta& time_delta);
-  void ArmAtStartTime(const TimeTicks start_time);
-
-  // Reset time, and do not set off the alarm.
-  void Disarm();
-
-  // Alarm is called if the time expires after an Arm() without someone calling
-  // Disarm().  This method can be overridden to create testable classes.
-  virtual void Alarm();
-
-  // Reset static data to initial state. Useful for tests, to ensure
-  // they are independent.
-  static void ResetStaticData();
-
- private:
-  class ThreadDelegate : public PlatformThread::Delegate {
-   public:
-    explicit ThreadDelegate(Watchdog* watchdog) : watchdog_(watchdog) {
-    }
-    void ThreadMain() override;
-
-   private:
-    void SetThreadName() const;
-
-    Watchdog* watchdog_;
-  };
-
-  enum State {ARMED, DISARMED, SHUTDOWN, JOINABLE };
-
-  bool enabled_;
-
-  Lock lock_;  // Mutex for state_.
-  ConditionVariable condition_variable_;
-  State state_;
-  const TimeDelta duration_;  // How long after start_time_ do we alarm?
-  const std::string thread_watched_name_;
-  PlatformThreadHandle handle_;
-  ThreadDelegate delegate_;  // Store it, because it must outlive the thread.
-
-  TimeTicks start_time_;  // Start of epoch, and alarm after duration_.
-
-  DISALLOW_COPY_AND_ASSIGN(Watchdog);
-};
-
-}  // namespace base
-
-#endif  // BASE_THREADING_WATCHDOG_H_
diff --git a/base/time/default_clock.cc b/base/time/default_clock.cc
deleted file mode 100644
index aa08f52..0000000
--- a/base/time/default_clock.cc
+++ /dev/null
@@ -1,23 +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 "base/time/default_clock.h"
-
-#include "base/lazy_instance.h"
-
-namespace base {
-
-DefaultClock::~DefaultClock() = default;
-
-Time DefaultClock::Now() const {
-  return Time::Now();
-}
-
-// static
-DefaultClock* DefaultClock::GetInstance() {
-  static LazyInstance<DefaultClock>::Leaky instance = LAZY_INSTANCE_INITIALIZER;
-  return instance.Pointer();
-}
-
-}  // namespace base
diff --git a/base/time/default_clock.h b/base/time/default_clock.h
deleted file mode 100644
index a0e175b..0000000
--- a/base/time/default_clock.h
+++ /dev/null
@@ -1,28 +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_TIME_DEFAULT_CLOCK_H_
-#define BASE_TIME_DEFAULT_CLOCK_H_
-
-#include "base/base_export.h"
-#include "base/compiler_specific.h"
-#include "base/time/clock.h"
-
-namespace base {
-
-// DefaultClock is a Clock implementation that uses Time::Now().
-class BASE_EXPORT DefaultClock : public Clock {
- public:
-  ~DefaultClock() override;
-
-  // Simply returns Time::Now().
-  Time Now() const override;
-
-  // Returns a shared instance of DefaultClock. This is thread-safe.
-  static DefaultClock* GetInstance();
-};
-
-}  // namespace base
-
-#endif  // BASE_TIME_DEFAULT_CLOCK_H_
diff --git a/base/timer/hi_res_timer_manager.h b/base/timer/hi_res_timer_manager.h
deleted file mode 100644
index 13477c0..0000000
--- a/base/timer/hi_res_timer_manager.h
+++ /dev/null
@@ -1,42 +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_TIMER_HI_RES_TIMER_MANAGER_H_
-#define BASE_TIMER_HI_RES_TIMER_MANAGER_H_
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/timer/timer.h"
-#include "build_config.h"
-
-namespace base {
-
-// Ensures that the Windows high resolution timer is only used
-// when not running on battery power.
-class BASE_EXPORT HighResolutionTimerManager {
- public:
-  HighResolutionTimerManager();
-  ~HighResolutionTimerManager();
-
-  // Returns true if the hi resolution clock could be used right now.
-  bool hi_res_clock_available() const { return hi_res_clock_available_; }
-
- private:
-  // Enable or disable the faster multimedia timer.
-  void UseHiResClock(bool use);
-
-  bool hi_res_clock_available_;
-
-#if defined(OS_WIN)
-  // Timer for polling the high resolution timer usage.
-  base::RepeatingTimer timer_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(HighResolutionTimerManager);
-};
-
-}  // namespace base
-
-#endif  // BASE_TIMER_HI_RES_TIMER_MANAGER_H_
diff --git a/base/timer/hi_res_timer_manager_posix.cc b/base/timer/hi_res_timer_manager_posix.cc
deleted file mode 100644
index d2a3aa5..0000000
--- a/base/timer/hi_res_timer_manager_posix.cc
+++ /dev/null
@@ -1,27 +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 "base/timer/hi_res_timer_manager.h"
-
-// On POSIX we don't need to do anything special with the system timer.
-
-namespace base {
-
-HighResolutionTimerManager::HighResolutionTimerManager()
-    : hi_res_clock_available_(false) {
-}
-
-HighResolutionTimerManager::~HighResolutionTimerManager() = default;
-
-void HighResolutionTimerManager::OnPowerStateChange(bool on_battery_power) {
-}
-
-void HighResolutionTimerManager::OnSuspend() {}
-
-void HighResolutionTimerManager::OnResume() {}
-
-void HighResolutionTimerManager::UseHiResClock(bool use) {
-}
-
-}  // namespace base
diff --git a/base/timer/hi_res_timer_manager_win.cc b/base/timer/hi_res_timer_manager_win.cc
deleted file mode 100644
index 9c3a78e..0000000
--- a/base/timer/hi_res_timer_manager_win.cc
+++ /dev/null
@@ -1,45 +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 "base/timer/hi_res_timer_manager.h"
-
-#include <algorithm>
-
-#include "base/atomicops.h"
-#include "base/task_scheduler/post_task.h"
-#include "base/time/time.h"
-
-namespace base {
-
-namespace {
-
-constexpr TimeDelta kUsageSampleInterval = TimeDelta::FromMinutes(10);
-
-void ReportHighResolutionTimerUsage() {
-  // Reset usage for the next interval.
-  Time::ResetHighResolutionTimerUsage();
-}
-
-}  // namespace
-
-HighResolutionTimerManager::HighResolutionTimerManager()
-    : hi_res_clock_available_(false) {
-  // Start polling the high resolution timer usage.
-  Time::ResetHighResolutionTimerUsage();
-  timer_.Start(FROM_HERE, kUsageSampleInterval,
-               Bind(&ReportHighResolutionTimerUsage));
-}
-
-HighResolutionTimerManager::~HighResolutionTimerManager() {
-  UseHiResClock(false);
-}
-
-void HighResolutionTimerManager::UseHiResClock(bool use) {
-  if (use == hi_res_clock_available_)
-    return;
-  hi_res_clock_available_ = use;
-  Time::EnableHighResolutionTimer(use);
-}
-
-}  // namespace base
diff --git a/base/timer/timer.cc b/base/timer/timer.cc
deleted file mode 100644
index 99cd839..0000000
--- a/base/timer/timer.cc
+++ /dev/null
@@ -1,268 +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 "base/timer/timer.h"
-
-#include <stddef.h>
-
-#include <utility>
-
-#include "base/logging.h"
-#include "base/memory/ptr_util.h"
-#include "base/memory/ref_counted.h"
-#include "base/threading/platform_thread.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-#include "base/time/tick_clock.h"
-
-namespace base {
-
-// BaseTimerTaskInternal is a simple delegate for scheduling a callback to Timer
-// on the current sequence. It also handles the following edge cases:
-// - deleted by the task runner.
-// - abandoned (orphaned) by Timer.
-class BaseTimerTaskInternal {
- public:
-  explicit BaseTimerTaskInternal(Timer* timer)
-      : timer_(timer) {
-  }
-
-  ~BaseTimerTaskInternal() {
-    // This task may be getting cleared because the task runner has been
-    // destructed.  If so, don't leave Timer with a dangling pointer
-    // to this.
-    if (timer_)
-      timer_->AbandonAndStop();
-  }
-
-  void Run() {
-    // |timer_| is nullptr if we were abandoned.
-    if (!timer_)
-      return;
-
-    // |this| will be deleted by the task runner, so Timer needs to forget us:
-    timer_->scheduled_task_ = nullptr;
-
-    // Although Timer should not call back into |this|, let's clear |timer_|
-    // first to be pedantic.
-    Timer* timer = timer_;
-    timer_ = nullptr;
-    timer->RunScheduledTask();
-  }
-
-  // The task remains in the queue, but nothing will happen when it runs.
-  void Abandon() { timer_ = nullptr; }
-
- private:
-  Timer* timer_;
-
-  DISALLOW_COPY_AND_ASSIGN(BaseTimerTaskInternal);
-};
-
-Timer::Timer(bool retain_user_task, bool is_repeating)
-    : Timer(retain_user_task, is_repeating, nullptr) {}
-
-Timer::Timer(bool retain_user_task,
-             bool is_repeating,
-             const TickClock* tick_clock)
-    : scheduled_task_(nullptr),
-      is_repeating_(is_repeating),
-      retain_user_task_(retain_user_task),
-      tick_clock_(tick_clock),
-      is_running_(false) {
-  // It is safe for the timer to be created on a different thread/sequence than
-  // the one from which the timer APIs are called. The first call to the
-  // checker's CalledOnValidSequence() method will re-bind the checker, and
-  // later calls will verify that the same task runner is used.
-  origin_sequence_checker_.DetachFromSequence();
-}
-
-Timer::Timer(const Location& posted_from,
-             TimeDelta delay,
-             const base::Closure& user_task,
-             bool is_repeating)
-    : Timer(posted_from, delay, user_task, is_repeating, nullptr) {}
-
-Timer::Timer(const Location& posted_from,
-             TimeDelta delay,
-             const base::Closure& user_task,
-             bool is_repeating,
-             const TickClock* tick_clock)
-    : scheduled_task_(nullptr),
-      posted_from_(posted_from),
-      delay_(delay),
-      user_task_(user_task),
-      is_repeating_(is_repeating),
-      retain_user_task_(true),
-      tick_clock_(tick_clock),
-      is_running_(false) {
-  // See comment in other constructor.
-  origin_sequence_checker_.DetachFromSequence();
-}
-
-Timer::~Timer() {
-  DCHECK(origin_sequence_checker_.CalledOnValidSequence());
-  AbandonAndStop();
-}
-
-bool Timer::IsRunning() const {
-  DCHECK(origin_sequence_checker_.CalledOnValidSequence());
-  return is_running_;
-}
-
-TimeDelta Timer::GetCurrentDelay() const {
-  DCHECK(origin_sequence_checker_.CalledOnValidSequence());
-  return delay_;
-}
-
-void Timer::SetTaskRunner(scoped_refptr<SequencedTaskRunner> task_runner) {
-  // Do not allow changing the task runner when the Timer is running.
-  // Don't check for |origin_sequence_checker_.CalledOnValidSequence()| here to
-  // allow the use case of constructing the Timer and immediatetly invoking
-  // SetTaskRunner() before starting it (CalledOnValidSequence() would undo the
-  // DetachFromSequence() from the constructor). The |!is_running| check kind of
-  // verifies the same thing (and TSAN should catch callers that do it wrong but
-  // somehow evade all debug checks).
-  DCHECK(!is_running_);
-  task_runner_.swap(task_runner);
-}
-
-void Timer::Start(const Location& posted_from,
-                  TimeDelta delay,
-                  const base::Closure& user_task) {
-  DCHECK(origin_sequence_checker_.CalledOnValidSequence());
-
-  posted_from_ = posted_from;
-  delay_ = delay;
-  user_task_ = user_task;
-
-  Reset();
-}
-
-void Timer::Stop() {
-  // TODO(gab): Enable this when it's no longer called racily from
-  // RunScheduledTask(): https://crbug.com/587199.
-  // DCHECK(origin_sequence_checker_.CalledOnValidSequence());
-
-  is_running_ = false;
-
-  // It's safe to destroy or restart Timer on another sequence after Stop().
-  origin_sequence_checker_.DetachFromSequence();
-
-  if (!retain_user_task_)
-    user_task_.Reset();
-  // No more member accesses here: |this| could be deleted after freeing
-  // |user_task_|.
-}
-
-void Timer::Reset() {
-  DCHECK(origin_sequence_checker_.CalledOnValidSequence());
-  DCHECK(!user_task_.is_null());
-
-  // If there's no pending task, start one up and return.
-  if (!scheduled_task_) {
-    PostNewScheduledTask(delay_);
-    return;
-  }
-
-  // Set the new |desired_run_time_|.
-  if (delay_ > TimeDelta::FromMicroseconds(0))
-    desired_run_time_ = Now() + delay_;
-  else
-    desired_run_time_ = TimeTicks();
-
-  // We can use the existing scheduled task if it arrives before the new
-  // |desired_run_time_|.
-  if (desired_run_time_ >= scheduled_run_time_) {
-    is_running_ = true;
-    return;
-  }
-
-  // We can't reuse the |scheduled_task_|, so abandon it and post a new one.
-  AbandonScheduledTask();
-  PostNewScheduledTask(delay_);
-}
-
-TimeTicks Timer::Now() const {
-  // TODO(gab): Enable this when it's no longer called racily from
-  // RunScheduledTask(): https://crbug.com/587199.
-  // DCHECK(origin_sequence_checker_.CalledOnValidSequence());
-  return tick_clock_ ? tick_clock_->NowTicks() : TimeTicks::Now();
-}
-
-void Timer::PostNewScheduledTask(TimeDelta delay) {
-  // TODO(gab): Enable this when it's no longer called racily from
-  // RunScheduledTask(): https://crbug.com/587199.
-  // DCHECK(origin_sequence_checker_.CalledOnValidSequence());
-  DCHECK(!scheduled_task_);
-  is_running_ = true;
-  scheduled_task_ = new BaseTimerTaskInternal(this);
-  if (delay > TimeDelta::FromMicroseconds(0)) {
-    // TODO(gab): Posting BaseTimerTaskInternal::Run to another sequence makes
-    // this code racy. https://crbug.com/587199
-    GetTaskRunner()->PostDelayedTask(
-        posted_from_,
-        base::BindOnce(&BaseTimerTaskInternal::Run,
-                       base::Owned(scheduled_task_)),
-        delay);
-    scheduled_run_time_ = desired_run_time_ = Now() + delay;
-  } else {
-    GetTaskRunner()->PostTask(posted_from_,
-                              base::BindOnce(&BaseTimerTaskInternal::Run,
-                                             base::Owned(scheduled_task_)));
-    scheduled_run_time_ = desired_run_time_ = TimeTicks();
-  }
-}
-
-scoped_refptr<SequencedTaskRunner> Timer::GetTaskRunner() {
-  return task_runner_.get() ? task_runner_ : SequencedTaskRunnerHandle::Get();
-}
-
-void Timer::AbandonScheduledTask() {
-  // TODO(gab): Enable this when it's no longer called racily from
-  // RunScheduledTask() -> Stop(): https://crbug.com/587199.
-  // DCHECK(origin_sequence_checker_.CalledOnValidSequence());
-  if (scheduled_task_) {
-    scheduled_task_->Abandon();
-    scheduled_task_ = nullptr;
-  }
-}
-
-void Timer::RunScheduledTask() {
-  // TODO(gab): Enable this when it's no longer called racily:
-  // https://crbug.com/587199.
-  // DCHECK(origin_sequence_checker_.CalledOnValidSequence());
-
-  // Task may have been disabled.
-  if (!is_running_)
-    return;
-
-  // First check if we need to delay the task because of a new target time.
-  if (desired_run_time_ > scheduled_run_time_) {
-    // Now() can be expensive, so only call it if we know the user has changed
-    // the |desired_run_time_|.
-    TimeTicks now = Now();
-    // Task runner may have called us late anyway, so only post a continuation
-    // task if the |desired_run_time_| is in the future.
-    if (desired_run_time_ > now) {
-      // Post a new task to span the remaining time.
-      PostNewScheduledTask(desired_run_time_ - now);
-      return;
-    }
-  }
-
-  // Make a local copy of the task to run. The Stop method will reset the
-  // |user_task_| member if |retain_user_task_| is false.
-  base::Closure task = user_task_;
-
-  if (is_repeating_)
-    PostNewScheduledTask(delay_);
-  else
-    Stop();
-
-  task.Run();
-
-  // No more member accesses here: |this| could be deleted at this point.
-}
-
-}  // namespace base
diff --git a/base/timer/timer.h b/base/timer/timer.h
deleted file mode 100644
index 2777632..0000000
--- a/base/timer/timer.h
+++ /dev/null
@@ -1,295 +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.
-
-// OneShotTimer and RepeatingTimer provide a simple timer API.  As the names
-// suggest, OneShotTimer calls you back once after a time delay expires.
-// RepeatingTimer on the other hand calls you back periodically with the
-// prescribed time interval.
-//
-// OneShotTimer and RepeatingTimer both cancel the timer when they go out of
-// scope, which makes it easy to ensure that you do not get called when your
-// object has gone out of scope.  Just instantiate a OneShotTimer or
-// RepeatingTimer as a member variable of the class for which you wish to
-// receive timer events.
-//
-// Sample RepeatingTimer usage:
-//
-//   class MyClass {
-//    public:
-//     void StartDoingStuff() {
-//       timer_.Start(FROM_HERE, TimeDelta::FromSeconds(1),
-//                    this, &MyClass::DoStuff);
-//     }
-//     void StopDoingStuff() {
-//       timer_.Stop();
-//     }
-//    private:
-//     void DoStuff() {
-//       // This method is called every second to do stuff.
-//       ...
-//     }
-//     base::RepeatingTimer timer_;
-//   };
-//
-// Both OneShotTimer and RepeatingTimer also support a Reset method, which
-// allows you to easily defer the timer event until the timer delay passes once
-// again.  So, in the above example, if 0.5 seconds have already passed,
-// calling Reset on |timer_| would postpone DoStuff by another 1 second.  In
-// other words, Reset is shorthand for calling Stop and then Start again with
-// the same arguments.
-//
-// These APIs are not thread safe. All methods must be called from the same
-// sequence (not necessarily the construction sequence), except for the
-// destructor and SetTaskRunner().
-// - The destructor may be called from any sequence when the timer is not
-// running and there is no scheduled task active, i.e. when Start() has never
-// been called or after AbandonAndStop() has been called.
-// - SetTaskRunner() may be called from any sequence when the timer is not
-// running, i.e. when Start() has never been called or Stop() has been called
-// since the last Start().
-//
-// By default, the scheduled tasks will be run on the same sequence that the
-// Timer was *started on*, but this can be changed *prior* to Start() via
-// SetTaskRunner().
-
-#ifndef BASE_TIMER_TIMER_H_
-#define BASE_TIMER_TIMER_H_
-
-// IMPORTANT: If you change timer code, make sure that all tests (including
-// disabled ones) from timer_unittests.cc pass locally. Some are disabled
-// because they're flaky on the buildbot, but when you run them locally you
-// should be able to tell the difference.
-
-#include <memory>
-
-#include "base/base_export.h"
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/callback.h"
-#include "base/location.h"
-#include "base/macros.h"
-#include "base/sequence_checker_impl.h"
-#include "base/sequenced_task_runner.h"
-#include "base/time/time.h"
-
-namespace base {
-
-class BaseTimerTaskInternal;
-class TickClock;
-
-//-----------------------------------------------------------------------------
-// This class wraps TaskRunner::PostDelayedTask to manage delayed and repeating
-// tasks. See meta comment above for thread-safety requirements.
-//
-class BASE_EXPORT Timer {
- public:
-  // Construct a timer in repeating or one-shot mode. Start must be called later
-  // to set task info. |retain_user_task| determines whether the user_task is
-  // retained or reset when it runs or stops. If |tick_clock| is provided, it is
-  // used instead of TimeTicks::Now() to get TimeTicks when scheduling tasks.
-  Timer(bool retain_user_task, bool is_repeating);
-  Timer(bool retain_user_task, bool is_repeating, const TickClock* tick_clock);
-
-  // Construct a timer with retained task info. If |tick_clock| is provided, it
-  // is used instead of TimeTicks::Now() to get TimeTicks when scheduling tasks.
-  Timer(const Location& posted_from,
-        TimeDelta delay,
-        const base::Closure& user_task,
-        bool is_repeating);
-  Timer(const Location& posted_from,
-        TimeDelta delay,
-        const base::Closure& user_task,
-        bool is_repeating,
-        const TickClock* tick_clock);
-
-  virtual ~Timer();
-
-  // Returns true if the timer is running (i.e., not stopped).
-  virtual bool IsRunning() const;
-
-  // Returns the current delay for this timer.
-  virtual TimeDelta GetCurrentDelay() const;
-
-  // Set the task runner on which the task should be scheduled. This method can
-  // only be called before any tasks have been scheduled. If |task_runner| runs
-  // tasks on a different sequence than the sequence owning this Timer,
-  // |user_task_| will be posted to it when the Timer fires (note that this
-  // means |user_task_| can run after ~Timer() and should support that).
-  void SetTaskRunner(scoped_refptr<SequencedTaskRunner> task_runner);
-
-  // Start the timer to run at the given |delay| from now. If the timer is
-  // already running, it will be replaced to call the given |user_task|.
-  virtual void Start(const Location& posted_from,
-                     TimeDelta delay,
-                     const base::Closure& user_task);
-
-  // Start the timer to run at the given |delay| from now. If the timer is
-  // already running, it will be replaced to call a task formed from
-  // |reviewer->*method|.
-  template <class Receiver>
-  void Start(const Location& posted_from,
-             TimeDelta delay,
-             Receiver* receiver,
-             void (Receiver::*method)()) {
-    Start(posted_from, delay,
-          base::BindRepeating(method, base::Unretained(receiver)));
-  }
-
-  // Call this method to stop and cancel the timer.  It is a no-op if the timer
-  // is not running.
-  virtual void Stop();
-
-  // Stop running task (if any) and abandon scheduled task (if any).
-  void AbandonAndStop() {
-    AbandonScheduledTask();
-
-    Stop();
-    // No more member accesses here: |this| could be deleted at this point.
-  }
-
-  // Call this method to reset the timer delay. The |user_task_| must be set. If
-  // the timer is not running, this will start it by posting a task.
-  virtual void Reset();
-
-  const base::Closure& user_task() const { return user_task_; }
-  const TimeTicks& desired_run_time() const { return desired_run_time_; }
-
- protected:
-  // Returns the current tick count.
-  TimeTicks Now() const;
-
-  void set_user_task(const Closure& task) { user_task_ = task; }
-  void set_desired_run_time(TimeTicks desired) { desired_run_time_ = desired; }
-  void set_is_running(bool running) { is_running_ = running; }
-
-  const Location& posted_from() const { return posted_from_; }
-  bool retain_user_task() const { return retain_user_task_; }
-  bool is_repeating() const { return is_repeating_; }
-  bool is_running() const { return is_running_; }
-
- private:
-  friend class BaseTimerTaskInternal;
-
-  // Allocates a new |scheduled_task_| and posts it on the current sequence with
-  // the given |delay|. |scheduled_task_| must be null. |scheduled_run_time_|
-  // and |desired_run_time_| are reset to Now() + delay.
-  void PostNewScheduledTask(TimeDelta delay);
-
-  // Returns the task runner on which the task should be scheduled. If the
-  // corresponding |task_runner_| field is null, the task runner for the current
-  // sequence is returned.
-  scoped_refptr<SequencedTaskRunner> GetTaskRunner();
-
-  // Disable |scheduled_task_| and abandon it so that it no longer refers back
-  // to this object.
-  void AbandonScheduledTask();
-
-  // Called by BaseTimerTaskInternal when the delayed task fires.
-  void RunScheduledTask();
-
-  // When non-null, the |scheduled_task_| was posted to call RunScheduledTask()
-  // at |scheduled_run_time_|.
-  BaseTimerTaskInternal* scheduled_task_;
-
-  // The task runner on which the task should be scheduled. If it is null, the
-  // task runner for the current sequence will be used.
-  scoped_refptr<SequencedTaskRunner> task_runner_;
-
-  // Location in user code.
-  Location posted_from_;
-  // Delay requested by user.
-  TimeDelta delay_;
-  // |user_task_| is what the user wants to be run at |desired_run_time_|.
-  base::Closure user_task_;
-
-  // The time at which |scheduled_task_| is expected to fire. This time can be a
-  // "zero" TimeTicks if the task must be run immediately.
-  TimeTicks scheduled_run_time_;
-
-  // The desired run time of |user_task_|. The user may update this at any time,
-  // even if their previous request has not run yet. If |desired_run_time_| is
-  // greater than |scheduled_run_time_|, a continuation task will be posted to
-  // wait for the remaining time. This allows us to reuse the pending task so as
-  // not to flood the delayed queues with orphaned tasks when the user code
-  // excessively Stops and Starts the timer. This time can be a "zero" TimeTicks
-  // if the task must be run immediately.
-  TimeTicks desired_run_time_;
-
-  // Timer isn't thread-safe and must only be used on its origin sequence
-  // (sequence on which it was started). Once fully Stop()'ed it may be
-  // destroyed or restarted on another sequence.
-  SequenceChecker origin_sequence_checker_;
-
-  // Repeating timers automatically post the task again before calling the task
-  // callback.
-  const bool is_repeating_;
-
-  // If true, hold on to the |user_task_| closure object for reuse.
-  const bool retain_user_task_;
-
-  // The tick clock used to calculate the run time for scheduled tasks.
-  const TickClock* const tick_clock_;
-
-  // If true, |user_task_| is scheduled to run sometime in the future.
-  bool is_running_;
-
-  DISALLOW_COPY_AND_ASSIGN(Timer);
-};
-
-//-----------------------------------------------------------------------------
-// A simple, one-shot timer.  See usage notes at the top of the file.
-class OneShotTimer : public Timer {
- public:
-  OneShotTimer() : OneShotTimer(nullptr) {}
-  explicit OneShotTimer(const TickClock* tick_clock)
-      : Timer(false, false, tick_clock) {}
-};
-
-//-----------------------------------------------------------------------------
-// A simple, repeating timer.  See usage notes at the top of the file.
-class RepeatingTimer : public Timer {
- public:
-  RepeatingTimer() : RepeatingTimer(nullptr) {}
-  explicit RepeatingTimer(const TickClock* tick_clock)
-      : Timer(true, true, tick_clock) {}
-};
-
-//-----------------------------------------------------------------------------
-// A Delay timer is like The Button from Lost. Once started, you have to keep
-// calling Reset otherwise it will call the given method on the sequence it was
-// initially Reset() from.
-//
-// Once created, it is inactive until Reset is called. Once |delay| seconds have
-// passed since the last call to Reset, the callback is made. Once the callback
-// has been made, it's inactive until Reset is called again.
-//
-// If destroyed, the timeout is canceled and will not occur even if already
-// inflight.
-class DelayTimer : protected Timer {
- public:
-  template <class Receiver>
-  DelayTimer(const Location& posted_from,
-             TimeDelta delay,
-             Receiver* receiver,
-             void (Receiver::*method)())
-      : DelayTimer(posted_from, delay, receiver, method, nullptr) {}
-
-  template <class Receiver>
-  DelayTimer(const Location& posted_from,
-             TimeDelta delay,
-             Receiver* receiver,
-             void (Receiver::*method)(),
-             const TickClock* tick_clock)
-      : Timer(posted_from,
-              delay,
-              base::Bind(method, base::Unretained(receiver)),
-              false,
-              tick_clock) {}
-
-  using Timer::Reset;
-};
-
-}  // namespace base
-
-#endif  // BASE_TIMER_TIMER_H_
diff --git a/base/values.cc b/base/values.cc
index df12c29..905a468 100644
--- a/base/values.cc
+++ b/base/values.cc
@@ -23,7 +23,7 @@
 
 namespace {
 
-const char* const kTypeNames[] = {"null",   "boolean", "integer",    "double",
+const char* const kTypeNames[] = {"null",   "boolean", "integer",
                                   "string", "binary",  "dictionary", "list"};
 static_assert(arraysize(kTypeNames) ==
                   static_cast<size_t>(Value::Type::LIST) + 1,
@@ -109,9 +109,6 @@
     case Type::INTEGER:
       int_value_ = 0;
       return;
-    case Type::DOUBLE:
-      double_value_ = 0.0;
-      return;
     case Type::STRING:
       new (&string_value_) std::string();
       return;
@@ -131,14 +128,6 @@
 
 Value::Value(int in_int) : type_(Type::INTEGER), int_value_(in_int) {}
 
-Value::Value(double in_double) : type_(Type::DOUBLE), double_value_(in_double) {
-  if (!std::isfinite(double_value_)) {
-    NOTREACHED() << "Non-finite (i.e. NaN or positive/negative infinity) "
-                 << "values cannot be represented in JSON";
-    double_value_ = 0.0;
-  }
-}
-
 Value::Value(const char* in_string) : Value(std::string(in_string)) {}
 
 Value::Value(StringPiece in_string) : Value(std::string(in_string)) {}
@@ -193,8 +182,6 @@
       return Value(bool_value_);
     case Type::INTEGER:
       return Value(int_value_);
-    case Type::DOUBLE:
-      return Value(double_value_);
     case Type::STRING:
       return Value(string_value_);
     case Type::BINARY:
@@ -230,15 +217,6 @@
   return int_value_;
 }
 
-double Value::GetDouble() const {
-  if (is_double())
-    return double_value_;
-  if (is_int())
-    return int_value_;
-  CHECK(false);
-  return 0.0;
-}
-
 const std::string& Value::GetString() const {
   CHECK(is_string());
   return string_value_;
@@ -455,18 +433,6 @@
   return is_int();
 }
 
-bool Value::GetAsDouble(double* out_value) const {
-  if (out_value && is_double()) {
-    *out_value = double_value_;
-    return true;
-  } else if (out_value && is_int()) {
-    // Allow promotion from int to double.
-    *out_value = int_value_;
-    return true;
-  }
-  return is_double() || is_int();
-}
-
 bool Value::GetAsString(std::string* out_value) const {
   if (out_value && is_string()) {
     *out_value = string_value_;
@@ -550,8 +516,6 @@
       return lhs.bool_value_ == rhs.bool_value_;
     case Value::Type::INTEGER:
       return lhs.int_value_ == rhs.int_value_;
-    case Value::Type::DOUBLE:
-      return lhs.double_value_ == rhs.double_value_;
     case Value::Type::STRING:
       return lhs.string_value_ == rhs.string_value_;
     case Value::Type::BINARY:
@@ -590,8 +554,6 @@
       return lhs.bool_value_ < rhs.bool_value_;
     case Value::Type::INTEGER:
       return lhs.int_value_ < rhs.int_value_;
-    case Value::Type::DOUBLE:
-      return lhs.double_value_ < rhs.double_value_;
     case Value::Type::STRING:
       return lhs.string_value_ < rhs.string_value_;
     case Value::Type::BINARY:
@@ -643,9 +605,6 @@
     case Type::INTEGER:
       int_value_ = that.int_value_;
       return;
-    case Type::DOUBLE:
-      double_value_ = that.double_value_;
-      return;
     case Type::STRING:
       new (&string_value_) std::string(std::move(that.string_value_));
       return;
@@ -666,7 +625,6 @@
     case Type::NONE:
     case Type::BOOLEAN:
     case Type::INTEGER:
-    case Type::DOUBLE:
       // Nothing to do
       return;
 
@@ -748,10 +706,6 @@
   return Set(path, std::make_unique<Value>(in_value));
 }
 
-Value* DictionaryValue::SetDouble(StringPiece path, double in_value) {
-  return Set(path, std::make_unique<Value>(in_value));
-}
-
 Value* DictionaryValue::SetString(StringPiece path, StringPiece in_value) {
   return Set(path, std::make_unique<Value>(in_value));
 }
@@ -827,14 +781,6 @@
   return value->GetAsInteger(out_value);
 }
 
-bool DictionaryValue::GetDouble(StringPiece path, double* out_value) const {
-  const Value* value;
-  if (!Get(path, &value))
-    return false;
-
-  return value->GetAsDouble(out_value);
-}
-
 bool DictionaryValue::GetString(StringPiece path,
                                 std::string* out_value) const {
   const Value* value;
@@ -961,15 +907,6 @@
   return value->GetAsInteger(out_value);
 }
 
-bool DictionaryValue::GetDoubleWithoutPathExpansion(StringPiece key,
-                                                    double* out_value) const {
-  const Value* value;
-  if (!GetWithoutPathExpansion(key, &value))
-    return false;
-
-  return value->GetAsDouble(out_value);
-}
-
 bool DictionaryValue::GetStringWithoutPathExpansion(
     StringPiece key,
     std::string* out_value) const {
@@ -1201,14 +1138,6 @@
   return value->GetAsInteger(out_value);
 }
 
-bool ListValue::GetDouble(size_t index, double* out_value) const {
-  const Value* value;
-  if (!Get(index, &value))
-    return false;
-
-  return value->GetAsDouble(out_value);
-}
-
 bool ListValue::GetString(size_t index, std::string* out_value) const {
   const Value* value;
   if (!Get(index, &value))
@@ -1306,10 +1235,6 @@
   list_.emplace_back(in_value);
 }
 
-void ListValue::AppendDouble(double in_value) {
-  list_.emplace_back(in_value);
-}
-
 void ListValue::AppendString(StringPiece in_value) {
   list_.emplace_back(in_value);
 }
diff --git a/base/values.h b/base/values.h
index e9253db..01769a5 100644
--- a/base/values.h
+++ b/base/values.h
@@ -11,8 +11,7 @@
 //
 // IN PARTICULAR this means that there is no support for int64_t or unsigned
 // numbers. Writing JSON with such types would violate the spec. If you need
-// something like this, either use a double or make a string value containing
-// the number you want.
+// something like this, make a string value containing the number you want.
 //
 // NOTE: A Value parameter that is always a Value::STRING should just be passed
 // as a std::string. Similarly for Values that are always Value::DICTIONARY
@@ -88,7 +87,6 @@
     NONE = 0,
     BOOLEAN,
     INTEGER,
-    DOUBLE,
     STRING,
     BINARY,
     DICTIONARY,
@@ -118,7 +116,6 @@
   explicit Value(Type type);
   explicit Value(bool in_bool);
   explicit Value(int in_int);
-  explicit Value(double in_double);
 
   // Value(const char*) and Value(const char16*) are required despite
   // Value(StringPiece) and Value(StringPiece16) because otherwise the
@@ -153,7 +150,6 @@
   bool is_none() const { return type() == Type::NONE; }
   bool is_bool() const { return type() == Type::BOOLEAN; }
   bool is_int() const { return type() == Type::INTEGER; }
-  bool is_double() const { return type() == Type::DOUBLE; }
   bool is_string() const { return type() == Type::STRING; }
   bool is_blob() const { return type() == Type::BINARY; }
   bool is_dict() const { return type() == Type::DICTIONARY; }
@@ -162,7 +158,6 @@
   // These will all fatally assert if the type doesn't match.
   bool GetBool() const;
   int GetInt() const;
-  double GetDouble() const;  // Implicitly converts from int if necessary.
   const std::string& GetString() const;
   const BlobStorage& GetBlob() const;
 
@@ -188,7 +183,7 @@
   // Note: This fatally asserts if type() is not Type::DICTIONARY.
   //
   // Example:
-  //   auto* found = FindKey("foo", Type::DOUBLE);
+  //   auto* found = FindKey("foo", Type::INTEGER);
   Value* FindKeyOfType(StringPiece key, Type type);
   const Value* FindKeyOfType(StringPiece key, Type type) const;
 
@@ -309,8 +304,6 @@
   bool GetAsBoolean(bool* out_value) const;
   // DEPRECATED, use GetInt() instead.
   bool GetAsInteger(int* out_value) const;
-  // DEPRECATED, use GetDouble() instead.
-  bool GetAsDouble(double* out_value) const;
   // DEPRECATED, use GetString() instead.
   bool GetAsString(std::string* out_value) const;
   bool GetAsString(string16* out_value) const;
@@ -362,7 +355,6 @@
   union {
     bool bool_value_;
     int int_value_;
-    double double_value_;
     std::string string_value_;
     BlobStorage binary_value_;
     DictStorage dict_;
@@ -421,8 +413,6 @@
   Value* SetBoolean(StringPiece path, bool in_value);
   // DEPRECATED, use Value::SetPath(path, Value(int)) instead.
   Value* SetInteger(StringPiece path, int in_value);
-  // DEPRECATED, use Value::SetPath(path, Value(double)) instead.
-  Value* SetDouble(StringPiece path, double in_value);
   // DEPRECATED, use Value::SetPath(path, Value(StringPiece)) instead.
   Value* SetString(StringPiece path, StringPiece in_value);
   // DEPRECATED, use Value::SetPath(path, Value(const string& 16)) instead.
@@ -460,10 +450,6 @@
   bool GetBoolean(StringPiece path, bool* out_value) const;
   // DEPRECATED, use Value::FindPath(path) and Value::GetInt() instead.
   bool GetInteger(StringPiece path, int* out_value) const;
-  // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as
-  // doubles.
-  // DEPRECATED, use Value::FindPath(path) and Value::GetDouble() instead.
-  bool GetDouble(StringPiece path, double* out_value) const;
   // DEPRECATED, use Value::FindPath(path) and Value::GetString() instead.
   bool GetString(StringPiece path, std::string* out_value) const;
   // DEPRECATED, use Value::FindPath(path) and Value::GetString() instead.
@@ -494,8 +480,6 @@
   bool GetBooleanWithoutPathExpansion(StringPiece key, bool* out_value) const;
   // DEPRECATED, use Value::FindKey(key) and Value::GetInt() instead.
   bool GetIntegerWithoutPathExpansion(StringPiece key, int* out_value) const;
-  // DEPRECATED, use Value::FindKey(key) and Value::GetDouble() instead.
-  bool GetDoubleWithoutPathExpansion(StringPiece key, double* out_value) const;
   // DEPRECATED, use Value::FindKey(key) and Value::GetString() instead.
   bool GetStringWithoutPathExpansion(StringPiece key,
                                      std::string* out_value) const;
@@ -641,10 +625,6 @@
   bool GetBoolean(size_t index, bool* out_value) const;
   // DEPRECATED, use GetList()::operator[]::GetInt() instead.
   bool GetInteger(size_t index, int* out_value) const;
-  // Values of both type Type::INTEGER and Type::DOUBLE can be obtained as
-  // doubles.
-  // DEPRECATED, use GetList()::operator[]::GetDouble() instead.
-  bool GetDouble(size_t index, double* out_value) const;
   // DEPRECATED, use GetList()::operator[]::GetString() instead.
   bool GetString(size_t index, std::string* out_value) const;
   bool GetString(size_t index, string16* out_value) const;
@@ -686,7 +666,6 @@
   // DEPRECATED, use GetList()::emplace_back() instead.
   void AppendBoolean(bool in_value);
   void AppendInteger(int in_value);
-  void AppendDouble(double in_value);
   void AppendString(StringPiece in_value);
   void AppendString(const string16& in_value);
   // DEPRECATED, use GetList()::emplace_back() in a loop instead.
diff --git a/base/win/message_window.cc b/base/win/message_window.cc
deleted file mode 100644
index 8858b41..0000000
--- a/base/win/message_window.cc
+++ /dev/null
@@ -1,165 +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 "base/win/message_window.h"
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/win/current_module.h"
-#include "base/win/wrapped_window_proc.h"
-
-const wchar_t kMessageWindowClassName[] = L"Chrome_MessageWindow";
-
-namespace base {
-namespace win {
-
-// Used along with LazyInstance to register a window class for message-only
-// windows created by MessageWindow.
-class MessageWindow::WindowClass {
- public:
-  WindowClass();
-  ~WindowClass();
-
-  ATOM atom() { return atom_; }
-  HINSTANCE instance() { return instance_; }
-
- private:
-  ATOM atom_;
-  HINSTANCE instance_;
-
-  DISALLOW_COPY_AND_ASSIGN(WindowClass);
-};
-
-static LazyInstance<MessageWindow::WindowClass>::DestructorAtExit
-    g_window_class = LAZY_INSTANCE_INITIALIZER;
-
-MessageWindow::WindowClass::WindowClass()
-    : atom_(0), instance_(CURRENT_MODULE()) {
-  WNDCLASSEX window_class;
-  window_class.cbSize = sizeof(window_class);
-  window_class.style = 0;
-  window_class.lpfnWndProc = &base::win::WrappedWindowProc<WindowProc>;
-  window_class.cbClsExtra = 0;
-  window_class.cbWndExtra = 0;
-  window_class.hInstance = instance_;
-  window_class.hIcon = NULL;
-  window_class.hCursor = NULL;
-  window_class.hbrBackground = NULL;
-  window_class.lpszMenuName = NULL;
-  window_class.lpszClassName = kMessageWindowClassName;
-  window_class.hIconSm = NULL;
-  atom_ = RegisterClassEx(&window_class);
-  if (atom_ == 0) {
-    PLOG(ERROR)
-        << "Failed to register the window class for a message-only window";
-  }
-}
-
-MessageWindow::WindowClass::~WindowClass() {
-  if (atom_ != 0) {
-    BOOL result = UnregisterClass(MAKEINTATOM(atom_), instance_);
-    // Hitting this DCHECK usually means that some MessageWindow objects were
-    // leaked. For example not calling
-    // ui::Clipboard::DestroyClipboardForCurrentThread() results in a leaked
-    // MessageWindow.
-    DCHECK(result);
-  }
-}
-
-MessageWindow::MessageWindow()
-    : window_(NULL) {
-}
-
-MessageWindow::~MessageWindow() {
-  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
-
-  if (window_ != NULL) {
-    BOOL result = DestroyWindow(window_);
-    DCHECK(result);
-  }
-}
-
-bool MessageWindow::Create(MessageCallback message_callback) {
-  return DoCreate(std::move(message_callback), NULL);
-}
-
-bool MessageWindow::CreateNamed(MessageCallback message_callback,
-                                const string16& window_name) {
-  return DoCreate(std::move(message_callback), window_name.c_str());
-}
-
-// static
-HWND MessageWindow::FindWindow(const string16& window_name) {
-  return FindWindowEx(HWND_MESSAGE, NULL, kMessageWindowClassName,
-                      window_name.c_str());
-}
-
-bool MessageWindow::DoCreate(MessageCallback message_callback,
-                             const wchar_t* window_name) {
-  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
-  DCHECK(message_callback_.is_null());
-  DCHECK(!window_);
-
-  message_callback_ = std::move(message_callback);
-
-  WindowClass& window_class = g_window_class.Get();
-  window_ = CreateWindow(MAKEINTATOM(window_class.atom()), window_name, 0, 0, 0,
-                         0, 0, HWND_MESSAGE, 0, window_class.instance(), this);
-  if (!window_) {
-    PLOG(ERROR) << "Failed to create a message-only window";
-    return false;
-  }
-
-  return true;
-}
-
-// static
-LRESULT CALLBACK MessageWindow::WindowProc(HWND hwnd,
-                                           UINT message,
-                                           WPARAM wparam,
-                                           LPARAM lparam) {
-  MessageWindow* self = reinterpret_cast<MessageWindow*>(
-      GetWindowLongPtr(hwnd, GWLP_USERDATA));
-
-  switch (message) {
-    // Set up the self before handling WM_CREATE.
-    case WM_CREATE: {
-      CREATESTRUCT* cs = reinterpret_cast<CREATESTRUCT*>(lparam);
-      self = reinterpret_cast<MessageWindow*>(cs->lpCreateParams);
-
-      // Make |hwnd| available to the message handler. At this point the control
-      // hasn't returned from CreateWindow() yet.
-      self->window_ = hwnd;
-
-      // Store pointer to the self to the window's user data.
-      SetLastError(ERROR_SUCCESS);
-      LONG_PTR result = SetWindowLongPtr(
-          hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(self));
-      CHECK(result != 0 || GetLastError() == ERROR_SUCCESS);
-      break;
-    }
-
-    // Clear the pointer to stop calling the self once WM_DESTROY is
-    // received.
-    case WM_DESTROY: {
-      SetLastError(ERROR_SUCCESS);
-      LONG_PTR result = SetWindowLongPtr(hwnd, GWLP_USERDATA, NULL);
-      CHECK(result != 0 || GetLastError() == ERROR_SUCCESS);
-      break;
-    }
-  }
-
-  // Handle the message.
-  if (self) {
-    LRESULT message_result;
-    if (self->message_callback_.Run(message, wparam, lparam, &message_result))
-      return message_result;
-  }
-
-  return DefWindowProc(hwnd, message, wparam, lparam);
-}
-
-}  // namespace win
-}  // namespace base
diff --git a/base/win/message_window.h b/base/win/message_window.h
deleted file mode 100644
index 2fef480..0000000
--- a/base/win/message_window.h
+++ /dev/null
@@ -1,74 +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_WIN_MESSAGE_WINDOW_H_
-#define BASE_WIN_MESSAGE_WINDOW_H_
-
-#include <windows.h>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "base/threading/thread_checker.h"
-
-namespace base {
-namespace win {
-
-// Implements a message-only window.
-class BASE_EXPORT MessageWindow {
- public:
-  // Used to register a process-wide message window class.
-  class WindowClass;
-
-  // Implement this callback to handle messages received by the message window.
-  // If the callback returns |false|, the first four parameters are passed to
-  // DefWindowProc(). Otherwise, |*result| is returned by the window procedure.
-  using MessageCallback = base::RepeatingCallback<
-      bool(UINT message, WPARAM wparam, LPARAM lparam, LRESULT* result)>;
-
-  MessageWindow();
-  ~MessageWindow();
-
-  // Creates a message-only window. The incoming messages will be passed by
-  // |message_callback|. |message_callback| must outlive |this|.
-  bool Create(MessageCallback message_callback);
-
-  // Same as Create() but assigns the name to the created window.
-  bool CreateNamed(MessageCallback message_callback,
-                   const string16& window_name);
-
-  HWND hwnd() const { return window_; }
-
-  // Retrieves a handle of the first message-only window with matching
-  // |window_name|.
-  static HWND FindWindow(const string16& window_name);
-
- private:
-  // Give |WindowClass| access to WindowProc().
-  friend class WindowClass;
-
-  // Contains the actual window creation code.
-  bool DoCreate(MessageCallback message_callback, const wchar_t* window_name);
-
-  // Invoked by the OS to process incoming window messages.
-  static LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM wparam,
-                                     LPARAM lparam);
-
-  // Invoked to handle messages received by the window.
-  MessageCallback message_callback_;
-
-  // Handle of the input window.
-  HWND window_;
-
-  THREAD_CHECKER(thread_checker_);
-
-  DISALLOW_COPY_AND_ASSIGN(MessageWindow);
-};
-
-}  // namespace win
-}  // namespace base
-
-#endif  // BASE_WIN_MESSAGE_WINDOW_H_
diff --git a/base/win/object_watcher.cc b/base/win/object_watcher.cc
deleted file mode 100644
index 4c1c235..0000000
--- a/base/win/object_watcher.cc
+++ /dev/null
@@ -1,123 +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 "base/win/object_watcher.h"
-
-#include "base/bind.h"
-#include "base/logging.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-
-#include <windows.h>
-
-namespace base {
-namespace win {
-
-//-----------------------------------------------------------------------------
-
-ObjectWatcher::ObjectWatcher() : weak_factory_(this) {}
-
-ObjectWatcher::~ObjectWatcher() {
-  StopWatching();
-}
-
-bool ObjectWatcher::StartWatchingOnce(HANDLE object, Delegate* delegate) {
-  return StartWatchingInternal(object, delegate, true);
-}
-
-bool ObjectWatcher::StartWatchingMultipleTimes(HANDLE object,
-                                               Delegate* delegate) {
-  return StartWatchingInternal(object, delegate, false);
-}
-
-bool ObjectWatcher::StopWatching() {
-  if (!wait_object_)
-    return false;
-
-  // Make sure ObjectWatcher is used in a sequenced fashion.
-  DCHECK(task_runner_->RunsTasksInCurrentSequence());
-
-  // Blocking call to cancel the wait. Any callbacks already in progress will
-  // finish before we return from this call.
-  if (!UnregisterWaitEx(wait_object_, INVALID_HANDLE_VALUE)) {
-    DPLOG(FATAL) << "UnregisterWaitEx failed";
-    return false;
-  }
-
-  Reset();
-  return true;
-}
-
-bool ObjectWatcher::IsWatching() const {
-  return object_ != nullptr;
-}
-
-HANDLE ObjectWatcher::GetWatchedObject() const {
-  return object_;
-}
-
-// static
-void CALLBACK ObjectWatcher::DoneWaiting(void* param, BOOLEAN timed_out) {
-  DCHECK(!timed_out);
-
-  // The destructor blocks on any callbacks that are in flight, so we know that
-  // that is always a pointer to a valid ObjectWater.
-  ObjectWatcher* that = static_cast<ObjectWatcher*>(param);
-  that->task_runner_->PostTask(FROM_HERE, that->callback_);
-  if (that->run_once_)
-    that->callback_.Reset();
-}
-
-bool ObjectWatcher::StartWatchingInternal(HANDLE object, Delegate* delegate,
-                                          bool execute_only_once) {
-  DCHECK(delegate);
-  DCHECK(!wait_object_) << "Already watching an object";
-  DCHECK(SequencedTaskRunnerHandle::IsSet());
-
-  task_runner_ = SequencedTaskRunnerHandle::Get();
-
-  run_once_ = execute_only_once;
-
-  // Since our job is to just notice when an object is signaled and report the
-  // result back to this sequence, we can just run on a Windows wait thread.
-  DWORD wait_flags = WT_EXECUTEINWAITTHREAD;
-  if (run_once_)
-    wait_flags |= WT_EXECUTEONLYONCE;
-
-  // DoneWaiting can be synchronously called from RegisterWaitForSingleObject,
-  // so set up all state now.
-  callback_ =
-      Bind(&ObjectWatcher::Signal, weak_factory_.GetWeakPtr(), delegate);
-  object_ = object;
-
-  if (!RegisterWaitForSingleObject(&wait_object_, object, DoneWaiting,
-                                   this, INFINITE, wait_flags)) {
-    DPLOG(FATAL) << "RegisterWaitForSingleObject failed";
-    Reset();
-    return false;
-  }
-
-  return true;
-}
-
-void ObjectWatcher::Signal(Delegate* delegate) {
-  // Signaling the delegate may result in our destruction or a nested call to
-  // StartWatching(). As a result, we save any state we need and clear previous
-  // watcher state before signaling the delegate.
-  HANDLE object = object_;
-  if (run_once_)
-    StopWatching();
-  delegate->OnObjectSignaled(object);
-}
-
-void ObjectWatcher::Reset() {
-  callback_.Reset();
-  object_ = nullptr;
-  wait_object_ = nullptr;
-  task_runner_ = nullptr;
-  run_once_ = true;
-  weak_factory_.InvalidateWeakPtrs();
-}
-
-}  // namespace win
-}  // namespace base
diff --git a/base/win/object_watcher.h b/base/win/object_watcher.h
deleted file mode 100644
index b7ed76d..0000000
--- a/base/win/object_watcher.h
+++ /dev/null
@@ -1,131 +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_WIN_OBJECT_WATCHER_H_
-#define BASE_WIN_OBJECT_WATCHER_H_
-
-#include "base/win/windows_types.h"
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/weak_ptr.h"
-#include "base/sequenced_task_runner.h"
-
-namespace base {
-namespace win {
-
-// A class that provides a means to asynchronously wait for a Windows object to
-// become signaled.  It is an abstraction around RegisterWaitForSingleObject
-// that provides a notification callback, OnObjectSignaled, that runs back on
-// the origin sequence (i.e., the sequence that called StartWatching).
-//
-// This class acts like a smart pointer such that when it goes out-of-scope,
-// UnregisterWaitEx is automatically called, and any in-flight notification is
-// suppressed.
-//
-// The waiting handle MUST NOT be closed while watching is in progress. If this
-// handle is closed while the wait is still pending, the behavior is undefined
-// (see MSDN:RegisterWaitForSingleObject).
-//
-// Typical usage:
-//
-//   class MyClass : public base::win::ObjectWatcher::Delegate {
-//    public:
-//     void DoStuffWhenSignaled(HANDLE object) {
-//       watcher_.StartWatchingOnce(object, this);
-//     }
-//     void OnObjectSignaled(HANDLE object) override {
-//       // OK, time to do stuff!
-//     }
-//    private:
-//     base::win::ObjectWatcher watcher_;
-//   };
-//
-// In the above example, MyClass wants to "do stuff" when object becomes
-// signaled.  ObjectWatcher makes this task easy.  When MyClass goes out of
-// scope, the watcher_ will be destroyed, and there is no need to worry about
-// OnObjectSignaled being called on a deleted MyClass pointer.  Easy!
-// If the object is already signaled before being watched, OnObjectSignaled is
-// still called after (but not necessarily immediately after) watch is started.
-//
-// NOTE: Except for the constructor, all public methods of this class must be
-// called in sequence, in a scope where SequencedTaskRunnerHandle::IsSet().
-class BASE_EXPORT ObjectWatcher {
- public:
-  class BASE_EXPORT Delegate {
-   public:
-    virtual ~Delegate() {}
-    // Called from the sequence that started the watch when a signaled object is
-    // detected. To continue watching the object, StartWatching must be called
-    // again.
-    virtual void OnObjectSignaled(HANDLE object) = 0;
-  };
-
-  ObjectWatcher();
-  ~ObjectWatcher();
-
-  // When the object is signaled, the given delegate is notified on the sequence
-  // where StartWatchingOnce is called. The ObjectWatcher is not responsible for
-  // deleting the delegate.
-  // Returns whether watching was successfully initiated.
-  bool StartWatchingOnce(HANDLE object, Delegate* delegate);
-
-  // Notifies the delegate, on the sequence where this method is called, each
-  // time the object is set. By definition, the handle must be an auto-reset
-  // object. The caller must ensure that it (or any Windows system code) doesn't
-  // reset the event or else the delegate won't be called.
-  // Returns whether watching was successfully initiated.
-  bool StartWatchingMultipleTimes(HANDLE object, Delegate* delegate);
-
-  // Stops watching.  Does nothing if the watch has already completed.  If the
-  // watch is still active, then it is canceled, and the associated delegate is
-  // not notified.
-  //
-  // Returns true if the watch was canceled.  Otherwise, false is returned.
-  bool StopWatching();
-
-  // Returns true if currently watching an object.
-  bool IsWatching() const;
-
-  // Returns the handle of the object being watched.
-  HANDLE GetWatchedObject() const;
-
- private:
-  // Called on a background thread when done waiting.
-  static void CALLBACK DoneWaiting(void* param, BOOLEAN timed_out);
-
-  // Helper used by StartWatchingOnce and StartWatchingMultipleTimes.
-  bool StartWatchingInternal(HANDLE object, Delegate* delegate,
-                             bool execute_only_once);
-
-  void Signal(Delegate* delegate);
-
-  void Reset();
-
-  // A callback pre-bound to Signal() that is posted to the caller's task runner
-  // when the wait completes.
-  Closure callback_;
-
-  // The object being watched.
-  HANDLE object_ = nullptr;
-
-  // The wait handle returned by RegisterWaitForSingleObject.
-  HANDLE wait_object_ = nullptr;
-
-  // The task runner of the sequence on which the watch was started.
-  scoped_refptr<SequencedTaskRunner> task_runner_;
-
-  bool run_once_ = true;
-
-  WeakPtrFactory<ObjectWatcher> weak_factory_;
-
-  DISALLOW_COPY_AND_ASSIGN(ObjectWatcher);
-};
-
-}  // namespace win
-}  // namespace base
-
-#endif  // BASE_WIN_OBJECT_WATCHER_H_
diff --git a/base/win/process_startup_helper.cc b/base/win/process_startup_helper.cc
index 7a01211..de44b2a 100644
--- a/base/win/process_startup_helper.cc
+++ b/base/win/process_startup_helper.cc
@@ -6,9 +6,7 @@
 
 #include <crtdbg.h>
 #include <new.h>
-
-#include "base/base_switches.h"
-#include "base/command_line.h"
+#include <stdlib.h>
 
 namespace {
 
@@ -45,9 +43,7 @@
   _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
   _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
 #else
-  if (!command_line.HasSwitch(switches::kDisableBreakpad)) {
-    _CrtSetReportMode(_CRT_ASSERT, 0);
-  }
+  _CrtSetReportMode(_CRT_ASSERT, 0);
 #endif
 }
 
diff --git a/base/win/registry.cc b/base/win/registry.cc
index 2fe53cf..3de51e3 100644
--- a/base/win/registry.cc
+++ b/base/win/registry.cc
@@ -11,7 +11,6 @@
 #include "base/logging.h"
 #include "base/macros.h"
 #include "base/strings/string_util.h"
-#include "base/threading/thread_restrictions.h"
 #include "base/win/windows_version.h"
 
 namespace base {
@@ -36,56 +35,6 @@
 
 }  // namespace
 
-// Watches for modifications to a key.
-class RegKey::Watcher : public ObjectWatcher::Delegate {
- public:
-  Watcher() {}
-  ~Watcher() override {}
-
-  bool StartWatching(HKEY key, const ChangeCallback& callback);
-
-  // Implementation of ObjectWatcher::Delegate.
-  void OnObjectSignaled(HANDLE object) override {
-    DCHECK(watch_event_.IsValid() && watch_event_.Get() == object);
-    ChangeCallback callback = callback_;
-    callback_.Reset();
-    callback.Run();
-  }
-
- private:
-  ScopedHandle watch_event_;
-  ObjectWatcher object_watcher_;
-  ChangeCallback callback_;
-  DISALLOW_COPY_AND_ASSIGN(Watcher);
-};
-
-bool RegKey::Watcher::StartWatching(HKEY key, const ChangeCallback& callback) {
-  DCHECK(key);
-  DCHECK(callback_.is_null());
-
-  if (!watch_event_.IsValid())
-    watch_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL));
-
-  if (!watch_event_.IsValid())
-    return false;
-
-  DWORD filter = REG_NOTIFY_CHANGE_NAME |
-                 REG_NOTIFY_CHANGE_ATTRIBUTES |
-                 REG_NOTIFY_CHANGE_LAST_SET |
-                 REG_NOTIFY_CHANGE_SECURITY;
-
-  // Watch the registry key for a change of value.
-  LONG result = RegNotifyChangeKeyValue(key, TRUE, filter, watch_event_.Get(),
-                                        TRUE);
-  if (result != ERROR_SUCCESS) {
-    watch_event_.Close();
-    return false;
-  }
-
-  callback_ = callback;
-  return object_watcher_.StartWatchingOnce(watch_event_.Get(), this);
-}
-
 // RegKey ----------------------------------------------------------------------
 
 RegKey::RegKey() : key_(NULL), wow64access_(0) {
@@ -410,16 +359,6 @@
   return result;
 }
 
-bool RegKey::StartWatching(const ChangeCallback& callback) {
-  if (!key_watcher_)
-    key_watcher_.reset(new Watcher());
-
-  if (!key_watcher_->StartWatching(key_, callback))
-    return false;
-
-  return true;
-}
-
 // static
 LONG RegKey::RegDeleteKeyExWrapper(HKEY hKey,
                                    const wchar_t* lpSubKey,
diff --git a/base/win/registry.h b/base/win/registry.h
index 53327ec..db016bf 100644
--- a/base/win/registry.h
+++ b/base/win/registry.h
@@ -12,7 +12,6 @@
 
 #include "base/base_export.h"
 #include "base/macros.h"
-#include "base/win/object_watcher.h"
 #include "base/win/scoped_handle.h"
 
 namespace base {
@@ -29,9 +28,6 @@
 //    error as a (non-zero) win32 error code.
 class BASE_EXPORT RegKey {
  public:
-  // Called from the MessageLoop when the key changes.
-  typedef base::Callback<void()> ChangeCallback;
-
   RegKey();
   explicit RegKey(HKEY key);
   RegKey(HKEY rootkey, const wchar_t* subkey, REGSAM access);
@@ -125,18 +121,9 @@
                   DWORD dsize,
                   DWORD dtype);
 
-  // Starts watching the key to see if any of its values have changed.
-  // The key must have been opened with the KEY_NOTIFY access privilege.
-  // Returns true on success.
-  // To stop watching, delete this RegKey object. To continue watching the
-  // object after the callback is invoked, call StartWatching again.
-  bool StartWatching(const ChangeCallback& callback);
-
   HKEY Handle() const { return key_; }
 
  private:
-  class Watcher;
-
   // Calls RegDeleteKeyEx on supported platforms, alternatively falls back to
   // RegDeleteKey.
   static LONG RegDeleteKeyExWrapper(HKEY hKey,
@@ -151,7 +138,6 @@
 
   HKEY key_;  // The registry key being iterated.
   REGSAM wow64access_;
-  std::unique_ptr<Watcher> key_watcher_;
 
   DISALLOW_COPY_AND_ASSIGN(RegKey);
 };
diff --git a/base/win/scoped_com_initializer.cc b/base/win/scoped_com_initializer.cc
deleted file mode 100644
index 73e1b5c..0000000
--- a/base/win/scoped_com_initializer.cc
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2017 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/win/scoped_com_initializer.h"
-
-#include "base/logging.h"
-
-namespace base {
-namespace win {
-
-ScopedCOMInitializer::ScopedCOMInitializer() {
-  Initialize(COINIT_APARTMENTTHREADED);
-}
-
-ScopedCOMInitializer::ScopedCOMInitializer(SelectMTA mta) {
-  Initialize(COINIT_MULTITHREADED);
-}
-
-ScopedCOMInitializer::~ScopedCOMInitializer() {
-  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
-  if (Succeeded())
-    CoUninitialize();
-}
-
-bool ScopedCOMInitializer::Succeeded() const {
-  return SUCCEEDED(hr_);
-}
-
-void ScopedCOMInitializer::Initialize(COINIT init) {
-  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
-  hr_ = CoInitializeEx(NULL, init);
-  DCHECK_NE(RPC_E_CHANGED_MODE, hr_) << "Invalid COM thread model change";
-}
-
-}  // namespace win
-}  // namespace base
diff --git a/base/win/scoped_com_initializer.h b/base/win/scoped_com_initializer.h
deleted file mode 100644
index 3bb5795..0000000
--- a/base/win/scoped_com_initializer.h
+++ /dev/null
@@ -1,53 +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_WIN_SCOPED_COM_INITIALIZER_H_
-#define BASE_WIN_SCOPED_COM_INITIALIZER_H_
-
-#include <objbase.h>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/threading/thread_checker.h"
-#include "base/win/scoped_windows_thread_environment.h"
-
-namespace base {
-namespace win {
-
-// Initializes COM in the constructor (STA or MTA), and uninitializes COM in the
-// destructor.
-//
-// WARNING: This should only be used once per thread, ideally scoped to a
-// similar lifetime as the thread itself.  You should not be using this in
-// random utility functions that make COM calls -- instead ensure these
-// functions are running on a COM-supporting thread!
-class BASE_EXPORT ScopedCOMInitializer : public ScopedWindowsThreadEnvironment {
- public:
-  // Enum value provided to initialize the thread as an MTA instead of STA.
-  enum SelectMTA { kMTA };
-
-  // Constructor for STA initialization.
-  ScopedCOMInitializer();
-
-  // Constructor for MTA initialization.
-  explicit ScopedCOMInitializer(SelectMTA mta);
-
-  ~ScopedCOMInitializer() override;
-
-  // ScopedWindowsThreadEnvironment:
-  bool Succeeded() const override;
-
- private:
-  void Initialize(COINIT init);
-
-  HRESULT hr_;
-  THREAD_CHECKER(thread_checker_);
-
-  DISALLOW_COPY_AND_ASSIGN(ScopedCOMInitializer);
-};
-
-}  // namespace win
-}  // namespace base
-
-#endif  // BASE_WIN_SCOPED_COM_INITIALIZER_H_
diff --git a/base/win/scoped_handle.h b/base/win/scoped_handle.h
index 1b630bb..010e8a4 100644
--- a/base/win/scoped_handle.h
+++ b/base/win/scoped_handle.h
@@ -9,7 +9,6 @@
 
 #include "base/base_export.h"
 #include "base/gtest_prod_util.h"
-#include "base/location.h"
 #include "base/logging.h"
 #include "base/macros.h"
 
@@ -72,8 +71,6 @@
 
       if (Traits::IsHandleValid(handle)) {
         handle_ = handle;
-        Verifier::StartTracking(handle, this, BASE_WIN_GET_CALLER,
-                                GetProgramCounter());
       }
       ::SetLastError(last_error);
     }
@@ -87,19 +84,12 @@
   Handle Take() {
     Handle temp = handle_;
     handle_ = Traits::NullHandle();
-    if (Traits::IsHandleValid(temp)) {
-      Verifier::StopTracking(temp, this, BASE_WIN_GET_CALLER,
-                             GetProgramCounter());
-    }
     return temp;
   }
 
   // Explicitly closes the owned handle.
   void Close() {
     if (Traits::IsHandleValid(handle_)) {
-      Verifier::StopTracking(handle_, this, BASE_WIN_GET_CALLER,
-                             GetProgramCounter());
-
       Traits::CloseHandle(handle_);
       handle_ = Traits::NullHandle();
     }
diff --git a/base/win/shortcut.cc b/base/win/shortcut.cc
index 5663452..8abd5a6 100644
--- a/base/win/shortcut.cc
+++ b/base/win/shortcut.cc
@@ -11,7 +11,6 @@
 #include <wrl/client.h>
 
 #include "base/files/file_util.h"
-#include "base/threading/thread_restrictions.h"
 #include "base/win/scoped_propvariant.h"
 #include "base/win/win_util.h"
 #include "base/win/windows_version.h"
@@ -57,8 +56,6 @@
 bool CreateOrUpdateShortcutLink(const FilePath& shortcut_path,
                                 const ShortcutProperties& properties,
                                 ShortcutOperation operation) {
-  AssertBlockingAllowed();
-
   // A target is required unless |operation| is SHORTCUT_UPDATE_EXISTING.
   if (operation != SHORTCUT_UPDATE_EXISTING &&
       !(properties.options & ShortcutProperties::PROPERTIES_TARGET)) {
@@ -199,7 +196,6 @@
                                uint32_t options,
                                ShortcutProperties* properties) {
   DCHECK(options && properties);
-  AssertBlockingAllowed();
 
   if (options & ~ShortcutProperties::PROPERTIES_ALL)
     NOTREACHED() << "Unhandled property is used.";
@@ -355,7 +351,6 @@
 }
 
 bool PinShortcutToTaskbar(const FilePath& shortcut) {
-  AssertBlockingAllowed();
   DCHECK(CanPinShortcutToTaskbar());
 
   intptr_t result = reinterpret_cast<intptr_t>(ShellExecute(
@@ -364,8 +359,6 @@
 }
 
 bool UnpinShortcutFromTaskbar(const FilePath& shortcut) {
-  AssertBlockingAllowed();
-
   intptr_t result = reinterpret_cast<intptr_t>(ShellExecute(
       NULL, L"taskbarunpin", shortcut.value().c_str(), NULL, NULL, 0));
   return result > 32;
diff --git a/base/win/win_util.cc b/base/win/win_util.cc
index c6cb3e8..b3867b4 100644
--- a/base/win/win_util.cc
+++ b/base/win/win_util.cc
@@ -34,7 +34,6 @@
 
 #include <memory>
 
-#include "base/base_switches.h"
 #include "base/command_line.h"
 #include "base/files/file_path.h"
 #include "base/logging.h"
@@ -42,7 +41,6 @@
 #include "base/strings/string_util.h"
 #include "base/strings/stringprintf.h"
 #include "base/strings/utf_string_conversions.h"
-#include "base/threading/thread_restrictions.h"
 #include "base/win/core_winrt_util.h"
 #include "base/win/registry.h"
 #include "base/win/scoped_co_mem.h"
@@ -122,175 +120,6 @@
 
 }  // namespace
 
-// Uses the Windows 10 WRL API's to query the current system state. The API's
-// we are using in the function below are supported in Win32 apps as per msdn.
-// It looks like the API implementation is buggy at least on Surface 4 causing
-// it to always return UserInteractionMode_Touch which as per documentation
-// indicates tablet mode.
-bool IsWindows10TabletMode(HWND hwnd) {
-  if (GetVersion() < VERSION_WIN10)
-    return false;
-
-  if (!ResolveCoreWinRTDelayload() ||
-      !ScopedHString::ResolveCoreWinRTStringDelayload()) {
-    return false;
-  }
-
-  ScopedHString view_settings_guid = ScopedHString::Create(
-      RuntimeClass_Windows_UI_ViewManagement_UIViewSettings);
-  Microsoft::WRL::ComPtr<IUIViewSettingsInterop> view_settings_interop;
-  HRESULT hr = base::win::RoGetActivationFactory(
-      view_settings_guid.get(), IID_PPV_ARGS(&view_settings_interop));
-  if (FAILED(hr))
-    return false;
-
-  Microsoft::WRL::ComPtr<ABI::Windows::UI::ViewManagement::IUIViewSettings>
-      view_settings;
-  hr = view_settings_interop->GetForWindow(hwnd, IID_PPV_ARGS(&view_settings));
-  if (FAILED(hr))
-    return false;
-
-  ABI::Windows::UI::ViewManagement::UserInteractionMode mode =
-      ABI::Windows::UI::ViewManagement::UserInteractionMode_Mouse;
-  view_settings->get_UserInteractionMode(&mode);
-  return mode == ABI::Windows::UI::ViewManagement::UserInteractionMode_Touch;
-}
-
-// Returns true if a physical keyboard is detected on Windows 8 and up.
-// Uses the Setup APIs to enumerate the attached keyboards and returns true
-// if the keyboard count is 1 or more.. While this will work in most cases
-// it won't work if there are devices which expose keyboard interfaces which
-// are attached to the machine.
-bool IsKeyboardPresentOnSlate(std::string* reason, HWND hwnd) {
-  bool result = false;
-
-  if (GetVersion() < VERSION_WIN8) {
-    if (reason)
-      *reason = "Detection not supported";
-    return false;
-  }
-
-  // This function is only supported for Windows 8 and up.
-  if (CommandLine::ForCurrentProcess()->HasSwitch(
-          switches::kDisableUsbKeyboardDetect)) {
-    if (reason)
-      *reason = "Detection disabled";
-    return false;
-  }
-
-  // This function should be only invoked for machines with touch screens.
-  if ((GetSystemMetrics(SM_DIGITIZER) & NID_INTEGRATED_TOUCH)
-        != NID_INTEGRATED_TOUCH) {
-    if (reason) {
-      *reason += "NID_INTEGRATED_TOUCH\n";
-      result = true;
-    } else {
-      return true;
-    }
-  }
-
-  // If it is a tablet device we assume that there is no keyboard attached.
-  if (IsTabletDevice(reason, hwnd)) {
-    if (reason)
-      *reason += "Tablet device.\n";
-    return false;
-  } else {
-    if (reason) {
-      *reason += "Not a tablet device";
-      result = true;
-    } else {
-      return true;
-    }
-  }
-
-  // To determine whether a keyboard is present on the device, we do the
-  // following:-
-  // 1. Check whether the device supports auto rotation. If it does then
-  //    it possibly supports flipping from laptop to slate mode. If it
-  //    does not support auto rotation, then we assume it is a desktop
-  //    or a normal laptop and assume that there is a keyboard.
-
-  // 2. If the device supports auto rotation, then we get its platform role
-  //    and check the system metric SM_CONVERTIBLESLATEMODE to see if it is
-  //    being used in slate mode. If yes then we return false here to ensure
-  //    that the OSK is displayed.
-
-  // 3. If step 1 and 2 fail then we check attached keyboards and return true
-  //    if we find ACPI\* or HID\VID* keyboards.
-
-  typedef BOOL (WINAPI* GetAutoRotationState)(PAR_STATE state);
-
-  GetAutoRotationState get_rotation_state =
-      reinterpret_cast<GetAutoRotationState>(::GetProcAddress(
-          GetModuleHandle(L"user32.dll"), "GetAutoRotationState"));
-
-  if (get_rotation_state) {
-    AR_STATE auto_rotation_state = AR_ENABLED;
-    get_rotation_state(&auto_rotation_state);
-    if ((auto_rotation_state & AR_NOSENSOR) ||
-        (auto_rotation_state & AR_NOT_SUPPORTED)) {
-      // If there is no auto rotation sensor or rotation is not supported in
-      // the current configuration, then we can assume that this is a desktop
-      // or a traditional laptop.
-      if (reason) {
-        *reason += (auto_rotation_state & AR_NOSENSOR) ? "AR_NOSENSOR\n" :
-                                                         "AR_NOT_SUPPORTED\n";
-        result = true;
-      } else {
-        return true;
-      }
-    }
-  }
-
-  const GUID KEYBOARD_CLASS_GUID =
-      { 0x4D36E96B, 0xE325,  0x11CE,
-          { 0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18 } };
-
-  // Query for all the keyboard devices.
-  HDEVINFO device_info =
-      SetupDiGetClassDevs(&KEYBOARD_CLASS_GUID, NULL, NULL, DIGCF_PRESENT);
-  if (device_info == INVALID_HANDLE_VALUE) {
-    if (reason)
-      *reason += "No keyboard info\n";
-    return result;
-  }
-
-  // Enumerate all keyboards and look for ACPI\PNP and HID\VID devices. If
-  // the count is more than 1 we assume that a keyboard is present. This is
-  // under the assumption that there will always be one keyboard device.
-  for (DWORD i = 0;; ++i) {
-    SP_DEVINFO_DATA device_info_data = { 0 };
-    device_info_data.cbSize = sizeof(device_info_data);
-    if (!SetupDiEnumDeviceInfo(device_info, i, &device_info_data))
-      break;
-
-    // Get the device ID.
-    wchar_t device_id[MAX_DEVICE_ID_LEN];
-    CONFIGRET status = CM_Get_Device_ID(device_info_data.DevInst,
-                                        device_id,
-                                        MAX_DEVICE_ID_LEN,
-                                        0);
-    if (status == CR_SUCCESS) {
-      // To reduce the scope of the hack we only look for ACPI and HID\\VID
-      // prefixes in the keyboard device ids.
-      if (StartsWith(device_id, L"ACPI", CompareCase::INSENSITIVE_ASCII) ||
-          StartsWith(device_id, L"HID\\VID", CompareCase::INSENSITIVE_ASCII)) {
-        if (reason) {
-          *reason += "device: ";
-          *reason += WideToUTF8(device_id);
-          *reason += '\n';
-        }
-        // The heuristic we are using is to check the count of keyboards and
-        // return true if the API's report one or more keyboards. Please note
-        // that this will break for non keyboard devices which expose a
-        // keyboard PDO.
-        result = true;
-      }
-    }
-  }
-  return result;
-}
-
 static bool g_crash_on_process_detach = false;
 
 void GetNonClientMetrics(NONCLIENTMETRICS_XP* metrics) {
@@ -334,11 +163,6 @@
 }
 
 bool UserAccountControlIsEnabled() {
-  // This can be slow if Windows ends up going to disk.  Should watch this key
-  // for changes and only read it once, preferably on the file thread.
-  //   http://code.google.com/p/chromium/issues/detail?id=61644
-  ThreadRestrictions::ScopedAllowIO allow_io;
-
   RegKey key(HKEY_LOCAL_MACHINE,
              L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
              KEY_READ);
@@ -446,88 +270,6 @@
   signal(SIGABRT, ForceCrashOnSigAbort);
 }
 
-bool IsTabletDevice(std::string* reason, HWND hwnd) {
-  if (GetVersion() < VERSION_WIN8) {
-    if (reason)
-      *reason = "Tablet device detection not supported below Windows 8\n";
-    return false;
-  }
-
-  if (IsWindows10TabletMode(hwnd))
-    return true;
-
-  return IsDeviceUsedAsATablet(reason);
-}
-
-// This method is used to set the right interactions media queries,
-// see https://drafts.csswg.org/mediaqueries-4/#mf-interaction. It doesn't
-// check the Windows 10 tablet mode because it doesn't reflect the actual
-// input configuration of the device and can be manually triggered by the user
-// independently from the hardware state.
-bool IsDeviceUsedAsATablet(std::string* reason) {
-  if (GetVersion() < VERSION_WIN8) {
-    if (reason)
-      *reason = "Tablet device detection not supported below Windows 8\n";
-    return false;
-  }
-
-  if (GetSystemMetrics(SM_MAXIMUMTOUCHES) == 0) {
-    if (reason) {
-      *reason += "Device does not support touch.\n";
-    } else {
-      return false;
-    }
-  }
-
-  // If the device is docked, the user is treating the device as a PC.
-  if (GetSystemMetrics(SM_SYSTEMDOCKED) != 0) {
-    if (reason) {
-      *reason += "SM_SYSTEMDOCKED\n";
-    } else {
-      return false;
-    }
-  }
-
-  // If the device is not supporting rotation, it's unlikely to be a tablet,
-  // a convertible or a detachable.
-  // See
-  // https://msdn.microsoft.com/en-us/library/windows/desktop/dn629263(v=vs.85).aspx
-  typedef decltype(GetAutoRotationState)* GetAutoRotationStateType;
-  GetAutoRotationStateType get_auto_rotation_state_func =
-      reinterpret_cast<GetAutoRotationStateType>(GetProcAddress(
-          GetModuleHandle(L"user32.dll"), "GetAutoRotationState"));
-
-  if (get_auto_rotation_state_func) {
-    AR_STATE rotation_state = AR_ENABLED;
-    if (get_auto_rotation_state_func(&rotation_state) &&
-        (rotation_state & (AR_NOT_SUPPORTED | AR_LAPTOP | AR_NOSENSOR)) != 0)
-      return false;
-  }
-
-  // PlatformRoleSlate was added in Windows 8+.
-  POWER_PLATFORM_ROLE role = GetPlatformRole();
-  bool is_tablet = false;
-  if (role == PlatformRoleMobile || role == PlatformRoleSlate) {
-    is_tablet = !GetSystemMetrics(SM_CONVERTIBLESLATEMODE);
-    if (!is_tablet) {
-      if (reason) {
-        *reason += "Not in slate mode.\n";
-      } else {
-        return false;
-      }
-    } else {
-      if (reason) {
-        *reason += (role == PlatformRoleMobile) ? "PlatformRoleMobile\n"
-                                                : "PlatformRoleSlate\n";
-      }
-    }
-  } else {
-    if (reason)
-      *reason += "Device role is not mobile or slate.\n";
-  }
-  return is_tablet;
-}
-
 bool IsUser32AndGdi32Available() {
   static auto is_user32_and_gdi32_available = []() {
     // If win32k syscalls aren't disabled, then user32 and gdi32 are available.
diff --git a/base/win/win_util.h b/base/win/win_util.h
index dc996fd..3d8830b 100644
--- a/base/win/win_util.h
+++ b/base/win/win_util.h
@@ -111,38 +111,6 @@
 // process is aborted.
 BASE_EXPORT void SetAbortBehaviorForCrashReporting();
 
-// Checks whether the supplied |hwnd| is in Windows 10 tablet mode. Will return
-// false on versions below 10.
-BASE_EXPORT bool IsWindows10TabletMode(HWND hwnd);
-
-// A tablet is a device that is touch enabled and also is being used
-// "like a tablet". This is used by the following:
-// 1. Metrics: To gain insight into how users use Chrome.
-// 2. Physical keyboard presence: If a device is in tablet mode, it means
-//    that there is no physical keyboard attached.
-// This function optionally sets the |reason| parameter to determine as to why
-// or why not a device was deemed to be a tablet.
-// Returns true if the user has set Windows 10 in tablet mode.
-BASE_EXPORT bool IsTabletDevice(std::string* reason, HWND hwnd);
-
-// Return true if the device is physically used as a tablet independently of
-// Windows tablet mode. It checks if the device:
-// - Is running Windows 8 or newer,
-// - Has a touch digitizer,
-// - Is not docked,
-// - Has a supported rotation sensor,
-// - Is not in laptop mode,
-// - prefers the mobile or slate power management profile (per OEM choice), and
-// - Is in slate mode.
-// This function optionally sets the |reason| parameter to determine as to why
-// or why not a device was deemed to be a tablet.
-BASE_EXPORT bool IsDeviceUsedAsATablet(std::string* reason);
-
-// A slate is a touch device that may have a keyboard attached. This function
-// returns true if a keyboard is attached and optionally will set the |reason|
-// parameter to the detection method that was used to detect the keyboard.
-BASE_EXPORT bool IsKeyboardPresentOnSlate(std::string* reason, HWND hwnd);
-
 // Get the size of a struct up to and including the specified member.
 // This is necessary to set compatible struct sizes for different versions
 // of certain Windows APIs (e.g. SystemParametersInfo).
diff --git a/build/gen.py b/build/gen.py
index 86affb5..45c3e33 100755
--- a/build/gen.py
+++ b/build/gen.py
@@ -225,8 +225,6 @@
 
   static_libraries = {
       'base': {'sources': [
-        'base/at_exit.cc',
-        'base/base_switches.cc',
         'base/callback_helpers.cc',
         'base/callback_internal.cc',
         'base/command_line.cc',
@@ -235,9 +233,7 @@
         'base/files/file_enumerator.cc',
         'base/files/file_path.cc',
         'base/files/file_path_constants.cc',
-        'base/files/file_tracing.cc',
         'base/files/file_util.cc',
-        'base/files/memory_mapped_file.cc',
         'base/files/scoped_file.cc',
         'base/files/scoped_temp_dir.cc',
         'base/hash.cc',
@@ -246,31 +242,15 @@
         'base/json/json_string_value_serializer.cc',
         'base/json/json_writer.cc',
         'base/json/string_escape.cc',
-        'base/lazy_instance_helpers.cc',
-        'base/location.cc',
         'base/logging.cc',
         'base/md5.cc',
         'base/memory/ref_counted.cc',
         'base/memory/weak_ptr.cc',
-        'base/message_loop/incoming_task_queue.cc',
-        'base/message_loop/message_loop.cc',
-        'base/message_loop/message_loop_current.cc',
-        'base/message_loop/message_loop_task_runner.cc',
-        'base/message_loop/message_pump.cc',
-        'base/message_loop/message_pump_default.cc',
-        'base/message_loop/watchable_io_message_pump_posix.cc',
-        'base/observer_list_threadsafe.cc',
-        'base/pending_task.cc',
         'base/process/kill.cc',
         'base/process/memory.cc',
         'base/process/process_handle.cc',
         'base/process/process_iterator.cc',
-        'base/process/process_metrics.cc',
         'base/rand_util.cc',
-        'base/run_loop.cc',
-        'base/sequence_token.cc',
-        'base/sequence_checker_impl.cc',
-        'base/sequenced_task_runner.cc',
         'base/sha1.cc',
         'base/strings/pattern.cc',
         'base/strings/string_number_conversions.cc',
@@ -282,57 +262,21 @@
         'base/strings/utf_string_conversion_utils.cc',
         'base/strings/utf_string_conversions.cc',
         'base/synchronization/atomic_flag.cc',
-        'base/synchronization/lock.cc',
-        'base/sys_info.cc',
-        'base/task_runner.cc',
-        'base/task_scheduler/delayed_task_manager.cc',
-        'base/task_scheduler/environment_config.cc',
-        'base/task_scheduler/post_task.cc',
-        'base/task_scheduler/priority_queue.cc',
-        'base/task_scheduler/scheduler_lock_impl.cc',
-        'base/task_scheduler/scheduler_single_thread_task_runner_manager.cc',
-        'base/task_scheduler/scheduler_worker.cc',
-        'base/task_scheduler/scheduler_worker_pool.cc',
-        'base/task_scheduler/scheduler_worker_pool_impl.cc',
-        'base/task_scheduler/scheduler_worker_pool_params.cc',
-        'base/task_scheduler/scheduler_worker_stack.cc',
-        'base/task_scheduler/scoped_set_task_priority_for_current_thread.cc',
-        'base/task_scheduler/sequence.cc',
-        'base/task_scheduler/sequence_sort_key.cc',
-        'base/task_scheduler/service_thread.cc',
-        'base/task_scheduler/task.cc',
-        'base/task_scheduler/task_scheduler.cc',
-        'base/task_scheduler/task_scheduler_impl.cc',
-        'base/task_scheduler/task_tracker.cc',
-        'base/task_scheduler/task_traits.cc',
-        'base/third_party/dmg_fp/dtoa_wrapper.cc',
-        'base/third_party/dmg_fp/g_fmt.cc',
         'base/third_party/icu/icu_utf.cc',
         'base/third_party/nspr/prtime.cc',
-        'base/threading/post_task_and_reply_impl.cc',
-        'base/threading/scoped_blocking_call.cc',
-        'base/threading/sequence_local_storage_map.cc',
-        'base/threading/sequenced_task_runner_handle.cc',
-        'base/threading/simple_thread.cc',
-        'base/threading/thread.cc',
-        'base/threading/thread_checker_impl.cc',
         'base/threading/thread_collision_warner.cc',
-        'base/threading/thread_id_name_manager.cc',
-        'base/threading/thread_local_storage.cc',
-        'base/threading/thread_restrictions.cc',
-        'base/threading/thread_task_runner_handle.cc',
         'base/time/clock.cc',
-        'base/time/default_clock.cc',
         'base/time/default_tick_clock.cc',
         'base/time/tick_clock.cc',
         'base/time/time.cc',
         'base/timer/elapsed_timer.cc',
-        'base/timer/timer.cc',
         'base/value_iterators.cc',
         'base/values.cc',
       ], 'tool': 'cxx', 'include_dirs': []},
       'gn_lib': {'sources': [
         'src/exe_path.cc',
+        'src/msg_loop.cc',
+        'src/sys_info.cc',
         'src/worker_pool.cc',
         'tools/gn/action_target_generator.cc',
         'tools/gn/action_values.cc',
@@ -463,10 +407,6 @@
       'tool': 'cxx', 'include_dirs': [], 'libs': []},
 
       'gn_unittests': { 'sources': [
-        'base/task_scheduler/lazy_task_runner.cc',
-        'base/test/scoped_task_environment.cc',
-        'base/test/test_mock_time_task_runner.cc',
-        'base/test/test_pending_task.cc',
         'src/test/gn_test.cc',
         'tools/gn/action_target_generator_unittest.cc',
         'tools/gn/analyzer_unittest.cc',
@@ -537,49 +477,20 @@
   if is_posix:
     static_libraries['base']['sources'].extend([
         'base/files/file_enumerator_posix.cc',
-        'base/files/file_descriptor_watcher_posix.cc',
         'base/files/file_posix.cc',
         'base/files/file_util_posix.cc',
-        'base/files/memory_mapped_file_posix.cc',
-        'base/message_loop/message_pump_libevent.cc',
         'base/posix/file_descriptor_shuffle.cc',
-        'base/posix/global_descriptors.cc',
         'base/posix/safe_strerror.cc',
         'base/process/kill_posix.cc',
         'base/process/process_handle_posix.cc',
-        'base/process/process_metrics_posix.cc',
         'base/process/process_posix.cc',
         'base/rand_util_posix.cc',
         'base/strings/string16.cc',
         'base/synchronization/condition_variable_posix.cc',
         'base/synchronization/lock_impl_posix.cc',
-        'base/sys_info_posix.cc',
-        'base/task_scheduler/task_tracker_posix.cc',
-        'base/threading/platform_thread_internal_posix.cc',
         'base/threading/platform_thread_posix.cc',
-        'base/threading/thread_local_storage_posix.cc',
         'base/time/time_conversion_posix.cc',
     ])
-    static_libraries['libevent'] = {
-        'sources': [
-            'base/third_party/libevent/buffer.c',
-            'base/third_party/libevent/evbuffer.c',
-            'base/third_party/libevent/evdns.c',
-            'base/third_party/libevent/event.c',
-            'base/third_party/libevent/event_tagging.c',
-            'base/third_party/libevent/evrpc.c',
-            'base/third_party/libevent/evutil.c',
-            'base/third_party/libevent/http.c',
-            'base/third_party/libevent/log.c',
-            'base/third_party/libevent/poll.c',
-            'base/third_party/libevent/select.c',
-            'base/third_party/libevent/signal.c',
-            'base/third_party/libevent/strlcpy.c',
-        ],
-        'tool': 'cc',
-        'include_dirs': [],
-        'cflags': cflags + ['-DHAVE_CONFIG_H'],
-    }
 
   if is_linux:
     static_libraries['base']['sources'].extend([
@@ -589,10 +500,8 @@
         'base/process/process_info_linux.cc',
         'base/process/process_iterator_linux.cc',
         'base/process/process_linux.cc',
-        'base/process/process_metrics_linux.cc',
         'base/strings/sys_string_conversions_posix.cc',
         'base/synchronization/waitable_event_posix.cc',
-        'base/sys_info_linux.cc',
         'base/time/time_exploded_posix.cc',
         'base/time/time_now_posix.cc',
         'base/threading/platform_thread_linux.cc',
@@ -605,12 +514,6 @@
         '-lrt',
         '-latomic',
     ])
-    static_libraries['libevent']['include_dirs'].extend([
-        os.path.join(REPO_ROOT, 'base', 'third_party', 'libevent', 'linux')
-    ])
-    static_libraries['libevent']['sources'].extend([
-        'base/third_party/libevent/epoll.c',
-    ])
 
   if is_mac:
     static_libraries['base']['sources'].extend([
@@ -624,24 +527,15 @@
         'base/mac/scoped_mach_port.cc',
         'base/mac/scoped_mach_vm.cc',
         'base/mac/scoped_nsautorelease_pool.mm',
-        'base/message_loop/message_pump_mac.mm',
         'base/process/process_handle_mac.cc',
         'base/process/process_info_mac.cc',
         'base/process/process_iterator_mac.cc',
-        'base/process/process_metrics_mac.cc',
         'base/strings/sys_string_conversions_mac.mm',
         'base/synchronization/waitable_event_mac.cc',
-        'base/sys_info_mac.mm',
         'base/time/time_exploded_posix.cc',
         'base/time/time_mac.cc',
         'base/threading/platform_thread_mac.mm',
     ])
-    static_libraries['libevent']['include_dirs'].extend([
-        os.path.join(REPO_ROOT, 'base', 'third_party', 'libevent', 'mac')
-    ])
-    static_libraries['libevent']['sources'].extend([
-        'base/third_party/libevent/kqueue.c',
-    ])
 
     libs.extend([
         '-framework', 'AppKit',
@@ -654,45 +548,33 @@
     static_libraries['base']['sources'].extend([
         'base/cpu.cc',
         'base/files/file_enumerator_win.cc',
-        'base/files/file_path_watcher_win.cc',
         'base/files/file_util_win.cc',
         'base/files/file_win.cc',
-        'base/files/memory_mapped_file_win.cc',
-        'base/logging_win.cc',
-        'base/message_loop/message_pump_win.cc',
         'base/process/kill_win.cc',
         'base/process/launch_win.cc',
         'base/process/memory_win.cc',
         'base/process/process_handle_win.cc',
         'base/process/process_info_win.cc',
         'base/process/process_iterator_win.cc',
-        'base/process/process_metrics_win.cc',
         'base/process/process_win.cc',
         'base/rand_util_win.cc',
         'base/strings/sys_string_conversions_win.cc',
         'base/synchronization/condition_variable_win.cc',
         'base/synchronization/lock_impl_win.cc',
-        'base/synchronization/waitable_event_watcher_win.cc',
         'base/synchronization/waitable_event_win.cc',
-        'base/sys_info_win.cc',
         'base/threading/platform_thread_win.cc',
-        'base/threading/thread_local_storage_win.cc',
         'base/time/time_win.cc',
-        'base/timer/hi_res_timer_manager_win.cc',
         'base/win/core_winrt_util.cc',
         'base/win/enum_variant.cc',
         'base/win/event_trace_controller.cc',
         'base/win/event_trace_provider.cc',
         'base/win/iat_patch_function.cc',
         'base/win/iunknown_impl.cc',
-        'base/win/message_window.cc',
-        'base/win/object_watcher.cc',
         'base/win/pe_image.cc',
         'base/win/process_startup_helper.cc',
         'base/win/registry.cc',
         'base/win/resource_util.cc',
         'base/win/scoped_bstr.cc',
-        'base/win/scoped_com_initializer.cc',
         'base/win/scoped_handle.cc',
         'base/win/scoped_process_information.cc',
         'base/win/scoped_variant.cc',
diff --git a/src/msg_loop.cc b/src/msg_loop.cc
new file mode 100644
index 0000000..3bb0a24
--- /dev/null
+++ b/src/msg_loop.cc
@@ -0,0 +1,76 @@
+// Copyright 2018 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 "msg_loop.h"
+
+#include "base/logging.h"
+
+namespace {
+
+thread_local MsgLoop* g_current;
+}
+
+MsgLoop::MsgLoop() {
+  DCHECK(g_current == nullptr);
+  g_current = this;
+}
+
+MsgLoop::~MsgLoop() {
+  DCHECK(g_current == this);
+  g_current = nullptr;
+}
+
+void MsgLoop::Run() {
+  while (!should_quit_) {
+    Task task;
+    {
+      std::unique_lock<std::mutex> queue_lock(queue_mutex_);
+      notifier_.wait(queue_lock, [this]() {
+        return (!task_queue_.empty()) || should_quit_;
+      });
+
+      if (should_quit_)
+        return;
+
+      task = std::move(task_queue_.front());
+      task_queue_.pop();
+    }
+
+    std::move(task).Run();
+  }
+}
+
+void MsgLoop::PostQuit() {
+  PostTask(
+      base::BindOnce([](MsgLoop* self) { self->should_quit_ = true; }, this));
+}
+
+void MsgLoop::PostTask(Task work) {
+  {
+    std::unique_lock<std::mutex> queue_lock(queue_mutex_);
+    task_queue_.emplace(std::move(work));
+  }
+
+  notifier_.notify_one();
+}
+
+void MsgLoop::RunUntilIdleForTesting() {
+  for (bool done = false; !done;) {
+    Task task;
+    {
+      std::unique_lock<std::mutex> queue_lock(queue_mutex_);
+      task = std::move(task_queue_.front());
+      task_queue_.pop();
+
+      if (task_queue_.empty())
+        done = true;
+    }
+
+    std::move(task).Run();
+  }
+}
+
+MsgLoop* MsgLoop::Current() {
+  return g_current;
+}
diff --git a/src/msg_loop.h b/src/msg_loop.h
new file mode 100644
index 0000000..5f1d69c
--- /dev/null
+++ b/src/msg_loop.h
@@ -0,0 +1,47 @@
+// Copyright 2018 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 RUN_LOOP_H_
+#define RUN_LOOP_H_
+
+#include "base/macros.h"
+#include "task.h"
+
+#include <condition_variable>
+#include <mutex>
+#include <queue>
+
+class MsgLoop {
+ public:
+  MsgLoop();
+  ~MsgLoop();
+
+  // Blocks until PostQuit() is called, processing work items posted via
+  void Run();
+
+  // Schedules Run() to exit, but will not happen until other outstanding tasks
+  // complete. Can be called from any thread.
+  void PostQuit();
+
+  // Posts a work item to this queue. All items will be run on the thread from
+  // which Run() was called. Can be called from any thread.
+  void PostTask(Task task);
+
+  // Run()s until the queue is empty. Should only be used (carefully) in tests.
+  void RunUntilIdleForTesting();
+
+  // Gets the MsgLoop for the thread from which it's called, or nullptr if
+  // there's no MsgLoop for the current thread.
+  static MsgLoop* Current();
+
+ private:
+  std::mutex queue_mutex_;
+  std::queue<Task> task_queue_;
+  std::condition_variable notifier_;
+  bool should_quit_ = false;
+
+  DISALLOW_COPY_AND_ASSIGN(MsgLoop);
+};
+
+#endif  // RUN_LOOP_H_
diff --git a/src/sys_info.cc b/src/sys_info.cc
new file mode 100644
index 0000000..ad71b6f
--- /dev/null
+++ b/src/sys_info.cc
@@ -0,0 +1,81 @@
+// Copyright 2018 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 "sys_info.h"
+
+#include "base/logging.h"
+#include "build_config.h"
+
+#if defined(OS_POSIX)
+#include <sys/utsname.h>
+#include <unistd.h>
+#endif
+
+#if defined(OS_WIN)
+#include <windows.h>
+#endif
+
+std::string OperatingSystemArchitecture() {
+#if defined(OS_POSIX)
+  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";
+  } else if (std::string(info.sysname) == "AIX") {
+    arch = "ppc64";
+  }
+  return arch;
+#elif defined(OS_WIN)
+  SYSTEM_INFO system_info = {};
+  ::GetNativeSystemInfo(&system_info);
+  switch (system_info.wProcessorArchitecture) {
+    case PROCESSOR_ARCHITECTURE_INTEL:
+      return "x86";
+    case PROCESSOR_ARCHITECTURE_AMD64:
+      return "x86_64";
+    case PROCESSOR_ARCHITECTURE_IA64:
+      return "ia64";
+  }
+  return std::string();
+#else
+#error
+#endif
+}
+
+int NumberOfProcessors() {
+#if defined(OS_POSIX)
+  // sysconf returns the number of "logical" (not "physical") processors on both
+  // Mac and Linux.  So we get the number of max available "logical" processors.
+  //
+  // Note that the number of "currently online" processors may be fewer than the
+  // returned value of NumberOfProcessors(). On some platforms, the kernel may
+  // make some processors offline intermittently, to save power when system
+  // loading is low.
+  //
+  // One common use case that needs to know the processor count is to create
+  // optimal number of threads for optimization. It should make plan according
+  // to the number of "max available" processors instead of "currently online"
+  // ones. The kernel should be smart enough to make all processors online when
+  // it has sufficient number of threads waiting to run.
+  long res = sysconf(_SC_NPROCESSORS_CONF);
+  if (res == -1) {
+    NOTREACHED();
+    return 1;
+  }
+
+  return static_cast<int>(res);
+#elif defined(OS_WIN)
+  SYSTEM_INFO system_info = {};
+  ::GetNativeSystemInfo(&system_info);
+  return system_info.dwNumberOfProcessors;
+#else
+#error
+#endif
+}
diff --git a/src/sys_info.h b/src/sys_info.h
new file mode 100644
index 0000000..9b0a1ef
--- /dev/null
+++ b/src/sys_info.h
@@ -0,0 +1,13 @@
+// Copyright 2018 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 SYS_INFO_H_
+#define SYS_INFO_H_
+
+#include <string>
+
+std::string OperatingSystemArchitecture();
+int NumberOfProcessors();
+
+#endif  // SYS_INFO_H_
diff --git a/src/task.h b/src/task.h
new file mode 100644
index 0000000..21ec1a4
--- /dev/null
+++ b/src/task.h
@@ -0,0 +1,13 @@
+// Copyright 2018 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 TASK_H_
+#define TASK_H_
+
+#include "base/bind.h"
+#include "base/callback.h"
+
+using Task = base::OnceClosure;
+
+#endif  // TASK_H_
diff --git a/src/worker_pool.cc b/src/worker_pool.cc
index e204084..e59ddcc 100644
--- a/src/worker_pool.cc
+++ b/src/worker_pool.cc
@@ -6,7 +6,7 @@
 
 #include "base/command_line.h"
 #include "base/strings/string_number_conversions.h"
-#include "base/sys_info.h"
+#include "sys_info.h"
 #include "tools/gn/switches.h"
 
 namespace {
@@ -37,7 +37,7 @@
   // The minimum thread count is based on measuring the optimal threads for the
   // Chrome build on a several-year-old 4-core MacBook.
   // Almost all CPUs now are hyperthreaded.
-  int num_cores = base::SysInfo::NumberOfProcessors() / 2;
+  int num_cores = NumberOfProcessors() / 2;
   return std::max(num_cores - 1, 8);
 }
 
@@ -65,7 +65,7 @@
   }
 }
 
-void WorkerPool::PostTask(std::function<void()> work) {
+void WorkerPool::PostTask(Task work) {
   {
     std::unique_lock<std::mutex> queue_lock(queue_mutex_);
     CHECK(!should_stop_processing_);
@@ -77,7 +77,7 @@
 
 void WorkerPool::Worker() {
   for (;;) {
-    std::function<void()> task;
+    Task task;
 
     {
       std::unique_lock<std::mutex> queue_lock(queue_mutex_);
@@ -93,6 +93,6 @@
       task_queue_.pop();
     }
 
-    task();
+    std::move(task).Run();
   }
 }
diff --git a/src/worker_pool.h b/src/worker_pool.h
index a95a175..99dcd65 100644
--- a/src/worker_pool.h
+++ b/src/worker_pool.h
@@ -5,29 +5,28 @@
 #ifndef WORKER_POOL_H_
 #define WORKER_POOL_H_
 
-#include "base/logging.h"
-#include "base/macros.h"
-
 #include <condition_variable>
-#include <functional>
-#include <future>
 #include <mutex>
 #include <queue>
 #include <thread>
 
+#include "base/logging.h"
+#include "base/macros.h"
+#include "task.h"
+
 class WorkerPool {
  public:
   WorkerPool();
   WorkerPool(size_t thread_count);
   ~WorkerPool();
 
-  void PostTask(std::function<void()> work);
+  void PostTask(Task work);
 
  private:
   void Worker();
 
   std::vector<std::thread> threads_;
-  std::queue<std::function<void()>> task_queue_;
+  std::queue<base::OnceClosure> task_queue_;
   std::mutex queue_mutex_;
   std::condition_variable_any pool_notifier_;
   bool should_stop_processing_;
diff --git a/tools/gn/args.cc b/tools/gn/args.cc
index a9adfb8..c7cd60f 100644
--- a/tools/gn/args.cc
+++ b/tools/gn/args.cc
@@ -4,8 +4,8 @@
 
 #include "tools/gn/args.h"
 
-#include "base/sys_info.h"
 #include "build_config.h"
+#include "sys_info.h"
 #include "tools/gn/source_file.h"
 #include "tools/gn/string_utils.h"
 #include "tools/gn/variables.h"
@@ -329,7 +329,7 @@
 
   // Set the host CPU architecture based on the underlying OS, not
   // whatever the current bit-tedness of the GN binary is.
-  std::string os_arch = base::SysInfo::OperatingSystemArchitecture();
+  std::string os_arch = OperatingSystemArchitecture();
   if (os_arch == "x86")
     arch = kX86;
   else if (os_arch == "x86_64")
diff --git a/tools/gn/args.h b/tools/gn/args.h
index ee45085..4d768c7 100644
--- a/tools/gn/args.h
+++ b/tools/gn/args.h
@@ -7,8 +7,8 @@
 
 #include <map>
 #include <set>
+#include <unordered_map>
 
-#include "base/containers/hash_tables.h"
 #include "base/macros.h"
 #include "base/synchronization/lock.h"
 #include "tools/gn/scope.h"
@@ -97,7 +97,7 @@
 
  private:
   using ArgumentsPerToolchain =
-      base::hash_map<const Settings*, Scope::KeyValueMap>;
+      std::unordered_map<const Settings*, Scope::KeyValueMap>;
 
   // Sets the default config based on the current system.
   void SetSystemVarsLocked(Scope* scope) const;
diff --git a/tools/gn/command_gen.cc b/tools/gn/command_gen.cc
index 46c6ca9..be59240 100644
--- a/tools/gn/command_gen.cc
+++ b/tools/gn/command_gen.cc
@@ -73,7 +73,7 @@
   const Target* target = item->AsTarget();
   if (target) {
     g_scheduler->ScheduleWork(
-        std::bind(&BackgroundDoWrite, write_info, target));
+        base::Bind(&BackgroundDoWrite, write_info, target));
   }
 }
 
diff --git a/tools/gn/command_path.cc b/tools/gn/command_path.cc
index daa2200..52086f8 100644
--- a/tools/gn/command_path.cc
+++ b/tools/gn/command_path.cc
@@ -7,7 +7,6 @@
 #include <algorithm>
 
 #include "base/command_line.h"
-#include "base/containers/hash_tables.h"
 #include "base/strings/stringprintf.h"
 #include "tools/gn/commands.h"
 #include "tools/gn/setup.h"
diff --git a/tools/gn/function_exec_script.cc b/tools/gn/function_exec_script.cc
index 1c5c517..d1fc6e9 100644
--- a/tools/gn/function_exec_script.cc
+++ b/tools/gn/function_exec_script.cc
@@ -7,7 +7,6 @@
 #include "base/logging.h"
 #include "base/strings/string_number_conversions.h"
 #include "base/strings/utf_string_conversions.h"
-#include "base/threading/thread_restrictions.h"
 #include "base/time/time.h"
 #include "build_config.h"
 #include "tools/gn/err.h"
@@ -116,9 +115,6 @@
   exec_script("//foo/bar/myscript.py")
 )";
 
-class ExecScriptScopedAllowBaseSyncPrimitives
-    : public base::ScopedAllowBaseSyncPrimitives {};
-
 Value RunExecScript(Scope* scope,
                     const FunctionCallNode* function,
                     const std::vector<Value>& args,
@@ -229,7 +225,6 @@
   std::string stderr_output;
   int exit_code = 0;
   {
-    ExecScriptScopedAllowBaseSyncPrimitives allow_base_sync_primitives;
     if (!internal::ExecProcess(cmdline, startup_dir, &output, &stderr_output,
                                &exit_code)) {
       *err = Err(
diff --git a/tools/gn/gn_main.cc b/tools/gn/gn_main.cc
index a9f684e..d2dd4a8 100644
--- a/tools/gn/gn_main.cc
+++ b/tools/gn/gn_main.cc
@@ -5,11 +5,11 @@
 #include <algorithm>
 #include <string>
 
-#include "base/at_exit.h"
 #include "base/command_line.h"
-#include "base/message_loop/message_loop.h"
 #include "base/strings/utf_string_conversions.h"
 #include "build_config.h"
+#include "msg_loop.h"
+#include "sys_info.h"
 #include "tools/gn/commands.h"
 #include "tools/gn/err.h"
 #include "tools/gn/location.h"
@@ -41,7 +41,6 @@
 }  // namespace
 
 int main(int argc, char** argv) {
-  base::AtExitManager at_exit;
 #if defined(OS_WIN)
   base::CommandLine::set_slash_is_not_a_switch();
 #endif
@@ -75,7 +74,7 @@
 
   int retval;
   if (found_command != command_map.end()) {
-    base::MessageLoop message_loop;
+    MsgLoop msg_loop;
     retval = found_command->second.runner(args);
   } else {
     Err(Location(), "Command \"" + command + "\" unknown.").PrintToStdout();
diff --git a/tools/gn/header_checker.cc b/tools/gn/header_checker.cc
index 499b16e..a38ef25 100644
--- a/tools/gn/header_checker.cc
+++ b/tools/gn/header_checker.cc
@@ -170,19 +170,8 @@
     for (const auto& vect_i : file.second) {
       if (vect_i.target->check_includes()) {
         task_count_.Increment();
-        pool.PostTask([ this, target = vect_i.target, f = file.first ] {
-          Err err;
-          if (!CheckFile(target, f, &err)) {
-            base::AutoLock lock(lock_);
-            errors_.push_back(err);
-          }
-
-          if (!task_count_.Decrement()) {
-            // Signal |task_count_cv_| when |task_count_| becomes zero.
-            base::AutoLock auto_lock(lock_);
-            task_count_cv_.Signal();
-          }
-        });
+        pool.PostTask(base::BindOnce(&HeaderChecker::DoWork, this,
+                                     vect_i.target, file.first));
       }
     }
   }
@@ -193,6 +182,20 @@
     task_count_cv_.Wait();
 }
 
+void HeaderChecker::DoWork(const Target* target, const SourceFile& file) {
+  Err err;
+  if (!CheckFile(target, file, &err)) {
+    base::AutoLock lock(lock_);
+    errors_.push_back(err);
+  }
+
+  if (!task_count_.Decrement()) {
+    // Signal |task_count_cv_| when |task_count_| becomes zero.
+    base::AutoLock auto_lock(lock_);
+    task_count_cv_.Signal();
+  }
+}
+
 // static
 void HeaderChecker::AddTargetToFileMap(const Target* target, FileMap* dest) {
   // Files in the sources have this public bit by default.
diff --git a/tools/gn/header_checker.h b/tools/gn/header_checker.h
index 2117b88..b1d0f79 100644
--- a/tools/gn/header_checker.h
+++ b/tools/gn/header_checker.h
@@ -101,6 +101,8 @@
   // will be populate on failure.
   void RunCheckOverFiles(const FileMap& flies, bool force_check);
 
+  void DoWork(const Target* target, const SourceFile& file);
+
   // Adds the sources and public files from the given target to the given map.
   static void AddTargetToFileMap(const Target* target, FileMap* dest);
 
diff --git a/tools/gn/input_conversion.cc b/tools/gn/input_conversion.cc
index 22d33ca..131df0c 100644
--- a/tools/gn/input_conversion.cc
+++ b/tools/gn/input_conversion.cc
@@ -131,9 +131,6 @@
       return Value(origin, value.GetBool());
     case base::Value::Type::INTEGER:
       return Value(origin, static_cast<int64_t>(value.GetInt()));
-    case base::Value::Type::DOUBLE:
-      *err = Err(origin, "Floating point values are not supported.");
-      return Value();
     case base::Value::Type::STRING:
       return Value(origin, value.GetString());
     case base::Value::Type::BINARY:
diff --git a/tools/gn/input_conversion_unittest.cc b/tools/gn/input_conversion_unittest.cc
index 10d0488..e00559d 100644
--- a/tools/gn/input_conversion_unittest.cc
+++ b/tools/gn/input_conversion_unittest.cc
@@ -221,7 +221,8 @@
   Value result = ConvertInputToValue(settings(), input, nullptr,
                                      Value(nullptr, "json"), &err);
   EXPECT_TRUE(err.has_error());
-  EXPECT_EQ("Floating point values are not supported.", err.message());
+  // Doubles aren't supported.
+  EXPECT_EQ("Input is not a valid JSON: ", err.message());
 }
 
 TEST_F(InputConversionTest, ValueEmpty) {
diff --git a/tools/gn/input_file_manager.cc b/tools/gn/input_file_manager.cc
index e2ae6e8..37841ae 100644
--- a/tools/gn/input_file_manager.cc
+++ b/tools/gn/input_file_manager.cc
@@ -103,7 +103,7 @@
   // Try not to schedule callbacks while holding the lock. All cases that don't
   // want to schedule should return early. Otherwise, this will be scheduled
   // after we leave the lock.
-  std::function<void()> schedule_this;
+  Task schedule_this;
   {
     base::AutoLock lock(lock_);
 
@@ -113,8 +113,9 @@
       std::unique_ptr<InputFileData> data =
           std::make_unique<InputFileData>(file_name);
       data->scheduled_callbacks.push_back(callback);
-      schedule_this = std::bind(&InputFileManager::BackgroundLoadFile, this,
-                                origin, build_settings, file_name, &data->file);
+      schedule_this =
+          base::BindOnce(&InputFileManager::BackgroundLoadFile, this, origin,
+                         build_settings, file_name, &data->file);
       input_files_[file_name] = std::move(data);
 
     } else {
@@ -134,8 +135,8 @@
 
       if (data->loaded) {
         // Can just directly issue the callback on the background thread.
-        schedule_this = std::bind(&InvokeFileLoadCallback, callback,
-                                  data->parsed_root.get());
+        schedule_this = base::BindOnce(&InvokeFileLoadCallback, callback,
+                                       data->parsed_root.get());
       } else {
         // Load is pending on this file, schedule the invoke.
         data->scheduled_callbacks.push_back(callback);
@@ -143,7 +144,7 @@
       }
     }
   }
-  g_scheduler->ScheduleWork(schedule_this);
+  g_scheduler->ScheduleWork(std::move(schedule_this));
   return true;
 }
 
diff --git a/tools/gn/input_file_manager.h b/tools/gn/input_file_manager.h
index dd16604..f4dc130 100644
--- a/tools/gn/input_file_manager.h
+++ b/tools/gn/input_file_manager.h
@@ -6,11 +6,11 @@
 #define TOOLS_GN_INPUT_FILE_MANAGER_H_
 
 #include <set>
+#include <unordered_map>
 #include <utility>
 #include <vector>
 
 #include "base/callback.h"
-#include "base/containers/hash_tables.h"
 #include "base/files/file_path.h"
 #include "base/macros.h"
 #include "base/memory/ref_counted.h"
@@ -137,7 +137,7 @@
   mutable base::Lock lock_;
 
   // Maps repo-relative filenames to the corresponding owned pointer.
-  typedef base::hash_map<SourceFile, std::unique_ptr<InputFileData>>
+  typedef std::unordered_map<SourceFile, std::unique_ptr<InputFileData>>
       InputFileMap;
   InputFileMap input_files_;
 
diff --git a/tools/gn/label.h b/tools/gn/label.h
index 88fe430..54dadff 100644
--- a/tools/gn/label.h
+++ b/tools/gn/label.h
@@ -7,7 +7,6 @@
 
 #include <stddef.h>
 
-#include "base/containers/hash_tables.h"
 #include "tools/gn/source_dir.h"
 
 class Err;
@@ -105,7 +104,7 @@
   std::string toolchain_name_;
 };
 
-namespace BASE_HASH_NAMESPACE {
+namespace std {
 
 template<> struct hash<Label> {
   std::size_t operator()(const Label& v) const {
@@ -117,7 +116,7 @@
   }
 };
 
-}  // namespace BASE_HASH_NAMESPACE
+}  // namespace std
 
 inline void swap(Label& lhs, Label& rhs) {
   lhs.swap(rhs);
diff --git a/tools/gn/label_ptr.h b/tools/gn/label_ptr.h
index c0b2d63..24906dd 100644
--- a/tools/gn/label_ptr.h
+++ b/tools/gn/label_ptr.h
@@ -103,15 +103,15 @@
   return a.label < b.label;
 }
 
-namespace BASE_HASH_NAMESPACE {
+namespace std {
 
 template<typename T> struct hash< LabelPtrPair<T> > {
   std::size_t operator()(const LabelPtrPair<T>& v) const {
-    BASE_HASH_NAMESPACE::hash<Label> h;
+    hash<Label> h;
     return h(v.label);
   }
 };
 
-}  // namespace BASE_HASH_NAMESPACE
+}  // namespace std
 
 #endif  // TOOLS_GN_LABEL_PTR_H_
diff --git a/tools/gn/lib_file.h b/tools/gn/lib_file.h
index 675a48c..f1f073f 100644
--- a/tools/gn/lib_file.h
+++ b/tools/gn/lib_file.h
@@ -39,7 +39,7 @@
   SourceFile source_file_;
 };
 
-namespace BASE_HASH_NAMESPACE {
+namespace std {
 
 template <>
 struct hash<LibFile> {
@@ -49,7 +49,7 @@
   }
 };
 
-}  // namespace BASE_HASH_NAMESPACE
+}  // namespace std
 
 inline void swap(LibFile& lhs, LibFile& rhs) {
   lhs.Swap(&rhs);
diff --git a/tools/gn/loader.cc b/tools/gn/loader.cc
index 2e10c9a..1459f8e 100644
--- a/tools/gn/loader.cc
+++ b/tools/gn/loader.cc
@@ -7,7 +7,6 @@
 #include <memory>
 
 #include "base/bind.h"
-#include "base/threading/thread_task_runner_handle.h"
 #include "tools/gn/build_settings.h"
 #include "tools/gn/err.h"
 #include "tools/gn/filesystem_utils.h"
@@ -98,8 +97,7 @@
     : pending_loads_(0), build_settings_(build_settings) {
   // There may not be an active TaskRunner at this point. When that's the case,
   // the calling code is expected to call set_task_runner().
-  if (base::ThreadTaskRunnerHandle::IsSet())
-    task_runner_ = base::ThreadTaskRunnerHandle::Get();
+  task_runner_ = MsgLoop::Current();
 }
 
 LoaderImpl::~LoaderImpl() = default;
@@ -239,7 +237,7 @@
                                     const ParseNode* root) {
   if (!root) {
     task_runner_->PostTask(
-        FROM_HERE, base::Bind(&LoaderImpl::DecrementPendingLoads, this));
+        base::BindOnce(&LoaderImpl::DecrementPendingLoads, this));
     return;
   }
 
@@ -278,7 +276,7 @@
 
   trace.Done();
 
-  task_runner_->PostTask(FROM_HERE, base::Bind(&LoaderImpl::DidLoadFile, this));
+  task_runner_->PostTask(base::BindOnce(&LoaderImpl::DidLoadFile, this));
 }
 
 void LoaderImpl::BackgroundLoadBuildConfig(
@@ -287,7 +285,7 @@
     const ParseNode* root) {
   if (!root) {
     task_runner_->PostTask(
-        FROM_HERE, base::Bind(&LoaderImpl::DecrementPendingLoads, this));
+        base::BindOnce(&LoaderImpl::DecrementPendingLoads, this));
     return;
   }
 
@@ -339,9 +337,8 @@
     }
   }
 
-  task_runner_->PostTask(FROM_HERE,
-                         base::Bind(&LoaderImpl::DidLoadBuildConfig, this,
-                                    settings->toolchain_label()));
+  task_runner_->PostTask(base::BindOnce(&LoaderImpl::DidLoadBuildConfig, this,
+                                        settings->toolchain_label()));
 }
 
 void LoaderImpl::DidLoadFile() {
diff --git a/tools/gn/loader.h b/tools/gn/loader.h
index 17f7110..a028565 100644
--- a/tools/gn/loader.h
+++ b/tools/gn/loader.h
@@ -11,7 +11,7 @@
 
 #include "base/callback.h"
 #include "base/memory/ref_counted.h"
-#include "base/single_thread_task_runner.h"
+#include "msg_loop.h"
 #include "tools/gn/label.h"
 #include "tools/gn/scope.h"
 
@@ -90,10 +90,7 @@
   // Sets the task runner corresponding to the main thread. By default this
   // class will use the thread active during construction, but there is not
   // a task runner active during construction all the time.
-  void set_task_runner(
-      scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
-    task_runner_ = task_runner;
-  }
+  void set_task_runner(MsgLoop* task_runner) { task_runner_ = task_runner; }
 
   // The complete callback is called whenever there are no more pending loads.
   // Called on the main thread only. This may be called more than once if the
@@ -159,7 +156,7 @@
                      const base::Callback<void(const ParseNode*)>& callback,
                      Err* err);
 
-  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
+  MsgLoop* task_runner_;
 
   int pending_loads_;
   base::Closure complete_callback_;
diff --git a/tools/gn/loader_unittest.cc b/tools/gn/loader_unittest.cc
index add7c55..78a8584 100644
--- a/tools/gn/loader_unittest.cc
+++ b/tools/gn/loader_unittest.cc
@@ -8,7 +8,7 @@
 #include <vector>
 
 #include "base/bind.h"
-#include "base/run_loop.h"
+#include "msg_loop.h"
 #include "test/test.h"
 #include "tools/gn/build_settings.h"
 #include "tools/gn/err.h"
@@ -176,12 +176,12 @@
 
   // Completing the build config load should kick off the root build file load.
   mock_ifm_.IssueAllPending();
-  base::RunLoop().RunUntilIdle();
+  MsgLoop::Current()->RunUntilIdleForTesting();
   EXPECT_TRUE(mock_ifm_.HasOnePending(root_build));
 
   // Load the root build file.
   mock_ifm_.IssueAllPending();
-  base::RunLoop().RunUntilIdle();
+  MsgLoop::Current()->RunUntilIdleForTesting();
 
   // Schedule some other file to load in another toolchain.
   Label second_tc(SourceDir("//tc2/"), "tc2");
@@ -192,7 +192,7 @@
   // Running the toolchain file should schedule the build config file to load
   // for that toolchain.
   mock_ifm_.IssueAllPending();
-  base::RunLoop().RunUntilIdle();
+  MsgLoop::Current()->RunUntilIdleForTesting();
 
   // We have to tell it we have a toolchain definition now (normally the
   // builder would do this).
@@ -209,7 +209,7 @@
 
   // Running the build config file should make our third file pending.
   mock_ifm_.IssueAllPending();
-  base::RunLoop().RunUntilIdle();
+  MsgLoop::Current()->RunUntilIdleForTesting();
   EXPECT_TRUE(mock_ifm_.HasTwoPending(second_file, third_file));
 
   EXPECT_FALSE(scheduler().is_failed());
@@ -242,13 +242,13 @@
 
   // Completing the build config load should kick off the root build file load.
   mock_ifm_.IssueAllPending();
-  base::RunLoop().RunUntilIdle();
+  MsgLoop::Current()->RunUntilIdleForTesting();
   EXPECT_TRUE(mock_ifm_.HasOnePending(root_build));
 
   // Completing the root build file should define a target which must have
   // set of source files hashes.
   mock_ifm_.IssueAllPending();
-  base::RunLoop().RunUntilIdle();
+  MsgLoop::Current()->RunUntilIdleForTesting();
 
   std::vector<const Item*> items = mock_builder_.GetAllItems();
   EXPECT_TRUE(items[0]->AsTarget());
diff --git a/tools/gn/ninja_binary_target_writer.cc b/tools/gn/ninja_binary_target_writer.cc
index fb2fcf8..2e24135 100644
--- a/tools/gn/ninja_binary_target_writer.cc
+++ b/tools/gn/ninja_binary_target_writer.cc
@@ -10,8 +10,8 @@
 #include <cstring>
 #include <set>
 #include <sstream>
+#include <unordered_set>
 
-#include "base/containers/hash_tables.h"
 #include "base/strings/string_util.h"
 #include "tools/gn/config_values_extractors.h"
 #include "tools/gn/deps_iterator.h"
@@ -1064,7 +1064,7 @@
 
 bool NinjaBinaryTargetWriter::CheckForDuplicateObjectFiles(
     const std::vector<OutputFile>& files) const {
-  base::hash_set<std::string> set;
+  std::unordered_set<std::string> set;
   for (const auto& file : files) {
     if (!set.insert(file.value()).second) {
       Err err(
diff --git a/tools/gn/ninja_build_writer.cc b/tools/gn/ninja_build_writer.cc
index 0f40226..1ce08e9 100644
--- a/tools/gn/ninja_build_writer.cc
+++ b/tools/gn/ninja_build_writer.cc
@@ -9,6 +9,7 @@
 #include <fstream>
 #include <map>
 #include <sstream>
+#include <unordered_set>
 
 #include "base/command_line.h"
 #include "base/files/file_util.h"
@@ -417,7 +418,7 @@
   // Track rules as we generate them so we don't accidentally write a phony
   // rule that collides with something else.
   // GN internally generates an "all" target, so don't duplicate it.
-  base::hash_set<std::string> written_rules;
+  std::unordered_set<std::string> written_rules;
   written_rules.insert("all");
 
   // Set if we encounter a target named "//:default".
diff --git a/tools/gn/ninja_build_writer.h b/tools/gn/ninja_build_writer.h
index df6d1c8..bfc75e3 100644
--- a/tools/gn/ninja_build_writer.h
+++ b/tools/gn/ninja_build_writer.h
@@ -8,6 +8,7 @@
 #include <iosfwd>
 #include <map>
 #include <vector>
+#include <unordered_map>
 
 #include "base/macros.h"
 #include "tools/gn/path_output.h"
diff --git a/tools/gn/output_file.h b/tools/gn/output_file.h
index a7882fd..2f96a33 100644
--- a/tools/gn/output_file.h
+++ b/tools/gn/output_file.h
@@ -9,7 +9,6 @@
 
 #include <string>
 
-#include "base/containers/hash_tables.h"
 #include "tools/gn/build_settings.h"
 
 class SourceFile;
@@ -48,7 +47,7 @@
   std::string value_;
 };
 
-namespace BASE_HASH_NAMESPACE {
+namespace std {
 
 template<> struct hash<OutputFile> {
   std::size_t operator()(const OutputFile& v) const {
@@ -57,7 +56,7 @@
   }
 };
 
-}  // namespace BASE_HASH_NAMESPACE
+}  // namespace std
 
 inline void swap(OutputFile& lhs, OutputFile& rhs) {
   lhs.value().swap(rhs.value());
diff --git a/tools/gn/scheduler.cc b/tools/gn/scheduler.cc
index dd43ce7..0ab9c22 100644
--- a/tools/gn/scheduler.cc
+++ b/tools/gn/scheduler.cc
@@ -7,8 +7,6 @@
 #include <algorithm>
 
 #include "base/bind.h"
-#include "base/single_thread_task_runner.h"
-#include "base/threading/thread_task_runner_handle.h"
 #include "tools/gn/standard_out.h"
 #include "tools/gn/target.h"
 
@@ -19,7 +17,7 @@
 Scheduler* g_scheduler = nullptr;
 
 Scheduler::Scheduler()
-    : main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()),
+    : main_thread_run_loop_(MsgLoop::Current()),
       input_file_manager_(new InputFileManager),
       verbose_logging_(false),
       pool_work_count_cv_(&pool_work_count_lock_),
@@ -36,7 +34,7 @@
 }
 
 bool Scheduler::Run() {
-  runner_.Run();
+  main_thread_run_loop_->Run();
   bool local_is_failed;
   {
     base::AutoLock lock(lock_);
@@ -50,15 +48,8 @@
 }
 
 void Scheduler::Log(const std::string& verb, const std::string& msg) {
-  if (task_runner()->BelongsToCurrentThread()) {
-    LogOnMainThread(verb, msg);
-  } else {
-    // The run loop always joins on the sub threads, so the lifetime of this
-    // object outlives the invocations of this function, hence "unretained".
-    task_runner()->PostTask(FROM_HERE,
-                            base::Bind(&Scheduler::LogOnMainThread,
-                                       base::Unretained(this), verb, msg));
-  }
+  task_runner()->PostTask(base::BindOnce(&Scheduler::LogOnMainThread,
+                                         base::Unretained(this), verb, msg));
 }
 
 void Scheduler::FailWithError(const Err& err) {
@@ -71,28 +62,23 @@
     is_failed_ = true;
   }
 
-  if (task_runner()->BelongsToCurrentThread()) {
-    FailWithErrorOnMainThread(err);
-  } else {
-    // The run loop always joins on the sub threads, so the lifetime of this
-    // object outlives the invocations of this function, hence "unretained".
-    task_runner()->PostTask(FROM_HERE,
-                            base::Bind(&Scheduler::FailWithErrorOnMainThread,
-                                       base::Unretained(this), err));
-  }
+  task_runner()->PostTask(base::BindOnce(&Scheduler::FailWithErrorOnMainThread,
+                                         base::Unretained(this), err));
 }
 
-void Scheduler::ScheduleWork(std::function<void()> work) {
+void Scheduler::ScheduleWork(Task work) {
   IncrementWorkCount();
   pool_work_count_.Increment();
-  worker_pool_.PostTask([ this, work = std::move(work) ] {
-    work();
-    DecrementWorkCount();
-    if (!pool_work_count_.Decrement()) {
-      base::AutoLock auto_lock(pool_work_count_lock_);
-      pool_work_count_cv_.Signal();
-    }
-  });
+  worker_pool_.PostTask(base::BindOnce(
+      [](Scheduler* self, Task work) {
+        std::move(work).Run();
+        self->DecrementWorkCount();
+        if (!self->pool_work_count_.Decrement()) {
+          base::AutoLock auto_lock(self->pool_work_count_lock_);
+          self->pool_work_count_cv_.Signal();
+        }
+      },
+      this, std::move(work)));
 }
 
 void Scheduler::AddGenDependency(const base::FilePath& file) {
@@ -166,12 +152,8 @@
 
 void Scheduler::DecrementWorkCount() {
   if (!work_count_.Decrement()) {
-    if (task_runner()->BelongsToCurrentThread()) {
-      OnComplete();
-    } else {
-      task_runner()->PostTask(FROM_HERE, base::Bind(&Scheduler::OnComplete,
-                                                    base::Unretained(this)));
-    }
+    task_runner()->PostTask(
+        base::BindOnce(&Scheduler::OnComplete, base::Unretained(this)));
   }
 }
 
@@ -189,13 +171,13 @@
 void Scheduler::FailWithErrorOnMainThread(const Err& err) {
   if (!suppress_output_for_testing_)
     err.PrintToStdout();
-  runner_.Quit();
+  task_runner()->PostQuit();
 }
 
 void Scheduler::OnComplete() {
   // Should be called on the main thread.
-  DCHECK(task_runner()->BelongsToCurrentThread());
-  runner_.Quit();
+  DCHECK(task_runner() == MsgLoop::Current());
+  task_runner()->PostQuit();
 }
 
 void Scheduler::WaitForPoolTasks() {
diff --git a/tools/gn/scheduler.h b/tools/gn/scheduler.h
index e37be30..a7af3d4 100644
--- a/tools/gn/scheduler.h
+++ b/tools/gn/scheduler.h
@@ -10,10 +10,10 @@
 #include "base/atomic_ref_count.h"
 #include "base/files/file_path.h"
 #include "base/macros.h"
-#include "base/run_loop.h"
-#include "base/single_thread_task_runner.h"
 #include "base/synchronization/condition_variable.h"
 #include "base/synchronization/lock.h"
+#include "msg_loop.h"
+#include "task.h"
 #include "tools/gn/input_file_manager.h"
 #include "tools/gn/label.h"
 #include "tools/gn/source_file.h"
@@ -30,8 +30,9 @@
 
   bool Run();
 
-  scoped_refptr<base::SingleThreadTaskRunner> task_runner() {
-    return main_thread_task_runner_;
+  MsgLoop* task_runner() {
+    DCHECK(main_thread_run_loop_);
+    return main_thread_run_loop_;
   }
 
   InputFileManager* input_file_manager() { return input_file_manager_.get(); }
@@ -45,7 +46,7 @@
   void Log(const std::string& verb, const std::string& msg);
   void FailWithError(const Err& err);
 
-  void ScheduleWork(std::function<void()> work);
+  void ScheduleWork(Task work);
 
   void Shutdown();
 
@@ -104,13 +105,10 @@
   // Waits for tasks scheduled via ScheduleWork() to complete their execution.
   void WaitForPoolTasks();
 
-  // TaskRunner for the thread on which the Scheduler is initialized.
-  const scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_;
+  MsgLoop* main_thread_run_loop_;
 
   scoped_refptr<InputFileManager> input_file_manager_;
 
-  base::RunLoop runner_;
-
   bool verbose_logging_;
 
   base::AtomicRefCount work_count_;
diff --git a/tools/gn/scope.h b/tools/gn/scope.h
index 9e683d2..1ae120f 100644
--- a/tools/gn/scope.h
+++ b/tools/gn/scope.h
@@ -10,8 +10,8 @@
 #include <set>
 #include <utility>
 #include <vector>
+#include <unordered_map>
 
-#include "base/containers/hash_tables.h"
 #include "base/macros.h"
 #include "base/memory/ref_counted.h"
 #include "tools/gn/err.h"
@@ -38,7 +38,7 @@
 // variables. So you should use a non-const containing scope whenever possible.
 class Scope {
  public:
-  typedef base::hash_map<base::StringPiece, Value, base::StringPieceHash>
+  typedef std::unordered_map<base::StringPiece, Value, base::StringPieceHash>
       KeyValueMap;
   // Holds an owning list of Items.
   typedef std::vector<std::unique_ptr<Item>> ItemVector;
@@ -338,7 +338,7 @@
     Value value;
   };
 
-  typedef base::hash_map<base::StringPiece, Record, base::StringPieceHash>
+  typedef std::unordered_map<base::StringPiece, Record, base::StringPieceHash>
       RecordMap;
 
   void AddProvider(ProgrammaticProvider* p);
@@ -367,7 +367,7 @@
 
   // Note that this can't use string pieces since the names are constructed from
   // Values which might be deallocated before this goes out of scope.
-  typedef base::hash_map<std::string, std::unique_ptr<Scope>> NamedScopeMap;
+  typedef std::unordered_map<std::string, std::unique_ptr<Scope>> NamedScopeMap;
   NamedScopeMap target_defaults_;
 
   // Null indicates not set and that we should fallback to the containing
diff --git a/tools/gn/setup.cc b/tools/gn/setup.cc
index 69def2e..8a66259 100644
--- a/tools/gn/setup.cc
+++ b/tools/gn/setup.cc
@@ -17,7 +17,6 @@
 #include "base/files/file_util.h"
 #include "base/memory/ref_counted.h"
 #include "base/process/launch.h"
-#include "base/single_thread_task_runner.h"
 #include "base/strings/string_split.h"
 #include "base/strings/string_util.h"
 #include "base/strings/sys_string_conversions.h"
@@ -163,20 +162,10 @@
   return FindDotFile(up_one_dir);
 }
 
-void ForwardItemDefinedToBuilderInMainThread(
-    Builder* builder_call_on_main_thread_only,
-    std::unique_ptr<Item> item) {
-  builder_call_on_main_thread_only->ItemDefined(std::move(item));
-
-  // Pair to the Increment in ItemDefinedCallback.
-  g_scheduler->DecrementWorkCount();
-}
-
 // Called on any thread. Post the item to the builder on the main thread.
-void ItemDefinedCallback(
-    scoped_refptr<base::SingleThreadTaskRunner> task_runner,
-    Builder* builder_call_on_main_thread_only,
-    std::unique_ptr<Item> item) {
+void ItemDefinedCallback(MsgLoop* task_runner,
+                         Builder* builder_call_on_main_thread_only,
+                         std::unique_ptr<Item> item) {
   DCHECK(item);
 
   // Increment the work count for the duration of defining the item with the
@@ -185,11 +174,13 @@
   // this call completing on the main thread, the 'Complete' function will
   // be signaled and we'll stop running with an incomplete build.
   g_scheduler->IncrementWorkCount();
-  task_runner->PostTask(
-      FROM_HERE,
-      base::Bind(&ForwardItemDefinedToBuilderInMainThread,
-                 base::Unretained(builder_call_on_main_thread_only),
-                 base::Passed(&item)));
+  task_runner->PostTask(base::BindOnce(
+      [](Builder* builder_call_on_main_thread_only,
+         std::unique_ptr<Item> item) {
+        builder_call_on_main_thread_only->ItemDefined(std::move(item));
+        g_scheduler->DecrementWorkCount();
+      },
+      builder_call_on_main_thread_only, base::Passed(&item)));
 }
 
 void DecrementWorkCount() {
diff --git a/tools/gn/source_dir.h b/tools/gn/source_dir.h
index 142285c..8b407b5 100644
--- a/tools/gn/source_dir.h
+++ b/tools/gn/source_dir.h
@@ -10,7 +10,6 @@
 #include <algorithm>
 #include <string>
 
-#include "base/containers/hash_tables.h"
 #include "base/files/file_path.h"
 #include "base/logging.h"
 #include "base/strings/string_piece.h"
@@ -145,7 +144,7 @@
   // Copy & assign supported.
 };
 
-namespace BASE_HASH_NAMESPACE {
+namespace std {
 
 template<> struct hash<SourceDir> {
   std::size_t operator()(const SourceDir& v) const {
@@ -154,7 +153,7 @@
   }
 };
 
-}  // namespace BASE_HASH_NAMESPACE
+}  // namespace std
 
 inline void swap(SourceDir& lhs, SourceDir& rhs) {
   lhs.swap(rhs);
diff --git a/tools/gn/source_file.h b/tools/gn/source_file.h
index 06bbd11..a7a08e6 100644
--- a/tools/gn/source_file.h
+++ b/tools/gn/source_file.h
@@ -10,7 +10,6 @@
 #include <algorithm>
 #include <string>
 
-#include "base/containers/hash_tables.h"
 #include "base/files/file_path.h"
 #include "base/logging.h"
 #include "base/strings/string_piece.h"
@@ -91,7 +90,7 @@
   // Copy & assign supported.
 };
 
-namespace BASE_HASH_NAMESPACE {
+namespace std {
 
 template<> struct hash<SourceFile> {
   std::size_t operator()(const SourceFile& v) const {
@@ -100,7 +99,7 @@
   }
 };
 
-}  // namespace BASE_HASH_NAMESPACE
+}  // namespace std
 
 inline void swap(SourceFile& lhs, SourceFile& rhs) {
   lhs.swap(rhs);
diff --git a/tools/gn/test_with_scheduler.h b/tools/gn/test_with_scheduler.h
index 07e3713..010b834 100644
--- a/tools/gn/test_with_scheduler.h
+++ b/tools/gn/test_with_scheduler.h
@@ -6,7 +6,7 @@
 #define TOOLS_GN_TEST_WITH_SCHEDULER_H_
 
 #include "base/macros.h"
-#include "base/test/scoped_task_environment.h"
+#include "msg_loop.h"
 #include "test/test.h"
 #include "tools/gn/scheduler.h"
 
@@ -18,7 +18,7 @@
   Scheduler& scheduler() { return scheduler_; }
 
  private:
-  base::test::ScopedTaskEnvironment scoped_task_environment_;
+  MsgLoop run_loop_;
   Scheduler scheduler_;
 
   DISALLOW_COPY_AND_ASSIGN(TestWithScheduler);
diff --git a/tools/gn/unique_vector.h b/tools/gn/unique_vector.h
index e629ce2..7288762 100644
--- a/tools/gn/unique_vector.h
+++ b/tools/gn/unique_vector.h
@@ -8,8 +8,7 @@
 #include <stddef.h>
 
 #include <algorithm>
-
-#include "base/containers/hash_tables.h"
+#include <unordered_set>
 
 namespace internal {
 
@@ -65,7 +64,7 @@
 
  private:
   void FillHashValue() {
-    BASE_HASH_NAMESPACE::hash<T> h;
+    std::hash<T> h;
     hash_val_ = h(value());
   }
 
@@ -91,7 +90,7 @@
 
 }  // namespace internal
 
-namespace BASE_HASH_NAMESPACE {
+namespace std {
 
 template<typename T> struct hash< internal::UniquifyRef<T> > {
   std::size_t operator()(const internal::UniquifyRef<T>& v) const {
@@ -99,7 +98,7 @@
   }
 };
 
-}  // namespace BASE_HASH_NAMESPACE
+}  // namespace std
 
 // An ordered set optimized for GN's usage. Such sets are used to store lists
 // of configs and libraries, and are appended to but not randomly inserted
@@ -169,7 +168,7 @@
 
  private:
   typedef internal::UniquifyRef<T> Ref;
-  typedef base::hash_set<Ref> HashSet;
+  typedef std::unordered_set<Ref> HashSet;
 
   HashSet set_;
   Vector vector_;
diff --git a/tools/gn/visual_studio_utils_unittest.cc b/tools/gn/visual_studio_utils_unittest.cc
index cda32e3..f915158 100644
--- a/tools/gn/visual_studio_utils_unittest.cc
+++ b/tools/gn/visual_studio_utils_unittest.cc
@@ -4,7 +4,6 @@
 
 #include "tools/gn/visual_studio_utils.h"
 
-#include "base/location.h"
 #include "base/strings/string_util.h"
 #include "test/test.h"