Remove base/synchronization/, move src/ to util/
Moving src/ to util/ (and removing src/ from include path) was necessary
so that Semaphore could live in "util/semaphore.h" rather than having a
different name (because <semaphore.h> is where sem_t is on Linux).
Unfortunately this required touching ~everything because build_config.h
needed to be changed to util/build_config.h.
Change-Id: I4c913542c1f1504dca1c82e6ab6d99ef263f5cac
Reviewed-on: https://gn-review.googlesource.com/1680
Commit-Queue: Scott Graham <scottmg@chromium.org>
Reviewed-by: Brett Wilson <brettw@chromium.org>
diff --git a/base/bind_internal.h b/base/bind_internal.h
index ffe9ed7..0dc59e6 100644
--- a/base/bind_internal.h
+++ b/base/bind_internal.h
@@ -14,7 +14,7 @@
#include "base/memory/raw_scoped_refptr_mismatch_checker.h"
#include "base/memory/weak_ptr.h"
#include "base/template_util.h"
-#include "build_config.h"
+#include "util/build_config.h"
// See base/callback.h for user documentation.
//
diff --git a/base/bit_cast.h b/base/bit_cast.h
index 213dcc5..30a44c5 100644
--- a/base/bit_cast.h
+++ b/base/bit_cast.h
@@ -10,7 +10,7 @@
#include "base/compiler_specific.h"
#include "base/template_util.h"
-#include "build_config.h"
+#include "util/build_config.h"
// bit_cast<Dest,Source> is a template function that implements the equivalent
// of "*reinterpret_cast<Dest*>(&source)". We need this in very low-level
diff --git a/base/callback.h b/base/callback.h
index 00675be..1b84f40 100644
--- a/base/callback.h
+++ b/base/callback.h
@@ -78,7 +78,7 @@
bool Equals(const OnceCallback& other) const { return EqualsInternal(other); }
- R Run(Args... args) const & {
+ R Run(Args... args) const& {
static_assert(!sizeof(*this),
"OnceCallback::Run() may only be invoked on a non-const "
"rvalue, i.e. std::move(callback).Run().");
@@ -119,7 +119,7 @@
return EqualsInternal(other);
}
- R Run(Args... args) const & {
+ R Run(Args... args) const& {
PolymorphicInvoke f =
reinterpret_cast<PolymorphicInvoke>(this->polymorphic_invoke());
return f(this->bind_state_.get(), std::forward<Args>(args)...);
diff --git a/base/command_line.cc b/base/command_line.cc
index a49ca71..67204f0 100644
--- a/base/command_line.cc
+++ b/base/command_line.cc
@@ -15,7 +15,7 @@
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
diff --git a/base/command_line.h b/base/command_line.h
index 7530d66..265fe96 100644
--- a/base/command_line.h
+++ b/base/command_line.h
@@ -22,7 +22,7 @@
#include "base/strings/string16.h"
#include "base/strings/string_piece.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/compiler_specific.h b/base/compiler_specific.h
index b548aa6..4224197 100644
--- a/base/compiler_specific.h
+++ b/base/compiler_specific.h
@@ -5,7 +5,7 @@
#ifndef BASE_COMPILER_SPECIFIC_H_
#define BASE_COMPILER_SPECIFIC_H_
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(COMPILER_MSVC)
diff --git a/base/environment.cc b/base/environment.cc
index 19bc20e..7f0e5d9 100644
--- a/base/environment.cc
+++ b/base/environment.cc
@@ -12,7 +12,7 @@
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
@@ -216,7 +216,7 @@
size_t pointer_count_required =
result_indices.size() + 1 + // Null-terminated array of pointers.
(value_storage.size() + sizeof(char*) - 1) / sizeof(char*); // Buffer.
- std::unique_ptr<char* []> result(new char*[pointer_count_required]);
+ std::unique_ptr<char*[]> result(new char*[pointer_count_required]);
// The string storage goes after the array of pointers.
char* storage_data =
diff --git a/base/environment.h b/base/environment.h
index 135e3c8..82af987 100644
--- a/base/environment.h
+++ b/base/environment.h
@@ -11,7 +11,7 @@
#include "base/strings/string16.h"
#include "base/strings/string_piece.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
@@ -76,8 +76,8 @@
// returned array will have appended to it the storage for the array itself so
// there is only one pointer to manage, but this means that you can't copy the
// array without keeping the original around.
-std::unique_ptr<char* []> AlterEnvironment(const char* const* env,
- const EnvironmentMap& changes);
+std::unique_ptr<char*[]> AlterEnvironment(const char* const* env,
+ const EnvironmentMap& changes);
#endif
diff --git a/base/files/file.cc b/base/files/file.cc
index 8bc4fdb..98fa3a6 100644
--- a/base/files/file.cc
+++ b/base/files/file.cc
@@ -4,7 +4,7 @@
#include "base/files/file.h"
#include "base/files/file_path.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_POSIX) || defined(OS_FUCHSIA)
#include <errno.h>
diff --git a/base/files/file.h b/base/files/file.h
index 49a2cb4..e000636 100644
--- a/base/files/file.h
+++ b/base/files/file.h
@@ -14,7 +14,7 @@
#include "base/files/scoped_file.h"
#include "base/macros.h"
#include "base/time/time.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_POSIX) || defined(OS_FUCHSIA)
#include <sys/stat.h>
diff --git a/base/files/file_enumerator.h b/base/files/file_enumerator.h
index 905871d..edd5036 100644
--- a/base/files/file_enumerator.h
+++ b/base/files/file_enumerator.h
@@ -14,7 +14,7 @@
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/time/time.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
diff --git a/base/files/file_enumerator_posix.cc b/base/files/file_enumerator_posix.cc
index a1a93d2..003f045 100644
--- a/base/files/file_enumerator_posix.cc
+++ b/base/files/file_enumerator_posix.cc
@@ -11,7 +11,7 @@
#include <string.h>
#include "base/logging.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
namespace {
diff --git a/base/files/file_path.cc b/base/files/file_path.cc
index fbda54c..a66c8cc 100644
--- a/base/files/file_path.cc
+++ b/base/files/file_path.cc
@@ -13,7 +13,7 @@
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_MACOSX)
#include "base/mac/scoped_cftyperef.h"
diff --git a/base/files/file_path.h b/base/files/file_path.h
index f7a815e..1717cba 100644
--- a/base/files/file_path.h
+++ b/base/files/file_path.h
@@ -112,7 +112,7 @@
#include "base/macros.h"
#include "base/strings/string16.h"
#include "base/strings/string_piece.h"
-#include "build_config.h"
+#include "util/build_config.h"
// Windows-style drive letter support and pathname separator characters can be
// enabled and disabled independently, to aid testing. These #defines are
diff --git a/base/files/file_posix.cc b/base/files/file_posix.cc
index fcc10c6..c4f1080 100644
--- a/base/files/file_posix.cc
+++ b/base/files/file_posix.cc
@@ -13,7 +13,7 @@
#include "base/logging.h"
#include "base/posix/eintr_wrapper.h"
#include "base/strings/utf_string_conversions.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/files/file_util.cc b/base/files/file_util.cc
index b30057e..674dd27 100644
--- a/base/files/file_util.cc
+++ b/base/files/file_util.cc
@@ -19,7 +19,7 @@
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/files/file_util.h b/base/files/file_util.h
index 6176073..90f9cd6 100644
--- a/base/files/file_util.h
+++ b/base/files/file_util.h
@@ -24,7 +24,7 @@
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/strings/string16.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_WIN)
#include "base/win/windows_types.h"
diff --git a/base/files/file_util_posix.cc b/base/files/file_util_posix.cc
index 83cace9..4c1360f 100644
--- a/base/files/file_util_posix.cc
+++ b/base/files/file_util_posix.cc
@@ -37,7 +37,7 @@
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_MACOSX)
#include <AvailabilityMacros.h>
diff --git a/base/files/platform_file.h b/base/files/platform_file.h
index 59bb6fe..cba2fc8 100644
--- a/base/files/platform_file.h
+++ b/base/files/platform_file.h
@@ -6,7 +6,7 @@
#define BASE_FILES_PLATFORM_FILE_H_
#include "base/files/scoped_file.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_WIN)
#include "base/win/scoped_handle.h"
@@ -38,6 +38,6 @@
#endif
-} // namespace
+} // namespace base
#endif // BASE_FILES_PLATFORM_FILE_H_
diff --git a/base/files/scoped_file.cc b/base/files/scoped_file.cc
index f73e1c8..11afedd 100644
--- a/base/files/scoped_file.cc
+++ b/base/files/scoped_file.cc
@@ -5,7 +5,7 @@
#include "base/files/scoped_file.h"
#include "base/logging.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_POSIX) || defined(OS_FUCHSIA)
#include <errno.h>
diff --git a/base/files/scoped_file.h b/base/files/scoped_file.h
index f262f18..0d89650 100644
--- a/base/files/scoped_file.h
+++ b/base/files/scoped_file.h
@@ -11,7 +11,7 @@
#include "base/logging.h"
#include "base/scoped_generic.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/json/json_file_value_serializer.cc b/base/json/json_file_value_serializer.cc
index ac3ba7b..f87019d 100644
--- a/base/json/json_file_value_serializer.cc
+++ b/base/json/json_file_value_serializer.cc
@@ -7,7 +7,7 @@
#include "base/files/file_util.h"
#include "base/json/json_string_value_serializer.h"
#include "base/logging.h"
-#include "build_config.h"
+#include "util/build_config.h"
using base::FilePath;
diff --git a/base/json/json_writer.cc b/base/json/json_writer.cc
index 76035db..656a87c 100644
--- a/base/json/json_writer.cc
+++ b/base/json/json_writer.cc
@@ -14,7 +14,7 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/logging.cc b/base/logging.cc
index f6de944..f0ce6f5 100644
--- a/base/logging.cc
+++ b/base/logging.cc
@@ -8,44 +8,16 @@
#include <stdint.h>
#include "base/macros.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_WIN)
#include <io.h>
#include <windows.h>
-typedef HANDLE FileHandle;
-typedef HANDLE MutexHandle;
// Windows warns on using write(). It prefers _write().
#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
// Windows doesn't define STDERR_FILENO. Define it here.
#define STDERR_FILENO 2
-#elif defined(OS_MACOSX)
-// In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated
-// in favor of OS_LOG (Unified Logging).
-#include <AvailabilityMacros.h>
-#if defined(OS_IOS)
-#if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
-#define USE_ASL
-#endif
-#else // !defined(OS_IOS)
-#if !defined(MAC_OS_X_VERSION_10_12) || \
- MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
-#define USE_ASL
-#endif
-#endif // defined(OS_IOS)
-
-#if defined(USE_ASL)
-#include <asl.h>
-#else
-#include <os/log.h>
-#endif
-
-#include <CoreFoundation/CoreFoundation.h>
-#include <mach-o/dyld.h>
-#include <mach/mach.h>
-#include <mach/mach_time.h>
-
#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
#include <time.h>
#endif
@@ -59,9 +31,6 @@
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
-#define MAX_PATH PATH_MAX
-typedef FILE* FileHandle;
-typedef pthread_mutex_t* MutexHandle;
#endif
#include <algorithm>
@@ -80,7 +49,6 @@
#include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/synchronization/lock_impl.h"
#include "base/threading/platform_thread.h"
#if defined(OS_POSIX) || defined(OS_FUCHSIA)
@@ -103,238 +71,9 @@
int g_min_log_level = 0;
-LoggingDestination g_logging_destination = LOG_DEFAULT;
-
// For LOG_ERROR and above, always print to stderr.
const int kAlwaysPrintErrorLevel = LOG_ERROR;
-// Which log file to use? This is initialized by InitLogging or
-// will be lazily initialized to the default value when it is
-// first needed.
-#if defined(OS_WIN)
-typedef std::wstring PathString;
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
-typedef std::string PathString;
-#endif
-PathString* g_log_file_name = nullptr;
-
-// This file is lazily opened and the handle may be nullptr
-FileHandle g_log_file = nullptr;
-
-// What should be prepended to each message?
-bool g_log_process_id = false;
-bool g_log_thread_id = false;
-bool g_log_timestamp = true;
-bool g_log_tickcount = false;
-
-// Should we pop up fatal debug messages in a dialog?
-bool show_error_dialogs = false;
-
-// A log message handler that gets notified of every log message we process.
-LogMessageHandlerFunction log_message_handler = nullptr;
-
-// Helper functions to wrap platform differences.
-
-int32_t CurrentProcessId() {
-#if defined(OS_WIN)
- return GetCurrentProcessId();
-#elif defined(OS_POSIX)
- return getpid();
-#endif
-}
-
-uint64_t TickCount() {
-#if defined(OS_WIN)
- return GetTickCount();
-#elif defined(OS_MACOSX)
- return mach_absolute_time();
-#elif defined(OS_POSIX)
- struct timespec ts;
- clock_gettime(CLOCK_MONOTONIC, &ts);
-
- uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
- static_cast<int64_t>(ts.tv_nsec) / 1000;
-
- return absolute_micro;
-#endif
-}
-
-void DeleteFilePath(const PathString& log_name) {
-#if defined(OS_WIN)
- DeleteFile(log_name.c_str());
-#elif defined(OS_POSIX)
- unlink(log_name.c_str());
-#else
-#error Unsupported platform
-#endif
-}
-
-PathString GetDefaultLogFile() {
-#if defined(OS_WIN)
- // On Windows we use the same path as the exe.
- wchar_t module_name[MAX_PATH];
- GetModuleFileName(nullptr, module_name, MAX_PATH);
-
- PathString log_name = module_name;
- PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
- if (last_backslash != PathString::npos)
- log_name.erase(last_backslash + 1);
- log_name += L"debug.log";
- return log_name;
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
- // On other platforms we just use the current directory.
- return PathString("debug.log");
-#endif
-}
-
-// We don't need locks on Windows for atomically appending to files. The OS
-// provides this functionality.
-#if defined(OS_POSIX) || defined(OS_FUCHSIA)
-// This class acts as a wrapper for locking the logging files.
-// LoggingLock::Init() should be called from the main thread before any logging
-// is done. Then whenever logging, be sure to have a local LoggingLock
-// instance on the stack. This will ensure that the lock is unlocked upon
-// exiting the frame.
-// LoggingLocks can not be nested.
-class LoggingLock {
- public:
- LoggingLock() { LockLogging(); }
-
- ~LoggingLock() { UnlockLogging(); }
-
- static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
- if (initialized)
- return;
- lock_log_file = lock_log;
-
- if (lock_log_file != LOCK_LOG_FILE)
- log_lock = new base::internal::LockImpl();
-
- initialized = true;
- }
-
- private:
- static void LockLogging() {
- if (lock_log_file == LOCK_LOG_FILE) {
- pthread_mutex_lock(&log_mutex);
- } else {
- // use the lock
- log_lock->Lock();
- }
- }
-
- static void UnlockLogging() {
- if (lock_log_file == LOCK_LOG_FILE) {
- pthread_mutex_unlock(&log_mutex);
- } else {
- log_lock->Unlock();
- }
- }
-
- // The lock is used if log file locking is false. It helps us avoid problems
- // with multiple threads writing to the log file at the same time. Use
- // LockImpl directly instead of using Lock, because Lock makes logging calls.
- static base::internal::LockImpl* log_lock;
-
- // When we don't use a lock, we are using a global mutex. We need to do this
- // because LockFileEx is not thread safe.
- static pthread_mutex_t log_mutex;
-
- static bool initialized;
- static LogLockingState lock_log_file;
-};
-
-// static
-bool LoggingLock::initialized = false;
-// static
-base::internal::LockImpl* LoggingLock::log_lock = nullptr;
-// static
-LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
-
-pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
-
-#endif // OS_POSIX || OS_FUCHSIA
-
-// Called by logging functions to ensure that |g_log_file| is initialized
-// and can be used for writing. Returns false if the file could not be
-// initialized. |g_log_file| will be nullptr in this case.
-bool InitializeLogFileHandle() {
- if (g_log_file)
- return true;
-
- if (!g_log_file_name) {
- // Nobody has called InitLogging to specify a debug log file, so here we
- // initialize the log file name to a default.
- g_log_file_name = new PathString(GetDefaultLogFile());
- }
-
- if ((g_logging_destination & LOG_TO_FILE) != 0) {
-#if defined(OS_WIN)
- // The FILE_APPEND_DATA access mask ensures that the file is atomically
- // appended to across accesses from multiple threads.
- // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
- // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
- g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
- FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
- OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
- if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
- // We are intentionally not using FilePath or FileUtil here to reduce the
- // dependencies of the logging implementation. For e.g. FilePath and
- // FileUtil depend on shell32 and user32.dll. This is not acceptable for
- // some consumers of base logging like chrome_elf, etc.
- // Please don't change the code below to use FilePath.
- // try the current directory
- wchar_t system_buffer[MAX_PATH];
- system_buffer[0] = 0;
- DWORD len =
- ::GetCurrentDirectory(arraysize(system_buffer), system_buffer);
- if (len == 0 || len > arraysize(system_buffer))
- return false;
-
- *g_log_file_name = system_buffer;
- // Append a trailing backslash if needed.
- if (g_log_file_name->back() != L'\\')
- *g_log_file_name += L"\\";
- *g_log_file_name += L"debug.log";
-
- g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
- FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
- OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
- if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
- g_log_file = nullptr;
- return false;
- }
- }
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
- g_log_file = fopen(g_log_file_name->c_str(), "a");
- if (g_log_file == nullptr)
- return false;
-#else
-#error Unsupported platform
-#endif
- }
-
- return true;
-}
-
-void CloseFile(FileHandle log) {
-#if defined(OS_WIN)
- CloseHandle(log);
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
- fclose(log);
-#else
-#error Unsupported platform
-#endif
-}
-
-void CloseLogFileUnlocked() {
- if (!g_log_file)
- return;
-
- CloseFile(g_log_file);
- g_log_file = nullptr;
-}
-
} // namespace
#if DCHECK_IS_CONFIGURABLE
@@ -349,37 +88,6 @@
// operator.
std::ostream* g_swallow_stream;
-LoggingSettings::LoggingSettings()
- : logging_dest(LOG_DEFAULT),
- log_file(nullptr),
- lock_log(LOCK_LOG_FILE),
- delete_old(APPEND_TO_OLD_LOG_FILE) {}
-
-bool BaseInitLoggingImpl(const LoggingSettings& settings) {
- g_logging_destination = settings.logging_dest;
-
- // ignore file options unless logging to file is set.
- if ((g_logging_destination & LOG_TO_FILE) == 0)
- return true;
-
-#if defined(OS_POSIX) || defined(OS_FUCHSIA)
- LoggingLock::Init(settings.lock_log, settings.log_file);
- LoggingLock logging_lock;
-#endif
-
- // Calling InitLogging twice or after some log call has already opened the
- // default log file will re-initialize to the new options.
- CloseLogFileUnlocked();
-
- if (!g_log_file_name)
- g_log_file_name = new PathString();
- *g_log_file_name = settings.log_file;
- if (settings.delete_old == DELETE_OLD_LOG_FILE)
- DeleteFilePath(*g_log_file_name);
-
- return InitializeLogFileHandle();
-}
-
void SetMinLogLevel(int level) {
g_min_log_level = std::min(LOG_FATAL, level);
}
@@ -395,30 +103,7 @@
// Return true here unless we know ~LogMessage won't do anything. Note that
// ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
// when g_logging_destination is LOG_NONE.
- return g_logging_destination != LOG_NONE || log_message_handler ||
- severity >= kAlwaysPrintErrorLevel;
-}
-
-void SetLogItems(bool enable_process_id,
- bool enable_thread_id,
- bool enable_timestamp,
- bool enable_tickcount) {
- g_log_process_id = enable_process_id;
- g_log_thread_id = enable_thread_id;
- g_log_timestamp = enable_timestamp;
- g_log_tickcount = enable_tickcount;
-}
-
-void SetShowErrorDialogs(bool enable_dialogs) {
- show_error_dialogs = enable_dialogs;
-}
-
-void SetLogMessageHandler(LogMessageHandlerFunction handler) {
- log_message_handler = handler;
-}
-
-LogMessageHandlerFunction GetLogMessageHandler() {
- return log_message_handler;
+ return severity >= kAlwaysPrintErrorLevel;
}
// Explicit instantiations for commonly used comparisons.
@@ -446,28 +131,6 @@
(*os) << "nullptr";
}
-#if !defined(NDEBUG)
-// Displays a message box to the user with the error message in it.
-// Used for fatal messages, where we close the app simultaneously.
-// This is for developers only; we don't use this in circumstances
-// (like release builds) where users could see it, since users don't
-// understand these messages anyway.
-void DisplayDebugMessageInDialog(const std::string& str) {
- if (str.empty())
- return;
-
- if (!show_error_dialogs)
- return;
-
-#if defined(OS_WIN)
- // We intentionally don't implement a dialog on other platforms.
- // You can just look at stderr.
- MessageBoxW(nullptr, base::UTF8ToUTF16(str).c_str(), L"Fatal error",
- MB_OK | MB_ICONHAND | MB_TOPMOST);
-#endif // defined(OS_WIN)
-}
-#endif // !defined(NDEBUG)
-
#if defined(OS_WIN)
LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {}
@@ -505,224 +168,19 @@
}
LogMessage::~LogMessage() {
-#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
- !defined(OS_AIX)
if (severity_ == LOG_FATAL) {
stream_ << std::endl; // Newline to separate from log message.
}
-#endif
stream_ << std::endl;
std::string str_newline(stream_.str());
- // Give any log message handler first dibs on the message.
- if (log_message_handler && log_message_handler(severity_, file_, line_,
- message_start_, str_newline)) {
- // The handler took care of it, no further processing.
- return;
- }
-
- if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
#if defined(OS_WIN)
- OutputDebugStringA(str_newline.c_str());
-#elif defined(OS_MACOSX)
- // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
- // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
- // its successor OS_LOG. If there's something weird about stderr, assume
- // that log messages are going nowhere and log via ASL/OS_LOG too.
- // Messages logged via ASL/OS_LOG show up in Console.app.
- //
- // Programs started by launchd, as UI applications normally are, have had
- // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
- // a pipe to launchd, which logged what it received (see log_redirect_fd in
- // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
- //
- // Another alternative would be to determine whether stderr is a pipe to
- // launchd and avoid logging via ASL only in that case. See 10.7.5
- // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
- // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
- // to the system log at all.
- //
- // Note that the ASL client by default discards messages whose levels are
- // below ASL_LEVEL_NOTICE. It's possible to change that with
- // asl_set_filter(), but this is pointless because syslogd normally applies
- // the same filter.
- const bool log_to_system = []() {
- struct stat stderr_stat;
- if (fstat(fileno(stderr), &stderr_stat) == -1) {
- return true;
- }
- if (!S_ISCHR(stderr_stat.st_mode)) {
- return false;
- }
-
- struct stat dev_null_stat;
- if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
- return true;
- }
-
- return !S_ISCHR(dev_null_stat.st_mode) ||
- stderr_stat.st_rdev == dev_null_stat.st_rdev;
- }();
-
- if (log_to_system) {
- // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
- // CF-1153.18/CFUtilities.c __CFLogCString().
- CFBundleRef main_bundle = CFBundleGetMainBundle();
- CFStringRef main_bundle_id_cf =
- main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
- std::string main_bundle_id =
- main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
- : std::string("");
-#if defined(USE_ASL)
- // The facility is set to the main bundle ID if available. Otherwise,
- // "com.apple.console" is used.
- const class ASLClient {
- public:
- explicit ASLClient(const std::string& facility)
- : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
- ~ASLClient() { asl_close(client_); }
-
- aslclient get() const { return client_; }
-
- private:
- aslclient client_;
- DISALLOW_COPY_AND_ASSIGN(ASLClient);
- } asl_client(main_bundle_id.empty() ? main_bundle_id
- : "com.apple.console");
-
- const class ASLMessage {
- public:
- ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
- ~ASLMessage() { asl_free(message_); }
-
- aslmsg get() const { return message_; }
-
- private:
- aslmsg message_;
- DISALLOW_COPY_AND_ASSIGN(ASLMessage);
- } asl_message;
-
- // By default, messages are only readable by the admin group. Explicitly
- // make them readable by the user generating the messages.
- char euid_string[12];
- snprintf(euid_string, arraysize(euid_string), "%d", geteuid());
- asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
-
- // Map Chrome log severities to ASL log levels.
- const char* const asl_level_string = [](LogSeverity severity) {
-// ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
-// non-obvious two-step macro trick achieves what's needed.
-// https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
-#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
-#define ASL_LEVEL_STR_X(level) #level
- switch (severity) {
- case LOG_INFO:
- return ASL_LEVEL_STR(ASL_LEVEL_INFO);
- case LOG_WARNING:
- return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
- case LOG_ERROR:
- return ASL_LEVEL_STR(ASL_LEVEL_ERR);
- case LOG_FATAL:
- return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
- default:
- return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
- : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
- }
-#undef ASL_LEVEL_STR
-#undef ASL_LEVEL_STR_X
- }(severity_);
- asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
-
- asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
-
- asl_send(asl_client.get(), asl_message.get());
-#else // !defined(USE_ASL)
- const class OSLog {
- public:
- explicit OSLog(const char* subsystem)
- : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
- : OS_LOG_DEFAULT) {}
- ~OSLog() {
- if (os_log_ != OS_LOG_DEFAULT) {
- os_release(os_log_);
- }
- }
- os_log_t get() const { return os_log_; }
-
- private:
- os_log_t os_log_;
- DISALLOW_COPY_AND_ASSIGN(OSLog);
- } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
- const os_log_type_t os_log_type = [](LogSeverity severity) {
- switch (severity) {
- case LOG_INFO:
- return OS_LOG_TYPE_INFO;
- case LOG_WARNING:
- return OS_LOG_TYPE_DEFAULT;
- case LOG_ERROR:
- return OS_LOG_TYPE_ERROR;
- case LOG_FATAL:
- return OS_LOG_TYPE_FAULT;
- default:
- return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
- }
- }(severity_);
- os_log_with_type(log.get(), os_log_type, "%{public}s",
- str_newline.c_str());
-#endif // defined(USE_ASL)
- }
+ OutputDebugStringA(str_newline.c_str());
#endif
- ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
- fflush(stderr);
- } else if (severity_ >= kAlwaysPrintErrorLevel) {
- // When we're only outputting to a log file, above a certain log level, we
- // should still output to stderr so that we can better detect and diagnose
- // problems with unit tests, especially on the buildbots.
- ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
- fflush(stderr);
- }
-
- // write to log file
- if ((g_logging_destination & LOG_TO_FILE) != 0) {
-// We can have multiple threads and/or processes, so try to prevent them
-// from clobbering each other's writes.
-// If the client app did not call InitLogging, and the lock has not
-// been created do it now. We do this on demand, but if two threads try
-// to do this at the same time, there will be a race condition to create
-// the lock. This is why InitLogging should be called from the main
-// thread at the beginning of execution.
-#if defined(OS_POSIX) || defined(OS_FUCHSIA)
- LoggingLock::Init(LOCK_LOG_FILE, nullptr);
- LoggingLock logging_lock;
-#endif
- if (InitializeLogFileHandle()) {
-#if defined(OS_WIN)
- DWORD num_written;
- WriteFile(g_log_file, static_cast<const void*>(str_newline.c_str()),
- static_cast<DWORD>(str_newline.length()), &num_written,
- nullptr);
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
- ignore_result(
- fwrite(str_newline.data(), str_newline.size(), 1, g_log_file));
- fflush(g_log_file);
-#else
-#error Unsupported platform
-#endif
- }
- }
+ ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
+ fflush(stderr);
if (severity_ == LOG_FATAL) {
-// 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());
-#endif
- // Crash the process to generate a dump.
abort();
}
}
@@ -737,37 +195,29 @@
// TODO(darin): It might be nice if the columns were fixed width.
stream_ << '[';
- if (g_log_process_id)
- stream_ << CurrentProcessId() << ':';
- if (g_log_thread_id)
- stream_ << base::PlatformThread::CurrentId() << ':';
- if (g_log_timestamp) {
+ stream_ << base::PlatformThread::CurrentId() << ':';
#if defined(OS_WIN)
- SYSTEMTIME local_time;
- GetLocalTime(&local_time);
- stream_ << std::setfill('0') << std::setw(2) << local_time.wMonth
- << std::setw(2) << local_time.wDay << '/' << std::setw(2)
- << local_time.wHour << std::setw(2) << local_time.wMinute
- << std::setw(2) << local_time.wSecond << '.' << std::setw(3)
- << local_time.wMilliseconds << ':';
+ SYSTEMTIME local_time;
+ GetLocalTime(&local_time);
+ stream_ << std::setfill('0') << std::setw(2) << local_time.wMonth
+ << std::setw(2) << local_time.wDay << '/' << std::setw(2)
+ << local_time.wHour << std::setw(2) << local_time.wMinute
+ << std::setw(2) << local_time.wSecond << '.' << std::setw(3)
+ << local_time.wMilliseconds << ':';
#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
- timeval tv;
- gettimeofday(&tv, nullptr);
- time_t t = tv.tv_sec;
- struct tm local_time;
- localtime_r(&t, &local_time);
- struct tm* tm_time = &local_time;
- stream_ << std::setfill('0') << std::setw(2) << 1 + tm_time->tm_mon
- << std::setw(2) << tm_time->tm_mday << '/' << std::setw(2)
- << tm_time->tm_hour << std::setw(2) << tm_time->tm_min
- << std::setw(2) << tm_time->tm_sec << '.' << std::setw(6)
- << tv.tv_usec << ':';
+ timeval tv;
+ gettimeofday(&tv, nullptr);
+ time_t t = tv.tv_sec;
+ struct tm local_time;
+ localtime_r(&t, &local_time);
+ struct tm* tm_time = &local_time;
+ stream_ << std::setfill('0') << std::setw(2) << 1 + tm_time->tm_mon
+ << std::setw(2) << tm_time->tm_mday << '/' << std::setw(2)
+ << tm_time->tm_hour << std::setw(2) << tm_time->tm_min << std::setw(2)
+ << tm_time->tm_sec << '.' << std::setw(6) << tv.tv_usec << ':';
#else
#error Unsupported platform
#endif
- }
- if (g_log_tickcount)
- stream_ << TickCount() << ':';
if (severity_ >= 0)
stream_ << log_severity_name(severity_);
else
@@ -835,13 +285,6 @@
}
#endif // defined(OS_WIN)
-void CloseLogFile() {
-#if defined(OS_POSIX) || defined(OS_FUCHSIA)
- LoggingLock logging_lock;
-#endif
- CloseLogFileUnlocked();
-}
-
void RawLog(int level, const char* message) {
if (level >= g_min_log_level && message) {
size_t bytes_written = 0;
@@ -875,18 +318,6 @@
// This was defined at the beginning of this file.
#undef write
-#if defined(OS_WIN)
-bool IsLoggingToFileEnabled() {
- return g_logging_destination & LOG_TO_FILE;
-}
-
-std::wstring GetLogFileFullPath() {
- if (g_log_file_name)
- return *g_log_file_name;
- return std::wstring();
-}
-#endif
-
void LogErrorNotReached(const char* file, int line) {
LogMessage(file, line, LOG_ERROR).stream() << "NOTREACHED() hit.";
}
diff --git a/base/logging.h b/base/logging.h
index 3fb3778..2edad38 100644
--- a/base/logging.h
+++ b/base/logging.h
@@ -19,7 +19,7 @@
#include "base/macros.h"
#include "base/strings/string_piece_forward.h"
#include "base/template_util.h"
-#include "build_config.h"
+#include "util/build_config.h"
//
// Optional message capabilities
@@ -103,96 +103,6 @@
namespace logging {
-// TODO(avi): do we want to do a unification of character types here?
-#if defined(OS_WIN)
-typedef wchar_t PathChar;
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
-typedef char PathChar;
-#endif
-
-// Where to record logging output? A flat file and/or system debug log
-// via OutputDebugString.
-enum LoggingDestination {
- LOG_NONE = 0,
- LOG_TO_FILE = 1 << 0,
- LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,
-
- LOG_TO_ALL = LOG_TO_FILE | LOG_TO_SYSTEM_DEBUG_LOG,
-
-// On Windows, use a file next to the exe; on POSIX platforms, where
-// it may not even be possible to locate the executable on disk, use
-// stderr.
-#if defined(OS_WIN)
- LOG_DEFAULT = LOG_TO_FILE,
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
- LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
-#endif
-};
-
-// Indicates that the log file should be locked when being written to.
-// Unless there is only one single-threaded process that is logging to
-// the log file, the file should be locked during writes to make each
-// log output atomic. Other writers will block.
-//
-// All processes writing to the log file must have their locking set for it to
-// work properly. Defaults to LOCK_LOG_FILE.
-enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
-
-// On startup, should we delete or append to an existing log file (if any)?
-// Defaults to APPEND_TO_OLD_LOG_FILE.
-enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
-
-struct LoggingSettings {
- // The defaults values are:
- //
- // logging_dest: LOG_DEFAULT
- // log_file: NULL
- // lock_log: LOCK_LOG_FILE
- // delete_old: APPEND_TO_OLD_LOG_FILE
- LoggingSettings();
-
- LoggingDestination logging_dest;
-
- // The three settings below have an effect only when LOG_TO_FILE is
- // set in |logging_dest|.
- const PathChar* log_file;
- LogLockingState lock_log;
- OldFileDeletionState delete_old;
-};
-
-// Define different names for the BaseInitLoggingImpl() function depending on
-// whether NDEBUG is defined or not so that we'll fail to link if someone tries
-// to compile logging.cc with NDEBUG but includes logging.h without defining it,
-// or vice versa.
-#if defined(NDEBUG)
-#define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
-#else
-#define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
-#endif
-
-// Implementation of the InitLogging() method declared below. We use a
-// more-specific name so we can #define it above without affecting other code
-// that has named stuff "InitLogging".
-bool BaseInitLoggingImpl(const LoggingSettings& settings);
-
-// Sets the log file name and other global logging state. Calling this function
-// is recommended, and is normally done at the beginning of application init.
-// If you don't call it, all the flags will be initialized to their default
-// values, and there is a race condition that may leak a critical section
-// object if two threads try to do the first log at the same time.
-// See the definition of the enums above for descriptions and default values.
-//
-// The default log file is initialized to "debug.log" in the application
-// directory. You probably don't want this, especially since the program
-// directory may not be writable on an enduser's system.
-//
-// This function may be called a second time to re-direct logging (e.g after
-// loging in to a user partition), however it should never be called more than
-// twice.
-inline bool InitLogging(const LoggingSettings& settings) {
- return BaseInitLoggingImpl(settings);
-}
-
// Sets the log level. Anything at or above this level will be written to the
// log file/displayed to the user (if applicable). Anything below this level
// will be silently ignored. The log level defaults to 0 (everything is logged
@@ -205,32 +115,6 @@
// Used by LOG_IS_ON to lazy-evaluate stream arguments.
bool ShouldCreateLogMessage(int severity);
-// Sets the common items you want to be prepended to each log message.
-// process and thread IDs default to off, the timestamp defaults to on.
-// If this function is not called, logging defaults to writing the timestamp
-// only.
-void SetLogItems(bool enable_process_id,
- bool enable_thread_id,
- bool enable_timestamp,
- bool enable_tickcount);
-
-// Sets whether or not you'd like to see fatal debug messages popped up in
-// a dialog box or not.
-// Dialogs are not shown by default.
-void SetShowErrorDialogs(bool enable_dialogs);
-
-// 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
-// should not be sent to other log destinations.
-typedef bool (*LogMessageHandlerFunction)(int severity,
- const char* file,
- int line,
- size_t message_start,
- const std::string& str);
-void SetLogMessageHandler(LogMessageHandlerFunction handler);
-LogMessageHandlerFunction GetLogMessageHandler();
-
// The ANALYZER_ASSUME_TRUE(bool arg) macro adds compiler-specific hints
// to Clang which control what code paths are statically analyzed,
// and is meant to be used in conjunction with assert & assert-like functions.
diff --git a/base/mac/foundation_util.h b/base/mac/foundation_util.h
index c5cead4..6e1ce55 100644
--- a/base/mac/foundation_util.h
+++ b/base/mac/foundation_util.h
@@ -12,7 +12,7 @@
#include "base/logging.h"
#include "base/mac/scoped_cftyperef.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(__OBJC__)
#import <Foundation/Foundation.h>
diff --git a/base/mac/foundation_util.mm b/base/mac/foundation_util.mm
index 1fb91a9..d88ada8 100644
--- a/base/mac/foundation_util.mm
+++ b/base/mac/foundation_util.mm
@@ -15,7 +15,7 @@
#include "base/macros.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/sys_string_conversions.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if !defined(OS_IOS)
#import <AppKit/AppKit.h>
diff --git a/base/mac/mac_logging.h b/base/mac/mac_logging.h
index 9891d69..5ef75f3 100644
--- a/base/mac/mac_logging.h
+++ b/base/mac/mac_logging.h
@@ -7,7 +7,7 @@
#include "base/logging.h"
#include "base/macros.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_IOS)
#include <MacTypes.h>
diff --git a/base/mac/mac_logging.mm b/base/mac/mac_logging.mm
index ff311e3..f7c3052 100644
--- a/base/mac/mac_logging.mm
+++ b/base/mac/mac_logging.mm
@@ -8,7 +8,7 @@
#include <iomanip>
-#include "build_config.h"
+#include "util/build_config.h"
#if !defined(OS_IOS)
#include <CoreServices/CoreServices.h>
diff --git a/base/mac/mach_logging.cc b/base/mac/mach_logging.cc
index b708ded..4237f01 100644
--- a/base/mac/mach_logging.cc
+++ b/base/mac/mach_logging.cc
@@ -8,7 +8,7 @@
#include <string>
#include "base/strings/stringprintf.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if !defined(OS_IOS)
#include <servers/bootstrap.h>
diff --git a/base/mac/mach_logging.h b/base/mac/mach_logging.h
index 1f20b85..a69d7fe 100644
--- a/base/mac/mach_logging.h
+++ b/base/mac/mach_logging.h
@@ -9,7 +9,7 @@
#include "base/logging.h"
#include "base/macros.h"
-#include "build_config.h"
+#include "util/build_config.h"
// Use the MACH_LOG family of macros along with a mach_error_t (kern_return_t)
// containing a Mach error. The error value will be decoded so that logged
diff --git a/base/mac/sdk_forward_declarations.h b/base/mac/sdk_forward_declarations.h
index c00e1f5..5bcb3b3 100644
--- a/base/mac/sdk_forward_declarations.h
+++ b/base/mac/sdk_forward_declarations.h
@@ -266,7 +266,7 @@
@class VNRequest;
typedef void (^VNRequestCompletionHandler)(VNRequest* request, NSError* error);
-@interface VNRequest : NSObject<NSCopying>
+@interface VNRequest : NSObject <NSCopying>
- (instancetype)initWithCompletionHandler:
(VNRequestCompletionHandler)completionHandler NS_DESIGNATED_INITIALIZER;
@property(readonly, nonatomic, copy) NSArray* results;
@@ -276,11 +276,11 @@
@interface VNImageBasedRequest : VNRequest
@end
-@protocol VNFaceObservationAccepting<NSObject>
+@protocol VNFaceObservationAccepting <NSObject>
@end
@interface VNDetectFaceLandmarksRequest
- : VNImageBasedRequest<VNFaceObservationAccepting>
+ : VNImageBasedRequest <VNFaceObservationAccepting>
@end
// VNImageRequestHandler forward declarations.
@@ -310,7 +310,7 @@
@end
// VNFaceObservation forward declarations.
-@interface VNObservation : NSObject<NSCopying, NSSecureCoding>
+@interface VNObservation : NSObject <NSCopying, NSSecureCoding>
@end
@interface VNDetectedObjectObservation : VNObservation
diff --git a/base/macros.h b/base/macros.h
index f59fa6c..321f65b 100644
--- a/base/macros.h
+++ b/base/macros.h
@@ -89,6 +89,6 @@
// work around this bug, wrap the entire expression in this macro...
#define CR_EXPAND_ARG(arg) arg
-} // base
+} // namespace base
#endif // BASE_MACROS_H_
diff --git a/base/memory/ref_counted.h b/base/memory/ref_counted.h
index a897171..8ebdcd6 100644
--- a/base/memory/ref_counted.h
+++ b/base/memory/ref_counted.h
@@ -14,7 +14,7 @@
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
namespace subtle {
diff --git a/base/numerics/checked_math.h b/base/numerics/checked_math.h
index ede3344..433860c 100644
--- a/base/numerics/checked_math.h
+++ b/base/numerics/checked_math.h
@@ -370,23 +370,23 @@
} // namespace internal
+using internal::CheckAdd;
+using internal::CheckAnd;
+using internal::CheckDiv;
using internal::CheckedNumeric;
-using internal::IsValidForType;
-using internal::ValueOrDieForType;
-using internal::ValueOrDefaultForType;
-using internal::MakeCheckedNum;
+using internal::CheckLsh;
using internal::CheckMax;
using internal::CheckMin;
-using internal::CheckAdd;
-using internal::CheckSub;
-using internal::CheckMul;
-using internal::CheckDiv;
using internal::CheckMod;
-using internal::CheckLsh;
-using internal::CheckRsh;
-using internal::CheckAnd;
+using internal::CheckMul;
using internal::CheckOr;
+using internal::CheckRsh;
+using internal::CheckSub;
using internal::CheckXor;
+using internal::IsValidForType;
+using internal::MakeCheckedNum;
+using internal::ValueOrDefaultForType;
+using internal::ValueOrDieForType;
} // namespace base
diff --git a/base/numerics/clamped_math.h b/base/numerics/clamped_math.h
index b184363..9e83543 100644
--- a/base/numerics/clamped_math.h
+++ b/base/numerics/clamped_math.h
@@ -242,20 +242,20 @@
} // namespace internal
+using internal::ClampAdd;
+using internal::ClampAnd;
+using internal::ClampDiv;
using internal::ClampedNumeric;
-using internal::MakeClampedNum;
+using internal::ClampLsh;
using internal::ClampMax;
using internal::ClampMin;
-using internal::ClampAdd;
-using internal::ClampSub;
-using internal::ClampMul;
-using internal::ClampDiv;
using internal::ClampMod;
-using internal::ClampLsh;
-using internal::ClampRsh;
-using internal::ClampAnd;
+using internal::ClampMul;
using internal::ClampOr;
+using internal::ClampRsh;
+using internal::ClampSub;
using internal::ClampXor;
+using internal::MakeClampedNum;
} // namespace base
diff --git a/base/numerics/safe_conversions.h b/base/numerics/safe_conversions.h
index 9284f8f..a4fe387 100644
--- a/base/numerics/safe_conversions.h
+++ b/base/numerics/safe_conversions.h
@@ -327,14 +327,14 @@
using internal::as_signed;
using internal::as_unsigned;
using internal::checked_cast;
-using internal::strict_cast;
-using internal::saturated_cast;
-using internal::SafeUnsignedAbs;
-using internal::StrictNumeric;
-using internal::MakeStrictNum;
-using internal::IsValueInRangeForNumericType;
using internal::IsTypeInRangeForNumericType;
+using internal::IsValueInRangeForNumericType;
using internal::IsValueNegative;
+using internal::MakeStrictNum;
+using internal::SafeUnsignedAbs;
+using internal::saturated_cast;
+using internal::strict_cast;
+using internal::StrictNumeric;
// Explicitly make a shorter size_t alias for convenience.
using SizeT = StrictNumeric<size_t>;
diff --git a/base/numerics/safe_conversions_impl.h b/base/numerics/safe_conversions_impl.h
index 3355b34..8ae6a54 100644
--- a/base/numerics/safe_conversions_impl.h
+++ b/base/numerics/safe_conversions_impl.h
@@ -275,7 +275,8 @@
template <typename Dst,
typename Src,
- template <typename> class Bounds,
+ template <typename>
+ class Bounds,
IntegerRepresentation DstSign = std::is_signed<Dst>::value
? INTEGER_REPRESENTATION_SIGNED
: INTEGER_REPRESENTATION_UNSIGNED,
@@ -293,7 +294,8 @@
// Same sign narrowing: The range is contained for normal limits.
template <typename Dst,
typename Src,
- template <typename> class Bounds,
+ template <typename>
+ class Bounds,
IntegerRepresentation DstSign,
IntegerRepresentation SrcSign>
struct DstRangeRelationToSrcRangeImpl<Dst,
diff --git a/base/optional.h b/base/optional.h
index 14aa4be..931305c 100644
--- a/base/optional.h
+++ b/base/optional.h
@@ -584,7 +584,7 @@
return &storage_.value_;
}
- constexpr const T& operator*() const & {
+ constexpr const T& operator*() const& {
CHECK(storage_.is_populated_);
return storage_.value_;
}
@@ -594,7 +594,7 @@
return storage_.value_;
}
- constexpr const T&& operator*() const && {
+ constexpr const T&& operator*() const&& {
CHECK(storage_.is_populated_);
return std::move(storage_.value_);
}
@@ -613,7 +613,7 @@
return storage_.value_;
}
- constexpr const T& value() const & {
+ constexpr const T& value() const& {
CHECK(storage_.is_populated_);
return storage_.value_;
}
@@ -623,13 +623,13 @@
return std::move(storage_.value_);
}
- constexpr const T&& value() const && {
+ constexpr const T&& value() const&& {
CHECK(storage_.is_populated_);
return std::move(storage_.value_);
}
template <class U>
- constexpr T value_or(U&& default_value) const & {
+ constexpr T value_or(U&& default_value) const& {
// TODO(mlamouri): add the following assert when possible:
// static_assert(std::is_copy_constructible<T>::value,
// "T must be copy constructible");
diff --git a/base/posix/eintr_wrapper.h b/base/posix/eintr_wrapper.h
index 5c24e03..e18372e 100644
--- a/base/posix/eintr_wrapper.h
+++ b/base/posix/eintr_wrapper.h
@@ -17,7 +17,7 @@
#ifndef BASE_POSIX_EINTR_WRAPPER_H_
#define BASE_POSIX_EINTR_WRAPPER_H_
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_POSIX) && !defined(OS_FUCHSIA)
diff --git a/base/posix/safe_strerror.cc b/base/posix/safe_strerror.cc
index 3ae684f..3e3bb15 100644
--- a/base/posix/safe_strerror.cc
+++ b/base/posix/safe_strerror.cc
@@ -16,7 +16,7 @@
#include <stdio.h>
#include <string.h>
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/strings/string16.h b/base/strings/string16.h
index e79aee8..59bf6d7 100644
--- a/base/strings/string16.h
+++ b/base/strings/string16.h
@@ -33,7 +33,7 @@
#include <functional>
#include <string>
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(WCHAR_T_IS_UTF16)
diff --git a/base/strings/string_number_conversions.h b/base/strings/string_number_conversions.h
index e89e26b..ecf950e 100644
--- a/base/strings/string_number_conversions.h
+++ b/base/strings/string_number_conversions.h
@@ -13,7 +13,7 @@
#include "base/strings/string16.h"
#include "base/strings/string_piece.h"
-#include "build_config.h"
+#include "util/build_config.h"
// ----------------------------------------------------------------------------
// IMPORTANT MESSAGE FROM YOUR SPONSOR
diff --git a/base/strings/string_util.cc b/base/strings/string_util.cc
index a387586..9b03c26 100644
--- a/base/strings/string_util.cc
+++ b/base/strings/string_util.cc
@@ -25,7 +25,7 @@
#include "base/strings/utf_string_conversion_utils.h"
#include "base/strings/utf_string_conversions.h"
#include "base/third_party/icu/icu_utf.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/strings/string_util.h b/base/strings/string_util.h
index 5403ada..2d5d01c 100644
--- a/base/strings/string_util.h
+++ b/base/strings/string_util.h
@@ -19,7 +19,7 @@
#include "base/compiler_specific.h"
#include "base/strings/string16.h"
#include "base/strings/string_piece.h" // For implicit conversions.
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/strings/stringize_macros.h b/base/strings/stringize_macros.h
index 95322e0..251c443 100644
--- a/base/strings/stringize_macros.h
+++ b/base/strings/stringize_macros.h
@@ -9,7 +9,7 @@
#ifndef BASE_STRINGS_STRINGIZE_MACROS_H_
#define BASE_STRINGS_STRINGIZE_MACROS_H_
-#include "build_config.h"
+#include "util/build_config.h"
// This is not very useful as it does not expand defined symbols if
// called directly. Use its counterpart without the _NO_EXPANSION
diff --git a/base/strings/stringprintf.cc b/base/strings/stringprintf.cc
index a241ee6..c7d141b 100644
--- a/base/strings/stringprintf.cc
+++ b/base/strings/stringprintf.cc
@@ -13,7 +13,7 @@
#include "base/scoped_clear_errno.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/strings/stringprintf.h b/base/strings/stringprintf.h
index 9c07862..8c12aca 100644
--- a/base/strings/stringprintf.h
+++ b/base/strings/stringprintf.h
@@ -10,7 +10,7 @@
#include <string>
#include "base/compiler_specific.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/strings/sys_string_conversions.h b/base/strings/sys_string_conversions.h
index a13775c..9150c05 100644
--- a/base/strings/sys_string_conversions.h
+++ b/base/strings/sys_string_conversions.h
@@ -15,7 +15,7 @@
#include "base/strings/string16.h"
#include "base/strings/string_piece.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_MACOSX)
#include <CoreFoundation/CoreFoundation.h>
diff --git a/base/strings/sys_string_conversions_posix.cc b/base/strings/sys_string_conversions_posix.cc
index 1a0c685..0e14428 100644
--- a/base/strings/sys_string_conversions_posix.cc
+++ b/base/strings/sys_string_conversions_posix.cc
@@ -9,7 +9,7 @@
#include "base/strings/string_piece.h"
#include "base/strings/utf_string_conversions.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/strings/utf_string_conversion_utils.cc b/base/strings/utf_string_conversion_utils.cc
index 6098e3a..c962411 100644
--- a/base/strings/utf_string_conversion_utils.cc
+++ b/base/strings/utf_string_conversion_utils.cc
@@ -5,7 +5,7 @@
#include "base/strings/utf_string_conversion_utils.h"
#include "base/third_party/icu/icu_utf.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/strings/utf_string_conversions.cc b/base/strings/utf_string_conversions.cc
index 6a32e39..b04d54d 100644
--- a/base/strings/utf_string_conversions.cc
+++ b/base/strings/utf_string_conversions.cc
@@ -10,7 +10,7 @@
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversion_utils.h"
#include "base/third_party/icu/icu_utf.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/synchronization/condition_variable.h b/base/synchronization/condition_variable.h
deleted file mode 100644
index d778d13..0000000
--- a/base/synchronization/condition_variable.h
+++ /dev/null
@@ -1,118 +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.
-
-// ConditionVariable wraps pthreads condition variable synchronization or, on
-// Windows, simulates it. This functionality is very helpful for having
-// several threads wait for an event, as is common with a thread pool managed
-// by a master. The meaning of such an event in the (worker) thread pool
-// scenario is that additional tasks are now available for processing. It is
-// used in Chrome in the DNS prefetching system to notify worker threads that
-// a queue now has items (tasks) which need to be tended to. A related use
-// would have a pool manager waiting on a ConditionVariable, waiting for a
-// thread in the pool to announce (signal) that there is now more room in a
-// (bounded size) communications queue for the manager to deposit tasks, or,
-// as a second example, that the queue of tasks is completely empty and all
-// workers are waiting.
-//
-// USAGE NOTE 1: spurious signal events are possible with this and
-// most implementations of condition variables. As a result, be
-// *sure* to retest your condition before proceeding. The following
-// is a good example of doing this correctly:
-//
-// while (!work_to_be_done()) Wait(...);
-//
-// In contrast do NOT do the following:
-//
-// if (!work_to_be_done()) Wait(...); // Don't do this.
-//
-// Especially avoid the above if you are relying on some other thread only
-// issuing a signal up *if* there is work-to-do. There can/will
-// be spurious signals. Recheck state on waiting thread before
-// assuming the signal was intentional. Caveat caller ;-).
-//
-// USAGE NOTE 2: Broadcast() frees up all waiting threads at once,
-// which leads to contention for the locks they all held when they
-// called Wait(). This results in POOR performance. A much better
-// approach to getting a lot of threads out of Wait() is to have each
-// thread (upon exiting Wait()) call Signal() to free up another
-// Wait'ing thread. Look at condition_variable_unittest.cc for
-// both examples.
-//
-// Broadcast() can be used nicely during teardown, as it gets the job
-// done, and leaves no sleeping threads... and performance is less
-// critical at that point.
-//
-// The semantics of Broadcast() are carefully crafted so that *all*
-// threads that were waiting when the request was made will indeed
-// get signaled. Some implementations mess up, and don't signal them
-// all, while others allow the wait to be effectively turned off (for
-// a while while waiting threads come around). This implementation
-// appears correct, as it will not "lose" any signals, and will guarantee
-// that all threads get signaled by Broadcast().
-//
-// This implementation offers support for "performance" in its selection of
-// which thread to revive. Performance, in direct contrast with "fairness,"
-// assures that the thread that most recently began to Wait() is selected by
-// Signal to revive. Fairness would (if publicly supported) assure that the
-// thread that has Wait()ed the longest is selected. The default policy
-// may improve performance, as the selected thread may have a greater chance of
-// having some of its stack data in various CPU caches.
-//
-// For a discussion of the many very subtle implementation details, see the FAQ
-// at the end of condition_variable_win.cc.
-
-#ifndef BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_
-#define BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_
-
-#if defined(OS_POSIX) || defined(OS_FUCHSIA)
-#include <pthread.h>
-#endif
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/synchronization/lock.h"
-#include "build_config.h"
-
-#if defined(OS_WIN)
-#include "base/win/windows_types.h"
-#endif
-
-namespace base {
-
-class TimeDelta;
-
-class ConditionVariable {
- public:
- // Construct a cv for use with ONLY one user lock.
- explicit ConditionVariable(Lock* user_lock);
-
- ~ConditionVariable();
-
- // Wait() releases the caller's critical section atomically as it starts to
- // sleep, and the reacquires it when it is signaled. The wait functions are
- // susceptible to spurious wakeups. (See usage note 1 for more details.)
- void Wait();
- void TimedWait(const TimeDelta& max_time);
-
- // Broadcast() revives all waiting threads. (See usage note 2 for more
- // details.)
- void Broadcast();
- // Signal() revives one waiting thread.
- void Signal();
-
- private:
-#if defined(OS_WIN)
- CHROME_CONDITION_VARIABLE cv_;
- CHROME_SRWLOCK* const srwlock_;
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
- pthread_cond_t condition_;
- pthread_mutex_t* user_mutex_;
-#endif
-
- DISALLOW_COPY_AND_ASSIGN(ConditionVariable);
-};
-
-} // namespace base
-
-#endif // BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_
diff --git a/base/synchronization/condition_variable_posix.cc b/base/synchronization/condition_variable_posix.cc
deleted file mode 100644
index 7a5ef5f..0000000
--- a/base/synchronization/condition_variable_posix.cc
+++ /dev/null
@@ -1,111 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/synchronization/condition_variable.h"
-
-#include <errno.h>
-#include <stdint.h>
-#include <sys/time.h>
-
-#include "base/synchronization/lock.h"
-#include "base/time/time.h"
-#include "build_config.h"
-
-namespace base {
-
-ConditionVariable::ConditionVariable(Lock* user_lock)
- : user_mutex_(user_lock->lock_.native_handle()) {
- int rv = 0;
-// http://crbug.com/293736
-// NaCl doesn't support monotonic clock based absolute deadlines.
-// On older Android platform versions, it's supported through the
-// non-standard pthread_cond_timedwait_monotonic_np. Newer platform
-// versions have pthread_condattr_setclock.
-// Mac can use relative time deadlines.
-#if !defined(OS_MACOSX) && !defined(OS_NACL) && \
- !(defined(OS_ANDROID) && defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
- pthread_condattr_t attrs;
- rv = pthread_condattr_init(&attrs);
- DCHECK_EQ(0, rv);
- pthread_condattr_setclock(&attrs, CLOCK_MONOTONIC);
- rv = pthread_cond_init(&condition_, &attrs);
- pthread_condattr_destroy(&attrs);
-#else
- rv = pthread_cond_init(&condition_, NULL);
-#endif
- DCHECK_EQ(0, rv);
-}
-
-ConditionVariable::~ConditionVariable() {
-#if defined(OS_MACOSX)
- // This hack is necessary to avoid a fatal pthreads subsystem bug in the
- // Darwin kernel. http://crbug.com/517681.
- {
- base::Lock lock;
- base::AutoLock l(lock);
- struct timespec ts;
- ts.tv_sec = 0;
- ts.tv_nsec = 1;
- pthread_cond_timedwait_relative_np(&condition_, lock.lock_.native_handle(),
- &ts);
- }
-#endif
-
- int rv = pthread_cond_destroy(&condition_);
- DCHECK_EQ(0, rv);
-}
-
-void ConditionVariable::Wait() {
- int rv = pthread_cond_wait(&condition_, user_mutex_);
- DCHECK_EQ(0, rv);
-}
-
-void ConditionVariable::TimedWait(const TimeDelta& max_time) {
- 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 defined(OS_MACOSX)
- int rv = pthread_cond_timedwait_relative_np(&condition_, user_mutex_,
- &relative_time);
-#else
- // The timeout argument to pthread_cond_timedwait is in absolute time.
- struct timespec absolute_time;
- struct timespec now;
- clock_gettime(CLOCK_MONOTONIC, &now);
- absolute_time.tv_sec = now.tv_sec;
- absolute_time.tv_nsec = now.tv_nsec;
-
- absolute_time.tv_sec += relative_time.tv_sec;
- absolute_time.tv_nsec += relative_time.tv_nsec;
- absolute_time.tv_sec += absolute_time.tv_nsec / Time::kNanosecondsPerSecond;
- absolute_time.tv_nsec %= Time::kNanosecondsPerSecond;
- DCHECK_GE(absolute_time.tv_sec, now.tv_sec); // Overflow paranoia
-
-#if defined(OS_ANDROID) && defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC)
- int rv = pthread_cond_timedwait_monotonic_np(&condition_, user_mutex_,
- &absolute_time);
-#else
- int rv = pthread_cond_timedwait(&condition_, user_mutex_, &absolute_time);
-#endif // OS_ANDROID && HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC
-#endif // OS_MACOSX
-
- // 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);
-}
-
-void ConditionVariable::Broadcast() {
- int rv = pthread_cond_broadcast(&condition_);
- DCHECK_EQ(0, rv);
-}
-
-void ConditionVariable::Signal() {
- int rv = pthread_cond_signal(&condition_);
- DCHECK_EQ(0, rv);
-}
-
-} // namespace base
diff --git a/base/synchronization/condition_variable_win.cc b/base/synchronization/condition_variable_win.cc
deleted file mode 100644
index 87cc353..0000000
--- a/base/synchronization/condition_variable_win.cc
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/synchronization/condition_variable.h"
-
-#include "base/synchronization/lock.h"
-#include "base/time/time.h"
-
-#include <windows.h>
-
-namespace base {
-
-ConditionVariable::ConditionVariable(Lock* user_lock)
- : srwlock_(user_lock->lock_.native_handle()) {
- DCHECK(user_lock);
- InitializeConditionVariable(reinterpret_cast<PCONDITION_VARIABLE>(&cv_));
-}
-
-ConditionVariable::~ConditionVariable() = default;
-
-void ConditionVariable::Wait() {
- TimedWait(TimeDelta::FromMilliseconds(INFINITE));
-}
-
-void ConditionVariable::TimedWait(const TimeDelta& max_time) {
- DWORD timeout = static_cast<DWORD>(max_time.InMilliseconds());
-
- if (!SleepConditionVariableSRW(reinterpret_cast<PCONDITION_VARIABLE>(&cv_),
- reinterpret_cast<PSRWLOCK>(srwlock_), timeout,
- 0)) {
- // On failure, we only expect the CV to timeout. Any other error value means
- // that we've unexpectedly woken up.
- // Note that WAIT_TIMEOUT != ERROR_TIMEOUT. WAIT_TIMEOUT is used with the
- // WaitFor* family of functions as a direct return value. ERROR_TIMEOUT is
- // used with GetLastError().
- DCHECK_EQ(static_cast<DWORD>(ERROR_TIMEOUT), GetLastError());
- }
-}
-
-void ConditionVariable::Broadcast() {
- WakeAllConditionVariable(reinterpret_cast<PCONDITION_VARIABLE>(&cv_));
-}
-
-void ConditionVariable::Signal() {
- WakeConditionVariable(reinterpret_cast<PCONDITION_VARIABLE>(&cv_));
-}
-
-} // namespace base
diff --git a/base/synchronization/lock.h b/base/synchronization/lock.h
deleted file mode 100644
index 98668e9..0000000
--- a/base/synchronization/lock.h
+++ /dev/null
@@ -1,104 +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_SYNCHRONIZATION_LOCK_H_
-#define BASE_SYNCHRONIZATION_LOCK_H_
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/synchronization/lock_impl.h"
-#include "build_config.h"
-
-namespace base {
-
-// A convenient wrapper for an OS specific critical section. The only real
-// intelligence in this class is in debug mode for the support for the
-// AssertAcquired() method.
-class Lock {
- public:
- // Optimized wrapper implementation
- Lock() : lock_() {}
- ~Lock() {}
- void Acquire() { lock_.Lock(); }
- void Release() { lock_.Unlock(); }
-
- // If the lock is not held, take it and return true. If the lock is already
- // held by another thread, immediately return false. This must not be called
- // by a thread already holding the lock (what happens is undefined and an
- // assertion may fail).
- bool Try() { return lock_.Try(); }
-
- // Null implementation if not debug.
- void AssertAcquired() const {}
-
- // Whether Lock mitigates priority inversion when used from different thread
- // priorities.
- static bool HandlesMultipleThreadPriorities() {
-#if defined(OS_WIN)
- // Windows mitigates priority inversion by randomly boosting the priority of
- // ready threads.
- // https://msdn.microsoft.com/library/windows/desktop/ms684831.aspx
- return true;
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
- // POSIX mitigates priority inversion by setting the priority of a thread
- // holding a Lock to the maximum priority of any other thread waiting on it.
- return internal::LockImpl::PriorityInheritanceAvailable();
-#else
-#error Unsupported platform
-#endif
- }
-
- // Both Windows and POSIX implementations of ConditionVariable need to be
- // able to see our lock and tweak our debugging counters, as they release and
- // acquire locks inside of their condition variable APIs.
- friend class ConditionVariable;
-
- private:
- // Platform specific underlying lock implementation.
- internal::LockImpl lock_;
-
- DISALLOW_COPY_AND_ASSIGN(Lock);
-};
-
-// A helper class that acquires the given Lock while the AutoLock is in scope.
-class AutoLock {
- public:
- struct AlreadyAcquired {};
-
- explicit AutoLock(Lock& lock) : lock_(lock) { lock_.Acquire(); }
-
- AutoLock(Lock& lock, const AlreadyAcquired&) : lock_(lock) {
- lock_.AssertAcquired();
- }
-
- ~AutoLock() {
- lock_.AssertAcquired();
- lock_.Release();
- }
-
- private:
- Lock& lock_;
- DISALLOW_COPY_AND_ASSIGN(AutoLock);
-};
-
-// AutoUnlock is a helper that will Release() the |lock| argument in the
-// constructor, and re-Acquire() it in the destructor.
-class AutoUnlock {
- public:
- explicit AutoUnlock(Lock& lock) : lock_(lock) {
- // We require our caller to have the lock.
- lock_.AssertAcquired();
- lock_.Release();
- }
-
- ~AutoUnlock() { lock_.Acquire(); }
-
- private:
- Lock& lock_;
- DISALLOW_COPY_AND_ASSIGN(AutoUnlock);
-};
-
-} // namespace base
-
-#endif // BASE_SYNCHRONIZATION_LOCK_H_
diff --git a/base/synchronization/lock_impl.h b/base/synchronization/lock_impl.h
deleted file mode 100644
index 24ca09e..0000000
--- a/base/synchronization/lock_impl.h
+++ /dev/null
@@ -1,77 +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_SYNCHRONIZATION_LOCK_IMPL_H_
-#define BASE_SYNCHRONIZATION_LOCK_IMPL_H_
-
-#include "base/logging.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 <errno.h>
-#include <pthread.h>
-#endif
-
-namespace base {
-namespace internal {
-
-// This class implements the underlying platform-specific spin-lock mechanism
-// used for the Lock class. Most users should not use LockImpl directly, but
-// should instead use Lock.
-class LockImpl {
- public:
-#if defined(OS_WIN)
- using NativeHandle = CHROME_SRWLOCK;
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
- using NativeHandle = pthread_mutex_t;
-#endif
-
- LockImpl();
- ~LockImpl();
-
- // If the lock is not held, take it and return true. If the lock is already
- // held by something else, immediately return false.
- bool Try();
-
- // Take the lock, blocking until it is available if necessary.
- void Lock();
-
- // Release the lock. This must only be called by the lock's holder: after
- // a successful call to Try, or a call to Lock.
- inline void Unlock();
-
- // Return the native underlying lock.
- // TODO(awalker): refactor lock and condition variables so that this is
- // unnecessary.
- NativeHandle* native_handle() { return &native_handle_; }
-
-#if defined(OS_POSIX) || defined(OS_FUCHSIA)
- // Whether this lock will attempt to use priority inheritance.
- static bool PriorityInheritanceAvailable();
-#endif
-
- private:
- NativeHandle native_handle_;
-
- DISALLOW_COPY_AND_ASSIGN(LockImpl);
-};
-
-#if defined(OS_WIN)
-void LockImpl::Unlock() {
- ::ReleaseSRWLockExclusive(reinterpret_cast<PSRWLOCK>(&native_handle_));
-}
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
-void LockImpl::Unlock() {
- int rv = pthread_mutex_unlock(&native_handle_);
- DCHECK_EQ(rv, 0) << ". " << strerror(rv);
-}
-#endif
-
-} // namespace internal
-} // namespace base
-
-#endif // BASE_SYNCHRONIZATION_LOCK_IMPL_H_
diff --git a/base/synchronization/lock_impl_posix.cc b/base/synchronization/lock_impl_posix.cc
deleted file mode 100644
index 3812fe2..0000000
--- a/base/synchronization/lock_impl_posix.cc
+++ /dev/null
@@ -1,117 +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/lock_impl.h"
-
-#include <string>
-
-#include "base/logging.h"
-#include "base/posix/safe_strerror.h"
-#include "base/strings/stringprintf.h"
-#include "base/synchronization/lock.h"
-#include "build_config.h"
-
-namespace base {
-namespace internal {
-
-namespace {
-
-#if DCHECK_IS_ON()
-const char* AdditionalHintForSystemErrorCode(int error_code) {
- switch (error_code) {
- case EINVAL:
- return "Hint: This is often related to a use-after-free.";
- default:
- return "";
- }
-}
-#endif // DCHECK_IS_ON()
-
-std::string SystemErrorCodeToString(int error_code) {
-#if DCHECK_IS_ON()
- return base::safe_strerror(error_code) + ". " +
- AdditionalHintForSystemErrorCode(error_code);
-#else // DCHECK_IS_ON()
- return std::string();
-#endif // DCHECK_IS_ON()
-}
-
-} // namespace
-
-// Determines which platforms can consider using priority inheritance locks. Use
-// this define for platform code that may not compile if priority inheritance
-// locks aren't available. For this platform code,
-// PRIORITY_INHERITANCE_LOCKS_POSSIBLE() is a necessary but insufficient check.
-// Lock::PriorityInheritanceAvailable still must be checked as the code may
-// compile but the underlying platform still may not correctly support priority
-// inheritance locks.
-#if defined(OS_NACL) || defined(OS_ANDROID) || defined(OS_FUCHSIA)
-#define PRIORITY_INHERITANCE_LOCKS_POSSIBLE() 0
-#else
-#define PRIORITY_INHERITANCE_LOCKS_POSSIBLE() 1
-#endif
-
-LockImpl::LockImpl() {
- pthread_mutexattr_t mta;
- int rv = pthread_mutexattr_init(&mta);
- DCHECK_EQ(rv, 0) << ". " << SystemErrorCodeToString(rv);
-#if PRIORITY_INHERITANCE_LOCKS_POSSIBLE()
- if (PriorityInheritanceAvailable()) {
- rv = pthread_mutexattr_setprotocol(&mta, PTHREAD_PRIO_INHERIT);
- DCHECK_EQ(rv, 0) << ". " << SystemErrorCodeToString(rv);
- }
-#endif
-#ifndef NDEBUG
- // In debug, setup attributes for lock error checking.
- rv = pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_ERRORCHECK);
- DCHECK_EQ(rv, 0) << ". " << SystemErrorCodeToString(rv);
-#endif
- rv = pthread_mutex_init(&native_handle_, &mta);
- DCHECK_EQ(rv, 0) << ". " << SystemErrorCodeToString(rv);
- rv = pthread_mutexattr_destroy(&mta);
- DCHECK_EQ(rv, 0) << ". " << SystemErrorCodeToString(rv);
-}
-
-LockImpl::~LockImpl() {
- int rv = pthread_mutex_destroy(&native_handle_);
- DCHECK_EQ(rv, 0) << ". " << SystemErrorCodeToString(rv);
-}
-
-bool LockImpl::Try() {
- int rv = pthread_mutex_trylock(&native_handle_);
- DCHECK(rv == 0 || rv == EBUSY) << ". " << SystemErrorCodeToString(rv);
- return rv == 0;
-}
-
-void LockImpl::Lock() {
- int rv = pthread_mutex_lock(&native_handle_);
- DCHECK_EQ(rv, 0) << ". " << SystemErrorCodeToString(rv);
-}
-
-// static
-bool LockImpl::PriorityInheritanceAvailable() {
-#if PRIORITY_INHERITANCE_LOCKS_POSSIBLE() && defined(OS_MACOSX)
- return true;
-#else
- // Security concerns prevent the use of priority inheritance mutexes on Linux.
- // * CVE-2010-0622 - Linux < 2.6.33-rc7, wake_futex_pi possible DoS.
- // https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2010-0622
- // * CVE-2012-6647 - Linux < 3.5.1, futex_wait_requeue_pi possible DoS.
- // https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-6647
- // * CVE-2014-3153 - Linux <= 3.14.5, futex_requeue, privilege escalation.
- // https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-3153
- //
- // If the above were all addressed, we still need a runtime check to deal with
- // the bug below.
- // * glibc Bug 14652: https://sourceware.org/bugzilla/show_bug.cgi?id=14652
- // Fixed in glibc 2.17.
- // Priority inheritance mutexes may deadlock with condition variables
- // during reacquisition of the mutex after the condition variable is
- // signalled.
- return false;
-#endif
-}
-
-} // namespace internal
-} // namespace base
diff --git a/base/synchronization/lock_impl_win.cc b/base/synchronization/lock_impl_win.cc
deleted file mode 100644
index d99dac1..0000000
--- a/base/synchronization/lock_impl_win.cc
+++ /dev/null
@@ -1,26 +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/lock_impl.h"
-
-#include <windows.h>
-
-namespace base {
-namespace internal {
-
-LockImpl::LockImpl() : native_handle_(SRWLOCK_INIT) {}
-
-LockImpl::~LockImpl() = default;
-
-bool LockImpl::Try() {
- return !!::TryAcquireSRWLockExclusive(
- reinterpret_cast<PSRWLOCK>(&native_handle_));
-}
-
-void LockImpl::Lock() {
- ::AcquireSRWLockExclusive(reinterpret_cast<PSRWLOCK>(&native_handle_));
-}
-
-} // namespace internal
-} // namespace base
diff --git a/base/synchronization/waitable_event.h b/base/synchronization/waitable_event.h
deleted file mode 100644
index ee1d33a..0000000
--- a/base/synchronization/waitable_event.h
+++ /dev/null
@@ -1,284 +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_H_
-#define BASE_SYNCHRONIZATION_WAITABLE_EVENT_H_
-
-#include <stddef.h>
-
-#include "base/macros.h"
-#include "build_config.h"
-
-#if defined(OS_WIN)
-#include "base/win/scoped_handle.h"
-#elif defined(OS_MACOSX)
-#include <mach/mach.h>
-
-#include <list>
-#include <memory>
-
-#include "base/callback_forward.h"
-#include "base/mac/scoped_mach_port.h"
-#include "base/memory/ref_counted.h"
-#include "base/synchronization/lock.h"
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
-#include <list>
-#include <utility>
-
-#include "base/memory/ref_counted.h"
-#include "base/synchronization/lock.h"
-#endif
-
-namespace base {
-
-class TimeDelta;
-class TimeTicks;
-
-// A WaitableEvent can be a useful thread synchronization tool when you want to
-// allow one thread to wait for another thread to finish some work. For
-// non-Windows systems, this can only be used from within a single address
-// space.
-//
-// Use a WaitableEvent when you would otherwise use a Lock+ConditionVariable to
-// protect a simple boolean value. However, if you find yourself using a
-// WaitableEvent in conjunction with a Lock to wait for a more complex state
-// change (e.g., for an item to be added to a queue), then you should probably
-// be using a ConditionVariable instead of a WaitableEvent.
-//
-// NOTE: On Windows, this class provides a subset of the functionality afforded
-// by a Windows event object. This is intentional. If you are writing Windows
-// specific code and you need other features of a Windows event, then you might
-// be better off just using an Windows event directly.
-class WaitableEvent {
- public:
- // Indicates whether a WaitableEvent should automatically reset the event
- // state after a single waiting thread has been released or remain signaled
- // until Reset() is manually invoked.
- enum class ResetPolicy { MANUAL, AUTOMATIC };
-
- // Indicates whether a new WaitableEvent should start in a signaled state or
- // not.
- enum class InitialState { SIGNALED, NOT_SIGNALED };
-
- // Constructs a WaitableEvent with policy and initial state as detailed in
- // the above enums.
- WaitableEvent(ResetPolicy reset_policy = ResetPolicy::MANUAL,
- InitialState initial_state = InitialState::NOT_SIGNALED);
-
-#if defined(OS_WIN)
- // Create a WaitableEvent from an Event HANDLE which has already been
- // created. This objects takes ownership of the HANDLE and will close it when
- // deleted.
- explicit WaitableEvent(win::ScopedHandle event_handle);
-#endif
-
- ~WaitableEvent();
-
- // Put the event in the un-signaled state.
- void Reset();
-
- // Put the event in the signaled state. Causing any thread blocked on Wait
- // to be woken up.
- void Signal();
-
- // Returns true if the event is in the signaled state, else false. If this
- // is not a manual reset event, then this test will cause a reset.
- bool IsSignaled();
-
- // Wait indefinitely for the event to be signaled. Wait's return "happens
- // after" |Signal| has completed. This means that it's safe for a
- // WaitableEvent to synchronise its own destruction, like this:
- //
- // WaitableEvent *e = new WaitableEvent;
- // SendToOtherThread(e);
- // e->Wait();
- // delete e;
- void Wait();
-
- // Wait up until wait_delta has passed for the event to be signaled. Returns
- // true if the event was signaled.
- //
- // TimedWait can synchronise its own destruction like |Wait|.
- bool TimedWait(const TimeDelta& wait_delta);
-
- // Wait up until end_time deadline has passed for the event to be signaled.
- // Return true if the event was signaled.
- //
- // TimedWaitUntil can synchronise its own destruction like |Wait|.
- bool TimedWaitUntil(const TimeTicks& end_time);
-
-#if defined(OS_WIN)
- HANDLE handle() const { return handle_.Get(); }
-#endif
-
- // Wait, synchronously, on multiple events.
- // waitables: an array of WaitableEvent pointers
- // count: the number of elements in @waitables
- //
- // returns: the index of a WaitableEvent which has been signaled.
- //
- // You MUST NOT delete any of the WaitableEvent objects while this wait is
- // happening, however WaitMany's return "happens after" the |Signal| call
- // that caused it has completed, like |Wait|.
- //
- // If more than one WaitableEvent is signaled to unblock WaitMany, the lowest
- // index among them is returned.
- static size_t WaitMany(WaitableEvent** waitables, size_t count);
-
- // For asynchronous waiting, see WaitableEventWatcher
-
- // This is a private helper class. It's here because it's used by friends of
- // this class (such as WaitableEventWatcher) to be able to enqueue elements
- // of the wait-list
- class Waiter {
- public:
- // Signal the waiter to wake up.
- //
- // Consider the case of a Waiter which is in multiple WaitableEvent's
- // wait-lists. Each WaitableEvent is automatic-reset and two of them are
- // signaled at the same time. Now, each will wake only the first waiter in
- // the wake-list before resetting. However, if those two waiters happen to
- // be the same object (as can happen if another thread didn't have a chance
- // to dequeue the waiter from the other wait-list in time), two auto-resets
- // will have happened, but only one waiter has been signaled!
- //
- // Because of this, a Waiter may "reject" a wake by returning false. In
- // this case, the auto-reset WaitableEvent shouldn't act as if anything has
- // been notified.
- virtual bool Fire(WaitableEvent* signaling_event) = 0;
-
- // Waiters may implement this in order to provide an extra condition for
- // two Waiters to be considered equal. In WaitableEvent::Dequeue, if the
- // pointers match then this function is called as a final check. See the
- // comments in ~Handle for why.
- virtual bool Compare(void* tag) = 0;
-
- protected:
- virtual ~Waiter() = default;
- };
-
- private:
- friend class WaitableEventWatcher;
-
-#if defined(OS_WIN)
- win::ScopedHandle handle_;
-#elif defined(OS_MACOSX)
- // Prior to macOS 10.12, a TYPE_MACH_RECV dispatch source may not be invoked
- // immediately. If a WaitableEventWatcher is used on a manual-reset event,
- // and another thread that is Wait()ing on the event calls Reset()
- // immediately after waking up, the watcher may not receive the callback.
- // On macOS 10.12 and higher, dispatch delivery is reliable. But for OSes
- // prior, a lock-protected list of callbacks is used for manual-reset event
- // watchers. Automatic-reset events are not prone to this issue, since the
- // first thread to wake will claim the event.
- static bool UseSlowWatchList(ResetPolicy policy);
-
- // Peeks the message queue named by |port| and returns true if a message
- // is present and false if not. If |dequeue| is true, the messsage will be
- // drained from the queue. If |dequeue| is false, the queue will only be
- // peeked. |port| must be a receive right.
- static bool PeekPort(mach_port_t port, bool dequeue);
-
- // The Mach receive right is waited on by both WaitableEvent and
- // WaitableEventWatcher. It is valid to signal and then delete an event, and
- // a watcher should still be notified. If the right were to be destroyed
- // immediately, the watcher would not receive the signal. Because Mach
- // receive rights cannot have a user refcount greater than one, the right
- // must be reference-counted manually.
- class ReceiveRight : public RefCountedThreadSafe<ReceiveRight> {
- public:
- ReceiveRight(mach_port_t name, bool create_slow_watch_list);
-
- mach_port_t Name() const { return right_.get(); };
-
- // This structure is used iff UseSlowWatchList() is true. See the comment
- // in Signal() for details.
- struct WatchList {
- WatchList();
- ~WatchList();
-
- // The lock protects a list of closures to be run when the event is
- // Signal()ed. The closures are invoked on the signaling thread, so they
- // must be safe to be called from any thread.
- Lock lock;
- std::list<OnceClosure> list;
- };
-
- WatchList* SlowWatchList() const { return slow_watch_list_.get(); }
-
- private:
- friend class RefCountedThreadSafe<ReceiveRight>;
- ~ReceiveRight();
-
- mac::ScopedMachReceiveRight right_;
-
- // This is allocated iff UseSlowWatchList() is true. It is created on the
- // heap to avoid performing initialization when not using the slow path.
- std::unique_ptr<WatchList> slow_watch_list_;
-
- DISALLOW_COPY_AND_ASSIGN(ReceiveRight);
- };
-
- const ResetPolicy policy_;
-
- // The receive right for the event.
- scoped_refptr<ReceiveRight> receive_right_;
-
- // The send right used to signal the event. This can be disposed of with
- // the event, unlike the receive right, since a deleted event cannot be
- // signaled.
- mac::ScopedMachSendRight send_right_;
-#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
- // On Windows, you must not close a HANDLE which is currently being waited on.
- // The MSDN documentation says that the resulting behaviour is 'undefined'.
- // To solve that issue each WaitableEventWatcher duplicates the given event
- // handle.
-
- // However, if we were to include the following members
- // directly then, on POSIX, one couldn't use WaitableEventWatcher to watch an
- // event which gets deleted. This mismatch has bitten us several times now,
- // so we have a kernel of the WaitableEvent, which is reference counted.
- // WaitableEventWatchers may then take a reference and thus match the Windows
- // behaviour.
- struct WaitableEventKernel
- : public RefCountedThreadSafe<WaitableEventKernel> {
- public:
- WaitableEventKernel(ResetPolicy reset_policy, InitialState initial_state);
-
- bool Dequeue(Waiter* waiter, void* tag);
-
- base::Lock lock_;
- const bool manual_reset_;
- bool signaled_;
- std::list<Waiter*> waiters_;
-
- private:
- friend class RefCountedThreadSafe<WaitableEventKernel>;
- ~WaitableEventKernel();
- };
-
- typedef std::pair<WaitableEvent*, size_t> WaiterAndIndex;
-
- // When dealing with arrays of WaitableEvent*, we want to sort by the address
- // of the WaitableEvent in order to have a globally consistent locking order.
- // In that case we keep them, in sorted order, in an array of pairs where the
- // second element is the index of the WaitableEvent in the original,
- // unsorted, array.
- static size_t EnqueueMany(WaiterAndIndex* waitables,
- size_t count,
- Waiter* waiter);
-
- bool SignalAll();
- bool SignalOne();
- void Enqueue(Waiter* waiter);
-
- scoped_refptr<WaitableEventKernel> kernel_;
-#endif
-
- DISALLOW_COPY_AND_ASSIGN(WaitableEvent);
-};
-
-} // namespace base
-
-#endif // BASE_SYNCHRONIZATION_WAITABLE_EVENT_H_
diff --git a/base/synchronization/waitable_event_mac.cc b/base/synchronization/waitable_event_mac.cc
deleted file mode 100644
index 67eca5b..0000000
--- a/base/synchronization/waitable_event_mac.cc
+++ /dev/null
@@ -1,349 +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.h"
-
-#include <dispatch/dispatch.h>
-#include <mach/mach.h>
-#include <sys/event.h>
-
-#include "base/callback.h"
-#include "base/files/scoped_file.h"
-#include "base/mac/dispatch_source_mach.h"
-#include "base/mac/mac_util.h"
-#include "base/mac/mach_logging.h"
-#include "base/mac/scoped_dispatch_object.h"
-#include "base/posix/eintr_wrapper.h"
-#include "base/time/time.h"
-#include "build_config.h"
-
-namespace base {
-
-WaitableEvent::WaitableEvent(ResetPolicy reset_policy,
- InitialState initial_state)
- : policy_(reset_policy) {
- mach_port_options_t options{};
- options.flags = MPO_INSERT_SEND_RIGHT;
- options.mpl.mpl_qlimit = 1;
-
- mach_port_t name;
- kern_return_t kr = mach_port_construct(mach_task_self(), &options, 0, &name);
- MACH_CHECK(kr == KERN_SUCCESS, kr) << "mach_port_construct";
-
- receive_right_ = new ReceiveRight(name, UseSlowWatchList(policy_));
- send_right_.reset(name);
-
- if (initial_state == InitialState::SIGNALED)
- Signal();
-}
-
-WaitableEvent::~WaitableEvent() = default;
-
-void WaitableEvent::Reset() {
- PeekPort(receive_right_->Name(), true);
-}
-
-void WaitableEvent::Signal() {
- // If using the slow watch-list, copy the watchers to a local. After
- // mach_msg(), the event object may be deleted by an awoken thread.
- const bool use_slow_path = UseSlowWatchList(policy_);
- ReceiveRight* receive_right = nullptr; // Manually reference counted.
- std::unique_ptr<std::list<OnceClosure>> watch_list;
- if (use_slow_path) {
- // To avoid a race condition of a WaitableEventWatcher getting added
- // while another thread is in this method, hold the watch-list lock for
- // the duration of mach_msg(). This requires ref-counting the
- // |receive_right_| object that contains it, in case the event is deleted
- // by a waiting thread after mach_msg().
- receive_right = receive_right_.get();
- receive_right->AddRef();
-
- ReceiveRight::WatchList* slow_watch_list = receive_right->SlowWatchList();
- slow_watch_list->lock.Acquire();
-
- if (!slow_watch_list->list.empty()) {
- watch_list.reset(new std::list<OnceClosure>());
- std::swap(*watch_list, slow_watch_list->list);
- }
- }
-
- mach_msg_empty_send_t msg{};
- msg.header.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_COPY_SEND);
- msg.header.msgh_size = sizeof(&msg);
- msg.header.msgh_remote_port = send_right_.get();
- // If the event is already signaled, this will time out because the queue
- // has a length of one.
- kern_return_t kr =
- mach_msg(&msg.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof(msg), 0,
- MACH_PORT_NULL, 0, MACH_PORT_NULL);
- MACH_CHECK(kr == KERN_SUCCESS || kr == MACH_SEND_TIMED_OUT, kr) << "mach_msg";
-
- if (use_slow_path) {
- // If a WaitableEventWatcher were to start watching when the event is
- // signaled, it runs the callback immediately without adding it to the
- // list. Therefore the watch list can only be non-empty if the event is
- // newly signaled.
- if (watch_list.get()) {
- MACH_CHECK(kr == KERN_SUCCESS, kr);
- for (auto& watcher : *watch_list) {
- std::move(watcher).Run();
- }
- }
-
- receive_right->SlowWatchList()->lock.Release();
- receive_right->Release();
- }
-}
-
-bool WaitableEvent::IsSignaled() {
- return PeekPort(receive_right_->Name(), policy_ == ResetPolicy::AUTOMATIC);
-}
-
-void WaitableEvent::Wait() {
- bool result = TimedWaitUntil(TimeTicks::Max());
- DCHECK(result) << "TimedWait() should never fail with infinite timeout";
-}
-
-bool WaitableEvent::TimedWait(const TimeDelta& wait_delta) {
- return TimedWaitUntil(TimeTicks::Now() + wait_delta);
-}
-
-bool WaitableEvent::TimedWaitUntil(const TimeTicks& end_time) {
- TimeDelta wait_time = end_time - TimeTicks::Now();
- if (wait_time < TimeDelta()) {
- // A negative delta would be treated by the system as indefinite, but
- // it needs to be treated as a poll instead.
- wait_time = TimeDelta();
- }
-
- mach_msg_empty_rcv_t msg{};
- msg.header.msgh_local_port = receive_right_->Name();
-
- mach_msg_option_t options = MACH_RCV_MSG;
-
- mach_msg_timeout_t timeout = 0;
- if (!end_time.is_max()) {
- options |= MACH_RCV_TIMEOUT;
- timeout = wait_time.InMillisecondsRoundedUp();
- }
-
- mach_msg_size_t rcv_size = sizeof(msg);
- if (policy_ == ResetPolicy::MANUAL) {
- // To avoid dequeing the message, receive with a size of 0 and set
- // MACH_RCV_LARGE to keep the message in the queue.
- options |= MACH_RCV_LARGE;
- rcv_size = 0;
- }
-
- kern_return_t kr = mach_msg(&msg.header, options, 0, rcv_size,
- receive_right_->Name(), timeout, MACH_PORT_NULL);
- if (kr == KERN_SUCCESS) {
- return true;
- } else if (rcv_size == 0 && kr == MACH_RCV_TOO_LARGE) {
- return true;
- } else {
- MACH_CHECK(kr == MACH_RCV_TIMED_OUT, kr) << "mach_msg";
- return false;
- }
-}
-
-// static
-bool WaitableEvent::UseSlowWatchList(ResetPolicy policy) {
-#if defined(OS_IOS)
- const bool use_slow_path = false;
-#else
- static bool use_slow_path = !mac::IsAtLeastOS10_12();
-#endif
- return policy == ResetPolicy::MANUAL && use_slow_path;
-}
-
-// static
-size_t WaitableEvent::WaitMany(WaitableEvent** raw_waitables, size_t count) {
- DCHECK(count) << "Cannot wait on no events";
-
- // 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
- // instead to work around that. On macOS 10.9 and 10.10, kqueue only works
- // for port sets, so port sets are just used directly. On macOS 10.11,
- // libdispatch sources are used. Therefore, there are three different
- // primitives that can be used to implement WaitMany. Which one to use is
- // selected at run-time by OS version checks.
- enum WaitManyPrimitive {
- KQUEUE,
- DISPATCH,
- PORT_SET,
- };
-#if defined(OS_IOS)
- const WaitManyPrimitive kPrimitive = PORT_SET;
-#else
- const WaitManyPrimitive kPrimitive =
- mac::IsAtLeastOS10_12() ? KQUEUE
- : (mac::IsOS10_11() ? DISPATCH : PORT_SET);
-#endif
- if (kPrimitive == KQUEUE) {
- std::vector<kevent64_s> events(count);
- for (size_t i = 0; i < count; ++i) {
- EV_SET64(&events[i], raw_waitables[i]->receive_right_->Name(),
- EVFILT_MACHPORT, EV_ADD, 0, 0, i, 0, 0);
- }
-
- std::vector<kevent64_s> out_events(count);
-
- ScopedFD wait_many(kqueue());
- PCHECK(wait_many.is_valid()) << "kqueue";
-
- int rv = HANDLE_EINTR(kevent64(wait_many.get(), events.data(), count,
- out_events.data(), count, 0, nullptr));
- PCHECK(rv > 0) << "kevent64";
-
- size_t triggered = -1;
- for (size_t i = 0; i < static_cast<size_t>(rv); ++i) {
- // WaitMany should return the lowest index in |raw_waitables| that was
- // triggered.
- size_t index = static_cast<size_t>(out_events[i].udata);
- triggered = std::min(triggered, index);
- }
-
- if (raw_waitables[triggered]->policy_ == ResetPolicy::AUTOMATIC) {
- // The message needs to be dequeued to reset the event.
- PeekPort(raw_waitables[triggered]->receive_right_->Name(), true);
- }
-
- return triggered;
- } else if (kPrimitive == DISPATCH) {
- // Each item in |raw_waitables| will be watched using a dispatch souce
- // scheduled on the serial |queue|. The first one to be invoked will
- // signal the |semaphore| that this method will wait on.
- ScopedDispatchObject<dispatch_queue_t> queue(dispatch_queue_create(
- "org.chromium.base.WaitableEvent.WaitMany", DISPATCH_QUEUE_SERIAL));
- ScopedDispatchObject<dispatch_semaphore_t> semaphore(
- dispatch_semaphore_create(0));
-
- // Block capture references. |signaled| will identify the index in
- // |raw_waitables| whose source was invoked.
- dispatch_semaphore_t semaphore_ref = semaphore.get();
- const size_t kUnsignaled = -1;
- __block size_t signaled = kUnsignaled;
-
- // Create a MACH_RECV dispatch source for each event. These must be
- // destroyed before the |queue| and |semaphore|.
- std::vector<std::unique_ptr<DispatchSourceMach>> sources;
- for (size_t i = 0; i < count; ++i) {
- const bool auto_reset =
- raw_waitables[i]->policy_ == WaitableEvent::ResetPolicy::AUTOMATIC;
- // The block will copy a reference to |right|.
- scoped_refptr<WaitableEvent::ReceiveRight> right =
- raw_waitables[i]->receive_right_;
- auto source =
- std::make_unique<DispatchSourceMach>(queue, right->Name(), ^{
- // After the semaphore is signaled, another event be signaled and
- // the source may have its block put on the |queue|. WaitMany
- // should only report (and auto-reset) one event, so the first
- // event to signal is reported.
- if (signaled == kUnsignaled) {
- signaled = i;
- if (auto_reset) {
- PeekPort(right->Name(), true);
- }
- dispatch_semaphore_signal(semaphore_ref);
- }
- });
- source->Resume();
- sources.push_back(std::move(source));
- }
-
- dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
- DCHECK_NE(signaled, kUnsignaled);
- return signaled;
- } else {
- DCHECK_EQ(kPrimitive, PORT_SET);
-
- kern_return_t kr;
-
- mac::ScopedMachPortSet port_set;
- {
- mach_port_t name;
- kr =
- mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_PORT_SET, &name);
- MACH_CHECK(kr == KERN_SUCCESS, kr) << "mach_port_allocate";
- port_set.reset(name);
- }
-
- for (size_t i = 0; i < count; ++i) {
- kr = mach_port_insert_member(mach_task_self(),
- raw_waitables[i]->receive_right_->Name(),
- port_set.get());
- MACH_CHECK(kr == KERN_SUCCESS, kr) << "index " << i;
- }
-
- mach_msg_empty_rcv_t msg{};
- // Wait on the port set. Only specify space enough for the header, to
- // identify which port in the set is signaled. Otherwise, receiving from the
- // port set may dequeue a message for a manual-reset event object, which
- // would cause it to be reset.
- kr = mach_msg(&msg.header,
- MACH_RCV_MSG | MACH_RCV_LARGE | MACH_RCV_LARGE_IDENTITY, 0,
- sizeof(msg.header), port_set.get(), 0, MACH_PORT_NULL);
- MACH_CHECK(kr == MACH_RCV_TOO_LARGE, kr) << "mach_msg";
-
- for (size_t i = 0; i < count; ++i) {
- WaitableEvent* event = raw_waitables[i];
- if (msg.header.msgh_local_port == event->receive_right_->Name()) {
- if (event->policy_ == ResetPolicy::AUTOMATIC) {
- // The message needs to be dequeued to reset the event.
- PeekPort(msg.header.msgh_local_port, true);
- }
- return i;
- }
- }
-
- NOTREACHED();
- return 0;
- }
-}
-
-// static
-bool WaitableEvent::PeekPort(mach_port_t port, bool dequeue) {
- if (dequeue) {
- mach_msg_empty_rcv_t msg{};
- msg.header.msgh_local_port = port;
- kern_return_t kr = mach_msg(&msg.header, MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0,
- sizeof(msg), port, 0, MACH_PORT_NULL);
- if (kr == KERN_SUCCESS) {
- return true;
- } else {
- MACH_CHECK(kr == MACH_RCV_TIMED_OUT, kr) << "mach_msg";
- return false;
- }
- } else {
- mach_port_seqno_t seqno = 0;
- mach_msg_size_t size;
- mach_msg_id_t id;
- mach_msg_trailer_t trailer;
- mach_msg_type_number_t trailer_size = sizeof(trailer);
- kern_return_t kr = mach_port_peek(
- mach_task_self(), port, MACH_RCV_TRAILER_TYPE(MACH_RCV_TRAILER_NULL),
- &seqno, &size, &id, reinterpret_cast<mach_msg_trailer_info_t>(&trailer),
- &trailer_size);
- if (kr == KERN_SUCCESS) {
- return true;
- } else {
- MACH_CHECK(kr == KERN_FAILURE, kr) << "mach_port_peek";
- return false;
- }
- }
-}
-
-WaitableEvent::ReceiveRight::ReceiveRight(mach_port_t name,
- bool create_slow_watch_list)
- : right_(name),
- slow_watch_list_(create_slow_watch_list ? new WatchList() : nullptr) {}
-
-WaitableEvent::ReceiveRight::~ReceiveRight() = default;
-
-WaitableEvent::ReceiveRight::WatchList::WatchList() = default;
-
-WaitableEvent::ReceiveRight::WatchList::~WatchList() = default;
-
-} // namespace base
diff --git a/base/synchronization/waitable_event_posix.cc b/base/synchronization/waitable_event_posix.cc
deleted file mode 100644
index 485038d..0000000
--- a/base/synchronization/waitable_event_posix.cc
+++ /dev/null
@@ -1,413 +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 <stddef.h>
-
-#include <algorithm>
-#include <limits>
-#include <vector>
-
-#include "base/logging.h"
-#include "base/synchronization/condition_variable.h"
-#include "base/synchronization/lock.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/time/time.h"
-
-// -----------------------------------------------------------------------------
-// A WaitableEvent on POSIX is implemented as a wait-list. Currently we don't
-// support cross-process events (where one process can signal an event which
-// others are waiting on). Because of this, we can avoid having one thread per
-// listener in several cases.
-//
-// The WaitableEvent maintains a list of waiters, protected by a lock. Each
-// waiter is either an async wait, in which case we have a Task and the
-// MessageLoop to run it on, or a blocking wait, in which case we have the
-// condition variable to signal.
-//
-// Waiting involves grabbing the lock and adding oneself to the wait list. Async
-// waits can be canceled, which means grabbing the lock and removing oneself
-// from the list.
-//
-// Waiting on multiple events is handled by adding a single, synchronous wait to
-// the wait-list of many events. An event passes a pointer to itself when
-// firing a waiter and so we can store that pointer to find out which event
-// triggered.
-// -----------------------------------------------------------------------------
-
-namespace base {
-
-// -----------------------------------------------------------------------------
-// This is just an abstract base class for waking the two types of waiters
-// -----------------------------------------------------------------------------
-WaitableEvent::WaitableEvent(ResetPolicy reset_policy,
- InitialState initial_state)
- : kernel_(new WaitableEventKernel(reset_policy, initial_state)) {}
-
-WaitableEvent::~WaitableEvent() = default;
-
-void WaitableEvent::Reset() {
- base::AutoLock locked(kernel_->lock_);
- kernel_->signaled_ = false;
-}
-
-void WaitableEvent::Signal() {
- base::AutoLock locked(kernel_->lock_);
-
- if (kernel_->signaled_)
- return;
-
- if (kernel_->manual_reset_) {
- SignalAll();
- kernel_->signaled_ = true;
- } else {
- // In the case of auto reset, if no waiters were woken, we remain
- // signaled.
- if (!SignalOne())
- kernel_->signaled_ = true;
- }
-}
-
-bool WaitableEvent::IsSignaled() {
- base::AutoLock locked(kernel_->lock_);
-
- const bool result = kernel_->signaled_;
- if (result && !kernel_->manual_reset_)
- kernel_->signaled_ = false;
- return result;
-}
-
-// -----------------------------------------------------------------------------
-// Synchronous waits
-
-// -----------------------------------------------------------------------------
-// This is a synchronous waiter. The thread is waiting on the given condition
-// variable and the fired flag in this object.
-// -----------------------------------------------------------------------------
-class SyncWaiter : public WaitableEvent::Waiter {
- public:
- SyncWaiter()
- : fired_(false), signaling_event_(nullptr), lock_(), cv_(&lock_) {}
-
- bool Fire(WaitableEvent* signaling_event) override {
- base::AutoLock locked(lock_);
-
- if (fired_)
- return false;
-
- fired_ = true;
- signaling_event_ = signaling_event;
-
- cv_.Broadcast();
-
- // Unlike AsyncWaiter objects, SyncWaiter objects are stack-allocated on
- // the blocking thread's stack. There is no |delete this;| in Fire. The
- // SyncWaiter object is destroyed when it goes out of scope.
-
- return true;
- }
-
- WaitableEvent* signaling_event() const { return signaling_event_; }
-
- // ---------------------------------------------------------------------------
- // These waiters are always stack allocated and don't delete themselves. Thus
- // there's no problem and the ABA tag is the same as the object pointer.
- // ---------------------------------------------------------------------------
- bool Compare(void* tag) override { return this == tag; }
-
- // ---------------------------------------------------------------------------
- // Called with lock held.
- // ---------------------------------------------------------------------------
- bool fired() const { return fired_; }
-
- // ---------------------------------------------------------------------------
- // During a TimedWait, we need a way to make sure that an auto-reset
- // WaitableEvent doesn't think that this event has been signaled between
- // unlocking it and removing it from the wait-list. Called with lock held.
- // ---------------------------------------------------------------------------
- void Disable() { fired_ = true; }
-
- base::Lock* lock() { return &lock_; }
-
- base::ConditionVariable* cv() { return &cv_; }
-
- private:
- bool fired_;
- WaitableEvent* signaling_event_; // The WaitableEvent which woke us
- base::Lock lock_;
- base::ConditionVariable cv_;
-};
-
-void WaitableEvent::Wait() {
- bool result = TimedWaitUntil(TimeTicks::Max());
- DCHECK(result) << "TimedWait() should never fail with infinite timeout";
-}
-
-bool WaitableEvent::TimedWait(const TimeDelta& wait_delta) {
- // TimeTicks takes care of overflow including the cases when wait_delta
- // is a maximum value.
- return TimedWaitUntil(TimeTicks::Now() + wait_delta);
-}
-
-bool WaitableEvent::TimedWaitUntil(const TimeTicks& end_time) {
- const bool finite_time = !end_time.is_max();
-
- kernel_->lock_.Acquire();
- if (kernel_->signaled_) {
- if (!kernel_->manual_reset_) {
- // In this case we were signaled when we had no waiters. Now that
- // someone has waited upon us, we can automatically reset.
- kernel_->signaled_ = false;
- }
-
- kernel_->lock_.Release();
- return true;
- }
-
- SyncWaiter sw;
- sw.lock()->Acquire();
-
- Enqueue(&sw);
- kernel_->lock_.Release();
- // We are violating locking order here by holding the SyncWaiter lock but not
- // the WaitableEvent lock. However, this is safe because we don't lock @lock_
- // again before unlocking it.
-
- for (;;) {
- const TimeTicks current_time(TimeTicks::Now());
-
- if (sw.fired() || (finite_time && current_time >= end_time)) {
- const bool return_value = sw.fired();
-
- // We can't acquire @lock_ before releasing the SyncWaiter lock (because
- // of locking order), however, in between the two a signal could be fired
- // and @sw would accept it, however we will still return false, so the
- // signal would be lost on an auto-reset WaitableEvent. Thus we call
- // Disable which makes sw::Fire return false.
- sw.Disable();
- sw.lock()->Release();
-
- // This is a bug that has been enshrined in the interface of
- // WaitableEvent now: |Dequeue| is called even when |sw.fired()| is true,
- // even though it'll always return false in that case. However, taking
- // the lock ensures that |Signal| has completed before we return and
- // means that a WaitableEvent can synchronise its own destruction.
- kernel_->lock_.Acquire();
- kernel_->Dequeue(&sw, &sw);
- kernel_->lock_.Release();
-
- return return_value;
- }
-
- if (finite_time) {
- const TimeDelta max_wait(end_time - current_time);
- sw.cv()->TimedWait(max_wait);
- } else {
- sw.cv()->Wait();
- }
- }
-}
-
-// -----------------------------------------------------------------------------
-// Synchronous waiting on multiple objects.
-
-static bool // StrictWeakOrdering
-cmp_fst_addr(const std::pair<WaitableEvent*, unsigned>& a,
- const std::pair<WaitableEvent*, unsigned>& b) {
- return a.first < b.first;
-}
-
-// static
-size_t WaitableEvent::WaitMany(WaitableEvent** raw_waitables, size_t count) {
- DCHECK(count) << "Cannot wait on no events";
-
- // 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
- // map back to the original index values later.
- std::vector<std::pair<WaitableEvent*, size_t>> waitables;
- waitables.reserve(count);
- for (size_t i = 0; i < count; ++i)
- waitables.push_back(std::make_pair(raw_waitables[i], i));
-
- DCHECK_EQ(count, waitables.size());
-
- sort(waitables.begin(), waitables.end(), cmp_fst_addr);
-
- // The set of waitables must be distinct. Since we have just sorted by
- // address, we can check this cheaply by comparing pairs of consecutive
- // elements.
- for (size_t i = 0; i < waitables.size() - 1; ++i) {
- DCHECK(waitables[i].first != waitables[i + 1].first);
- }
-
- SyncWaiter sw;
-
- const size_t r = EnqueueMany(&waitables[0], count, &sw);
- if (r < count) {
- // One of the events is already signaled. The SyncWaiter has not been
- // enqueued anywhere.
- return waitables[r].second;
- }
-
- // At this point, we hold the locks on all the WaitableEvents and we have
- // enqueued our waiter in them all.
- sw.lock()->Acquire();
- // Release the WaitableEvent locks in the reverse order
- for (size_t i = 0; i < count; ++i) {
- waitables[count - (1 + i)].first->kernel_->lock_.Release();
- }
-
- for (;;) {
- if (sw.fired())
- break;
-
- sw.cv()->Wait();
- }
- sw.lock()->Release();
-
- // The address of the WaitableEvent which fired is stored in the SyncWaiter.
- WaitableEvent* const signaled_event = sw.signaling_event();
- // This will store the index of the raw_waitables which fired.
- size_t signaled_index = 0;
-
- // Take the locks of each WaitableEvent in turn (except the signaled one) and
- // remove our SyncWaiter from the wait-list
- for (size_t i = 0; i < count; ++i) {
- if (raw_waitables[i] != signaled_event) {
- raw_waitables[i]->kernel_->lock_.Acquire();
- // There's no possible ABA issue with the address of the SyncWaiter here
- // because it lives on the stack. Thus the tag value is just the pointer
- // value again.
- raw_waitables[i]->kernel_->Dequeue(&sw, &sw);
- raw_waitables[i]->kernel_->lock_.Release();
- } else {
- // By taking this lock here we ensure that |Signal| has completed by the
- // time we return, because |Signal| holds this lock. This matches the
- // behaviour of |Wait| and |TimedWait|.
- raw_waitables[i]->kernel_->lock_.Acquire();
- raw_waitables[i]->kernel_->lock_.Release();
- signaled_index = i;
- }
- }
-
- return signaled_index;
-}
-
-// -----------------------------------------------------------------------------
-// If return value == count:
-// The locks of the WaitableEvents have been taken in order and the Waiter has
-// been enqueued in the wait-list of each. None of the WaitableEvents are
-// currently signaled
-// else:
-// None of the WaitableEvent locks are held. The Waiter has not been enqueued
-// in any of them and the return value is the index of the WaitableEvent which
-// was signaled with the lowest input index from the original WaitMany call.
-// -----------------------------------------------------------------------------
-// static
-size_t WaitableEvent::EnqueueMany(std::pair<WaitableEvent*, size_t>* waitables,
- size_t count,
- Waiter* waiter) {
- size_t winner = count;
- size_t winner_index = count;
- for (size_t i = 0; i < count; ++i) {
- auto& kernel = waitables[i].first->kernel_;
- kernel->lock_.Acquire();
- if (kernel->signaled_ && waitables[i].second < winner) {
- winner = waitables[i].second;
- winner_index = i;
- }
- }
-
- // No events signaled. All locks acquired. Enqueue the Waiter on all of them
- // and return.
- if (winner == count) {
- for (size_t i = 0; i < count; ++i)
- waitables[i].first->Enqueue(waiter);
- return count;
- }
-
- // Unlock in reverse order and possibly clear the chosen winner's signal
- // before returning its index.
- for (auto* w = waitables + count - 1; w >= waitables; --w) {
- auto& kernel = w->first->kernel_;
- if (w->second == winner) {
- if (!kernel->manual_reset_)
- kernel->signaled_ = false;
- }
- kernel->lock_.Release();
- }
-
- return winner_index;
-}
-
-// -----------------------------------------------------------------------------
-
-// -----------------------------------------------------------------------------
-// Private functions...
-
-WaitableEvent::WaitableEventKernel::WaitableEventKernel(
- ResetPolicy reset_policy,
- InitialState initial_state)
- : manual_reset_(reset_policy == ResetPolicy::MANUAL),
- signaled_(initial_state == InitialState::SIGNALED) {}
-
-WaitableEvent::WaitableEventKernel::~WaitableEventKernel() = default;
-
-// -----------------------------------------------------------------------------
-// Wake all waiting waiters. Called with lock held.
-// -----------------------------------------------------------------------------
-bool WaitableEvent::SignalAll() {
- bool signaled_at_least_one = false;
-
- for (std::list<Waiter*>::iterator i = kernel_->waiters_.begin();
- i != kernel_->waiters_.end(); ++i) {
- if ((*i)->Fire(this))
- signaled_at_least_one = true;
- }
-
- kernel_->waiters_.clear();
- return signaled_at_least_one;
-}
-
-// ---------------------------------------------------------------------------
-// Try to wake a single waiter. Return true if one was woken. Called with lock
-// held.
-// ---------------------------------------------------------------------------
-bool WaitableEvent::SignalOne() {
- for (;;) {
- if (kernel_->waiters_.empty())
- return false;
-
- const bool r = (*kernel_->waiters_.begin())->Fire(this);
- kernel_->waiters_.pop_front();
- if (r)
- return true;
- }
-}
-
-// -----------------------------------------------------------------------------
-// Add a waiter to the list of those waiting. Called with lock held.
-// -----------------------------------------------------------------------------
-void WaitableEvent::Enqueue(Waiter* waiter) {
- kernel_->waiters_.push_back(waiter);
-}
-
-// -----------------------------------------------------------------------------
-// Remove a waiter from the list of those waiting. Return true if the waiter was
-// actually removed. Called with lock held.
-// -----------------------------------------------------------------------------
-bool WaitableEvent::WaitableEventKernel::Dequeue(Waiter* waiter, void* tag) {
- for (std::list<Waiter*>::iterator i = waiters_.begin(); i != waiters_.end();
- ++i) {
- if (*i == waiter && (*i)->Compare(tag)) {
- waiters_.erase(i);
- return true;
- }
- }
-
- return false;
-}
-
-// -----------------------------------------------------------------------------
-
-} // namespace base
diff --git a/base/synchronization/waitable_event_win.cc b/base/synchronization/waitable_event_win.cc
deleted file mode 100644
index 1301840..0000000
--- a/base/synchronization/waitable_event_win.cc
+++ /dev/null
@@ -1,141 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/synchronization/waitable_event.h"
-
-#include <stddef.h>
-#include <windows.h>
-
-#include <algorithm>
-#include <utility>
-
-#include "base/logging.h"
-#include "base/numerics/safe_conversions.h"
-#include "base/time/time.h"
-
-namespace base {
-
-WaitableEvent::WaitableEvent(ResetPolicy reset_policy,
- InitialState initial_state)
- : handle_(CreateEvent(nullptr,
- reset_policy == ResetPolicy::MANUAL,
- initial_state == InitialState::SIGNALED,
- nullptr)) {
- // We're probably going to crash anyways if this is ever NULL, so we might as
- // well make our stack reports more informative by crashing here.
- CHECK(handle_.IsValid());
-}
-
-WaitableEvent::WaitableEvent(win::ScopedHandle handle)
- : handle_(std::move(handle)) {
- CHECK(handle_.IsValid()) << "Tried to create WaitableEvent from NULL handle";
-}
-
-WaitableEvent::~WaitableEvent() = default;
-
-void WaitableEvent::Reset() {
- ResetEvent(handle_.Get());
-}
-
-void WaitableEvent::Signal() {
- SetEvent(handle_.Get());
-}
-
-bool WaitableEvent::IsSignaled() {
- DWORD result = WaitForSingleObject(handle_.Get(), 0);
- DCHECK(result == WAIT_OBJECT_0 || result == WAIT_TIMEOUT)
- << "Unexpected WaitForSingleObject result " << result;
- return result == WAIT_OBJECT_0;
-}
-
-void WaitableEvent::Wait() {
- 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.
- DPCHECK(result != WAIT_FAILED);
- DCHECK_EQ(WAIT_OBJECT_0, result);
-}
-
-namespace {
-
-// Helper function called from TimedWait and TimedWaitUntil.
-bool WaitUntil(HANDLE handle, const TimeTicks& now, const TimeTicks& end_time) {
- TimeDelta delta = end_time - now;
- DCHECK_GT(delta, TimeDelta());
-
- do {
- // On Windows, waiting for less than 1 ms results in WaitForSingleObject
- // returning promptly which may result in the caller code spinning.
- // We need to ensure that we specify at least the minimally possible 1 ms
- // delay unless the initial timeout was exactly zero.
- delta = std::max(delta, TimeDelta::FromMilliseconds(1));
- // Truncate the timeout to milliseconds.
- DWORD timeout_ms = saturated_cast<DWORD>(delta.InMilliseconds());
- DWORD result = WaitForSingleObject(handle, timeout_ms);
- DCHECK(result == WAIT_OBJECT_0 || result == WAIT_TIMEOUT)
- << "Unexpected WaitForSingleObject result " << result;
- switch (result) {
- case WAIT_OBJECT_0:
- return true;
- case WAIT_TIMEOUT:
- // TimedWait can time out earlier than the specified |timeout| on
- // Windows. To make this consistent with the posix implementation we
- // should guarantee that TimedWait doesn't return earlier than the
- // specified |max_time| and wait again for the remaining time.
- delta = end_time - TimeTicks::Now();
- break;
- }
- } while (delta > TimeDelta());
- return false;
-}
-
-} // namespace
-
-bool WaitableEvent::TimedWait(const TimeDelta& wait_delta) {
- DCHECK_GE(wait_delta, TimeDelta());
- if (wait_delta.is_zero())
- return IsSignaled();
-
- TimeTicks now(TimeTicks::Now());
- // TimeTicks takes care of overflow including the cases when wait_delta
- // is a maximum value.
- return WaitUntil(handle_.Get(), now, now + wait_delta);
-}
-
-bool WaitableEvent::TimedWaitUntil(const TimeTicks& end_time) {
- if (end_time.is_null())
- return IsSignaled();
-
- TimeTicks now(TimeTicks::Now());
- if (end_time <= now)
- return IsSignaled();
-
- return WaitUntil(handle_.Get(), now, end_time);
-}
-
-// static
-size_t WaitableEvent::WaitMany(WaitableEvent** events, size_t count) {
- DCHECK(count) << "Cannot wait on no events";
-
- HANDLE handles[MAXIMUM_WAIT_OBJECTS];
- CHECK_LE(count, static_cast<size_t>(MAXIMUM_WAIT_OBJECTS))
- << "Can only wait on " << MAXIMUM_WAIT_OBJECTS << " with WaitMany";
-
- for (size_t i = 0; i < count; ++i)
- handles[i] = events[i]->handle();
-
- // The cast is safe because count is small - see the CHECK above.
- DWORD result =
- WaitForMultipleObjects(static_cast<DWORD>(count), handles,
- FALSE, // don't wait for all the objects
- INFINITE); // no timeout
- if (result >= WAIT_OBJECT_0 + count) {
- DPLOG(FATAL) << "WaitForMultipleObjects failed";
- return 0;
- }
-
- return result - WAIT_OBJECT_0;
-}
-
-} // namespace base
diff --git a/base/sys_byteorder.h b/base/sys_byteorder.h
index 767210c..bb7b4c3 100644
--- a/base/sys_byteorder.h
+++ b/base/sys_byteorder.h
@@ -14,7 +14,7 @@
#include <stdint.h>
#include "base/logging.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(COMPILER_MSVC)
#include <stdlib.h>
diff --git a/base/template_util.h b/base/template_util.h
index e92be91..dda9587 100644
--- a/base/template_util.h
+++ b/base/template_util.h
@@ -12,7 +12,7 @@
#include <utility>
#include <vector>
-#include "build_config.h"
+#include "util/build_config.h"
// Some versions of libstdc++ have partial support for type_traits, but misses
// a smaller subset while removing some of the older non-standard stuff. Assume
diff --git a/base/threading/platform_thread.h b/base/threading/platform_thread.h
index 3f1cc75..8b814c5 100644
--- a/base/threading/platform_thread.h
+++ b/base/threading/platform_thread.h
@@ -13,7 +13,7 @@
#include "base/macros.h"
#include "base/time/time.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_WIN)
#include "base/win/windows_types.h"
diff --git a/base/threading/platform_thread_linux.cc b/base/threading/platform_thread_linux.cc
index 66ff4c1..1833c54 100644
--- a/base/threading/platform_thread_linux.cc
+++ b/base/threading/platform_thread_linux.cc
@@ -11,7 +11,7 @@
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if !defined(OS_NACL) && !defined(OS_AIX)
#include <pthread.h>
diff --git a/base/threading/platform_thread_mac.mm b/base/threading/platform_thread_mac.mm
index 2a7cd48..770b618 100644
--- a/base/threading/platform_thread_mac.mm
+++ b/base/threading/platform_thread_mac.mm
@@ -16,7 +16,7 @@
#include "base/logging.h"
#include "base/mac/foundation_util.h"
#include "base/mac/mach_logging.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
diff --git a/base/threading/platform_thread_posix.cc b/base/threading/platform_thread_posix.cc
index bfec23c..42fbce5 100644
--- a/base/threading/platform_thread_posix.cc
+++ b/base/threading/platform_thread_posix.cc
@@ -16,7 +16,7 @@
#include <memory>
#include "base/logging.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_LINUX)
#include <sys/syscall.h>
diff --git a/base/threading/platform_thread_win.cc b/base/threading/platform_thread_win.cc
index 95accd5..349a6cf 100644
--- a/base/threading/platform_thread_win.cc
+++ b/base/threading/platform_thread_win.cc
@@ -155,7 +155,7 @@
// static
bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
return CreateThreadInternal(stack_size, delegate, nullptr /* non-joinable */
- );
+ );
}
// static
diff --git a/base/time/time.cc b/base/time/time.cc
index 8708c49..13b2343 100644
--- a/base/time/time.cc
+++ b/base/time/time.cc
@@ -15,7 +15,7 @@
#include "base/no_destructor.h"
#include "base/strings/stringprintf.h"
#include "base/time/time_override.h"
-#include "build_config.h"
+#include "util/build_config.h"
namespace base {
@@ -272,39 +272,6 @@
return time;
}
-Time Time::LocalMidnight() const {
- Exploded exploded;
- LocalExplode(&exploded);
- exploded.hour = 0;
- exploded.minute = 0;
- exploded.second = 0;
- exploded.millisecond = 0;
- Time out_time;
- if (FromLocalExploded(exploded, &out_time))
- return out_time;
- // This function must not fail.
- NOTREACHED();
- return Time();
-}
-
-// static
-bool Time::ExplodedMostlyEquals(const Exploded& lhs, const Exploded& rhs) {
- return lhs.year == rhs.year && lhs.month == rhs.month &&
- lhs.day_of_month == rhs.day_of_month && lhs.hour == rhs.hour &&
- lhs.minute == rhs.minute && lhs.second == rhs.second &&
- lhs.millisecond == rhs.millisecond;
-}
-
-std::ostream& operator<<(std::ostream& os, Time time) {
- Time::Exploded exploded;
- time.UTCExplode(&exploded);
- // Use StringPrintf because iostreams formatting is painful.
- return os << StringPrintf(
- "%04d-%02d-%02d %02d:%02d:%02d.%03d UTC", exploded.year,
- exploded.month, exploded.day_of_month, exploded.hour,
- exploded.minute, exploded.second, exploded.millisecond);
-}
-
// TimeTicks ------------------------------------------------------------------
// static
diff --git a/base/time/time.h b/base/time/time.h
index 1243ac4..47d7536 100644
--- a/base/time/time.h
+++ b/base/time/time.h
@@ -60,7 +60,7 @@
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/numerics/safe_math.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_MACOSX)
#include <CoreFoundation/CoreFoundation.h>
@@ -588,29 +588,6 @@
static double GetHighResolutionTimerUsage();
#endif // defined(OS_WIN)
- // Converts an exploded structure representing either the local time or UTC
- // into a Time class. Returns false on a failure when, for example, a day of
- // month is set to 31 on a 28-30 day month. Returns Time(0) on overflow.
- static bool FromUTCExploded(const Exploded& exploded,
- Time* time) WARN_UNUSED_RESULT {
- return FromExploded(false, exploded, time);
- }
- static bool FromLocalExploded(const Exploded& exploded,
- Time* time) WARN_UNUSED_RESULT {
- return FromExploded(true, exploded, time);
- }
-
- // Fills the given exploded structure with either the local time or UTC from
- // this time structure (containing UTC).
- void UTCExplode(Exploded* exploded) const { return Explode(false, exploded); }
- void LocalExplode(Exploded* exploded) const {
- return Explode(true, exploded);
- }
-
- // Rounds this time down to the nearest day in local time. It will represent
- // midnight on that day.
- Time LocalMidnight() const;
-
// Converts an integer value representing Time to a class. This may be used
// when deserializing a |Time| structure, using a value known to be
// compatible. It is not provided as a constructor because the integer type
@@ -624,22 +601,6 @@
friend class time_internal::TimeBase<Time>;
constexpr explicit Time(int64_t us) : TimeBase(us) {}
-
- // Explodes the given time to either local time |is_local = true| or UTC
- // |is_local = false|.
- void Explode(bool is_local, Exploded* exploded) const;
-
- // Unexplodes a given time assuming the source is either local time
- // |is_local = true| or UTC |is_local = false|. Function returns false on
- // failure and sets |time| to Time(0). Otherwise returns true and sets |time|
- // to non-exploded time.
- static bool FromExploded(bool is_local,
- const Exploded& exploded,
- Time* time) WARN_UNUSED_RESULT;
-
- // Comparison does not consider |day_of_week| when doing the operation.
- static bool ExplodedMostlyEquals(const Exploded& lhs,
- const Exploded& rhs) WARN_UNUSED_RESULT;
};
// static
diff --git a/base/time/time_exploded_posix.cc b/base/time/time_exploded_posix.cc
deleted file mode 100644
index c9ec2df..0000000
--- a/base/time/time_exploded_posix.cc
+++ /dev/null
@@ -1,231 +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/time.h"
-
-#include <stdint.h>
-#include <sys/time.h>
-#include <time.h>
-#if defined(OS_ANDROID) && !defined(__LP64__)
-#include <time64.h>
-#endif
-#include <unistd.h>
-
-#include <limits>
-
-#include "base/numerics/safe_math.h"
-#include "base/synchronization/lock.h"
-#include "build_config.h"
-
-#if defined(OS_MACOSX)
-static_assert(sizeof(time_t) >= 8, "Y2038 problem!");
-#endif
-
-namespace {
-
-// This prevents a crash on traversing the environment global and looking up
-// the 'TZ' variable in libc. See: crbug.com/390567.
-base::Lock* GetSysTimeToTimeStructLock() {
- static auto* lock = new base::Lock();
- return lock;
-}
-
-// Define a system-specific SysTime that wraps either to a time_t or
-// a time64_t depending on the host system, and associated convertion.
-// See crbug.com/162007
-typedef time_t SysTime;
-
-SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) {
- base::AutoLock locked(*GetSysTimeToTimeStructLock());
- if (is_local)
- return mktime(timestruct);
- else
- return timegm(timestruct);
-}
-
-void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
- base::AutoLock locked(*GetSysTimeToTimeStructLock());
- if (is_local)
- localtime_r(&t, timestruct);
- else
- gmtime_r(&t, timestruct);
-}
-
-} // namespace
-
-namespace base {
-
-void Time::Explode(bool is_local, Exploded* exploded) const {
- // Time stores times with microsecond resolution, but Exploded only carries
- // millisecond resolution, so begin by being lossy. Adjust from Windows
- // epoch (1601) to Unix epoch (1970);
- int64_t microseconds = us_ - kTimeTToMicrosecondsOffset;
- // The following values are all rounded towards -infinity.
- int64_t milliseconds; // Milliseconds since epoch.
- SysTime seconds; // Seconds since epoch.
- int millisecond; // Exploded millisecond value (0-999).
- if (microseconds >= 0) {
- // Rounding towards -infinity <=> rounding towards 0, in this case.
- milliseconds = microseconds / kMicrosecondsPerMillisecond;
- seconds = milliseconds / kMillisecondsPerSecond;
- millisecond = milliseconds % kMillisecondsPerSecond;
- } else {
- // Round these *down* (towards -infinity).
- milliseconds = (microseconds - kMicrosecondsPerMillisecond + 1) /
- kMicrosecondsPerMillisecond;
- seconds =
- (milliseconds - kMillisecondsPerSecond + 1) / kMillisecondsPerSecond;
- // Make this nonnegative (and between 0 and 999 inclusive).
- millisecond = milliseconds % kMillisecondsPerSecond;
- if (millisecond < 0)
- millisecond += kMillisecondsPerSecond;
- }
-
- struct tm timestruct;
- SysTimeToTimeStruct(seconds, ×truct, is_local);
-
- exploded->year = timestruct.tm_year + 1900;
- exploded->month = timestruct.tm_mon + 1;
- exploded->day_of_week = timestruct.tm_wday;
- exploded->day_of_month = timestruct.tm_mday;
- exploded->hour = timestruct.tm_hour;
- exploded->minute = timestruct.tm_min;
- exploded->second = timestruct.tm_sec;
- exploded->millisecond = millisecond;
-}
-
-// static
-bool Time::FromExploded(bool is_local, const Exploded& exploded, Time* time) {
- CheckedNumeric<int> month = exploded.month;
- month--;
- CheckedNumeric<int> year = exploded.year;
- year -= 1900;
- if (!month.IsValid() || !year.IsValid()) {
- *time = Time(0);
- return false;
- }
-
- struct tm timestruct;
- timestruct.tm_sec = exploded.second;
- timestruct.tm_min = exploded.minute;
- timestruct.tm_hour = exploded.hour;
- timestruct.tm_mday = exploded.day_of_month;
- timestruct.tm_mon = month.ValueOrDie();
- timestruct.tm_year = year.ValueOrDie();
- timestruct.tm_wday = exploded.day_of_week; // mktime/timegm ignore this
- timestruct.tm_yday = 0; // mktime/timegm ignore this
- timestruct.tm_isdst = -1; // attempt to figure it out
-#if !defined(OS_NACL) && !defined(OS_SOLARIS) && !defined(OS_AIX)
- timestruct.tm_gmtoff = 0; // not a POSIX field, so mktime/timegm ignore
- timestruct.tm_zone = nullptr; // not a POSIX field, so mktime/timegm ignore
-#endif
-
- SysTime seconds;
-
- // Certain exploded dates do not really exist due to daylight saving times,
- // and this causes mktime() to return implementation-defined values when
- // tm_isdst is set to -1. On Android, the function will return -1, while the
- // C libraries of other platforms typically return a liberally-chosen value.
- // Handling this requires the special code below.
-
- // SysTimeFromTimeStruct() modifies the input structure, save current value.
- struct tm timestruct0 = timestruct;
-
- seconds = SysTimeFromTimeStruct(×truct, is_local);
- if (seconds == -1) {
- // Get the time values with tm_isdst == 0 and 1, then select the closest one
- // to UTC 00:00:00 that isn't -1.
- timestruct = timestruct0;
- timestruct.tm_isdst = 0;
- int64_t seconds_isdst0 = SysTimeFromTimeStruct(×truct, is_local);
-
- timestruct = timestruct0;
- timestruct.tm_isdst = 1;
- int64_t seconds_isdst1 = SysTimeFromTimeStruct(×truct, is_local);
-
- // seconds_isdst0 or seconds_isdst1 can be -1 for some timezones.
- // E.g. "CLST" (Chile Summer Time) returns -1 for 'tm_isdt == 1'.
- if (seconds_isdst0 < 0)
- seconds = seconds_isdst1;
- else if (seconds_isdst1 < 0)
- seconds = seconds_isdst0;
- else
- seconds = std::min(seconds_isdst0, seconds_isdst1);
- }
-
- // Handle overflow. Clamping the range to what mktime and timegm might
- // return is the best that can be done here. It's not ideal, but it's better
- // than failing here or ignoring the overflow case and treating each time
- // overflow as one second prior to the epoch.
- int64_t milliseconds = 0;
- if (seconds == -1 && (exploded.year < 1969 || exploded.year > 1970)) {
- // If exploded.year is 1969 or 1970, take -1 as correct, with the
- // time indicating 1 second prior to the epoch. (1970 is allowed to handle
- // time zone and DST offsets.) Otherwise, return the most future or past
- // time representable. Assumes the time_t epoch is 1970-01-01 00:00:00 UTC.
- //
- // The minimum and maximum representible times that mktime and timegm could
- // return are used here instead of values outside that range to allow for
- // proper round-tripping between exploded and counter-type time
- // representations in the presence of possible truncation to time_t by
- // division and use with other functions that accept time_t.
- //
- // When representing the most distant time in the future, add in an extra
- // 999ms to avoid the time being less than any other possible value that
- // this function can return.
-
- // On Android, SysTime is int64_t, special care must be taken to avoid
- // overflows.
- const int64_t min_seconds = (sizeof(SysTime) < sizeof(int64_t))
- ? std::numeric_limits<SysTime>::min()
- : std::numeric_limits<int32_t>::min();
- const int64_t max_seconds = (sizeof(SysTime) < sizeof(int64_t))
- ? std::numeric_limits<SysTime>::max()
- : std::numeric_limits<int32_t>::max();
- if (exploded.year < 1969) {
- milliseconds = min_seconds * kMillisecondsPerSecond;
- } else {
- milliseconds = max_seconds * kMillisecondsPerSecond;
- milliseconds += (kMillisecondsPerSecond - 1);
- }
- } else {
- base::CheckedNumeric<int64_t> checked_millis = seconds;
- checked_millis *= kMillisecondsPerSecond;
- checked_millis += exploded.millisecond;
- if (!checked_millis.IsValid()) {
- *time = base::Time(0);
- return false;
- }
- milliseconds = checked_millis.ValueOrDie();
- }
-
- // Adjust from Unix (1970) to Windows (1601) epoch avoiding overflows.
- base::CheckedNumeric<int64_t> checked_microseconds_win_epoch = milliseconds;
- checked_microseconds_win_epoch *= kMicrosecondsPerMillisecond;
- checked_microseconds_win_epoch += kTimeTToMicrosecondsOffset;
- if (!checked_microseconds_win_epoch.IsValid()) {
- *time = base::Time(0);
- return false;
- }
- base::Time converted_time(checked_microseconds_win_epoch.ValueOrDie());
-
- // If |exploded.day_of_month| is set to 31 on a 28-30 day month, it will
- // return the first day of the next month. Thus round-trip the time and
- // compare the initial |exploded| with |utc_to_exploded| time.
- base::Time::Exploded to_exploded;
- if (!is_local)
- converted_time.UTCExplode(&to_exploded);
- else
- converted_time.LocalExplode(&to_exploded);
-
- if (ExplodedMostlyEquals(to_exploded, exploded)) {
- *time = converted_time;
- return true;
- }
-
- *time = Time(0);
- return false;
-}
-
-} // namespace base
diff --git a/base/time/time_mac.cc b/base/time/time_mac.cc
index 7b6452e..2d024e9 100644
--- a/base/time/time_mac.cc
+++ b/base/time/time_mac.cc
@@ -22,7 +22,7 @@
#include "base/macros.h"
#include "base/numerics/safe_conversions.h"
#include "base/time/time_override.h"
-#include "build_config.h"
+#include "util/build_config.h"
#if defined(OS_IOS)
#include <time.h>
diff --git a/base/time/time_now_posix.cc b/base/time/time_now_posix.cc
index f19a19f..a3f4602 100644
--- a/base/time/time_now_posix.cc
+++ b/base/time/time_now_posix.cc
@@ -15,7 +15,7 @@
#include "base/logging.h"
#include "base/numerics/safe_math.h"
#include "base/time/time_override.h"
-#include "build_config.h"
+#include "util/build_config.h"
// Ensure the Fuchsia and Mac builds do not include this module. Instead,
// non-POSIX implementation is used for sampling the system clocks.
diff --git a/base/time/time_win.cc b/base/time/time_win.cc
index 438049d..8632369 100644
--- a/base/time/time_win.cc
+++ b/base/time/time_win.cc
@@ -37,9 +37,10 @@
#include <mmsystem.h>
#include <stdint.h>
+#include <mutex>
+
#include "base/bit_cast.h"
#include "base/logging.h"
-#include "base/synchronization/lock.h"
#include "base/threading/platform_thread.h"
#include "base/time/time_override.h"
@@ -101,8 +102,8 @@
// is used to calculate the cumulative usage.
TimeTicks g_high_res_timer_last_activation;
// The lock to control access to the above two variables.
-Lock* GetHighResLock() {
- static auto* lock = new Lock();
+std::mutex* GetHighResLock() {
+ static auto* lock = new std::mutex();
return lock;
}
@@ -190,7 +191,7 @@
// static
void Time::EnableHighResolutionTimer(bool enable) {
- AutoLock lock(*GetHighResLock());
+ std::lock_guard<std::mutex> lock(*GetHighResLock());
if (g_high_res_timer_enabled == enable)
return;
g_high_res_timer_enabled = enable;
@@ -217,7 +218,7 @@
// called.
const uint32_t max = std::numeric_limits<uint32_t>::max();
- AutoLock lock(*GetHighResLock());
+ std::lock_guard<std::mutex> lock(*GetHighResLock());
UINT period = g_high_res_timer_enabled ? kMinTimerIntervalHighResMs
: kMinTimerIntervalLowResMs;
if (activating) {
@@ -241,13 +242,13 @@
// static
bool Time::IsHighResolutionTimerInUse() {
- AutoLock lock(*GetHighResLock());
+ std::lock_guard<std::mutex> lock(*GetHighResLock());
return g_high_res_timer_enabled && g_high_res_timer_count > 0;
}
// static
void Time::ResetHighResolutionTimerUsage() {
- AutoLock lock(*GetHighResLock());
+ std::lock_guard<std::mutex> lock(*GetHighResLock());
g_high_res_timer_usage = TimeDelta();
g_high_res_timer_usage_start = subtle::TimeTicksNowIgnoringOverride();
if (g_high_res_timer_count > 0)
@@ -256,7 +257,7 @@
// static
double Time::GetHighResolutionTimerUsage() {
- AutoLock lock(*GetHighResLock());
+ std::lock_guard<std::mutex> lock(*GetHighResLock());
TimeTicks now = subtle::TimeTicksNowIgnoringOverride();
TimeDelta elapsed_time = now - g_high_res_timer_usage_start;
if (elapsed_time.is_zero()) {
@@ -274,87 +275,6 @@
return used_time.InMillisecondsF() / elapsed_time.InMillisecondsF() * 100;
}
-// static
-bool Time::FromExploded(bool is_local, const Exploded& exploded, Time* time) {
- // Create the system struct representing our exploded time. It will either be
- // in local time or UTC.If casting from int to WORD results in overflow,
- // fail and return Time(0).
- SYSTEMTIME st;
- if (!SafeConvertToWord(exploded.year, &st.wYear) ||
- !SafeConvertToWord(exploded.month, &st.wMonth) ||
- !SafeConvertToWord(exploded.day_of_week, &st.wDayOfWeek) ||
- !SafeConvertToWord(exploded.day_of_month, &st.wDay) ||
- !SafeConvertToWord(exploded.hour, &st.wHour) ||
- !SafeConvertToWord(exploded.minute, &st.wMinute) ||
- !SafeConvertToWord(exploded.second, &st.wSecond) ||
- !SafeConvertToWord(exploded.millisecond, &st.wMilliseconds)) {
- *time = Time(0);
- return false;
- }
-
- FILETIME ft;
- bool success = true;
- // Ensure that it's in UTC.
- if (is_local) {
- SYSTEMTIME utc_st;
- success = TzSpecificLocalTimeToSystemTime(nullptr, &st, &utc_st) &&
- SystemTimeToFileTime(&utc_st, &ft);
- } else {
- success = !!SystemTimeToFileTime(&st, &ft);
- }
-
- if (!success) {
- *time = Time(0);
- return false;
- }
-
- *time = Time(FileTimeToMicroseconds(ft));
- return true;
-}
-
-void Time::Explode(bool is_local, Exploded* exploded) const {
- if (us_ < 0LL) {
- // We are not able to convert it to FILETIME.
- ZeroMemory(exploded, sizeof(*exploded));
- return;
- }
-
- // FILETIME in UTC.
- FILETIME utc_ft;
- MicrosecondsToFileTime(us_, &utc_ft);
-
- // FILETIME in local time if necessary.
- bool success = true;
- // FILETIME in SYSTEMTIME (exploded).
- SYSTEMTIME st = {0};
- if (is_local) {
- SYSTEMTIME utc_st;
- // We don't use FileTimeToLocalFileTime here, since it uses the current
- // settings for the time zone and daylight saving time. Therefore, if it is
- // daylight saving time, it will take daylight saving time into account,
- // even if the time you are converting is in standard time.
- success = FileTimeToSystemTime(&utc_ft, &utc_st) &&
- SystemTimeToTzSpecificLocalTime(nullptr, &utc_st, &st);
- } else {
- success = !!FileTimeToSystemTime(&utc_ft, &st);
- }
-
- if (!success) {
- NOTREACHED() << "Unable to convert time, don't know why";
- ZeroMemory(exploded, sizeof(*exploded));
- return;
- }
-
- exploded->year = st.wYear;
- exploded->month = st.wMonth;
- exploded->day_of_week = st.wDayOfWeek;
- exploded->day_of_month = st.wDay;
- exploded->hour = st.wHour;
- exploded->minute = st.wMinute;
- exploded->second = st.wSecond;
- exploded->millisecond = st.wMilliseconds;
-}
-
// TimeTicks ------------------------------------------------------------------
namespace {
@@ -467,7 +387,7 @@
return g_time_ticks_now_ignoring_override_function();
}
-} // namespace base
+} // namespace
namespace subtle {
TimeTicks TimeTicksNowIgnoringOverride() {