diff options
author | Kristian Monsen <kristianm@google.com> | 2011-05-24 16:24:13 +0100 |
---|---|---|
committer | Kristian Monsen <kristianm@google.com> | 2011-05-25 14:13:32 +0100 |
commit | 3f50c38dc070f4bb515c1b64450dae14f316474e (patch) | |
tree | 29f309f9534e05c47244eedb438fc612578d133b /base | |
parent | e23bef148f7be2bdf9c3cb2cd3aa5ceebf1190fb (diff) | |
download | external_chromium-3f50c38dc070f4bb515c1b64450dae14f316474e.zip external_chromium-3f50c38dc070f4bb515c1b64450dae14f316474e.tar.gz external_chromium-3f50c38dc070f4bb515c1b64450dae14f316474e.tar.bz2 |
Merge Chromium at r10.0.634.0: Initial merge by git.
Change-Id: Iac2af492818d119bcc2562eb5fdabf5ab0b6df9c
Diffstat (limited to 'base')
188 files changed, 1875 insertions, 2150 deletions
diff --git a/base/at_exit.h b/base/at_exit.h index fa0f277..35c96b9 100644 --- a/base/at_exit.h +++ b/base/at_exit.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. @@ -28,13 +28,6 @@ namespace base { // callbacks and singleton destructors will be called. class AtExitManager { - protected: - // This constructor will allow this instance of AtExitManager to be created - // even if one already exists. This should only be used for testing! - // AtExitManagers are kept on a global stack, and it will be removed during - // destruction. This allows you to shadow another AtExitManager. - explicit AtExitManager(bool shadow); - public: typedef void (*AtExitCallbackType)(void*); @@ -52,6 +45,13 @@ class AtExitManager { // is possible to register new callbacks after calling this function. static void ProcessCallbacksNow(); + protected: + // This constructor will allow this instance of AtExitManager to be created + // even if one already exists. This should only be used for testing! + // AtExitManagers are kept on a global stack, and it will be removed during + // destruction. This allows you to shadow another AtExitManager. + explicit AtExitManager(bool shadow); + private: struct CallbackAndParam { CallbackAndParam(AtExitCallbackType func, void* param) diff --git a/base/base.gyp b/base/base.gyp index 075561b..6dc450c 100644 --- a/base/base.gyp +++ b/base/base.gyp @@ -1,4 +1,4 @@ -# Copyright (c) 2010 The Chromium Authors. All rights reserved. +# 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. @@ -65,9 +65,7 @@ 'base64_unittest.cc', 'bits_unittest.cc', 'callback_unittest.cc', - 'cancellation_flag_unittest.cc', 'command_line_unittest.cc', - 'condition_variable_unittest.cc', 'crypto/encryptor_unittest.cc', 'crypto/rsa_private_key_unittest.cc', 'crypto/rsa_private_key_nss_unittest.cc', @@ -97,22 +95,18 @@ 'lazy_instance_unittest.cc', 'linked_list_unittest.cc', 'linked_ptr_unittest.cc', - 'lock_unittest.cc', 'logging_unittest.cc', - 'mac_util_unittest.mm', + 'mac/mac_util_unittest.mm', 'message_loop_proxy_impl_unittest.cc', 'message_loop_unittest.cc', 'message_pump_glib_unittest.cc', 'metrics/field_trial_unittest.cc', 'metrics/histogram_unittest.cc', 'metrics/stats_table_unittest.cc', - 'non_thread_safe_unittest.cc', - 'object_watcher_unittest.cc', 'observer_list_unittest.cc', 'path_service_unittest.cc', 'pickle_unittest.cc', 'platform_file_unittest.cc', - 'platform_thread_unittest.cc', 'pr_time_unittest.cc', 'process_util_unittest.cc', 'process_util_unittest_mac.h', @@ -125,7 +119,6 @@ 'sha1_unittest.cc', 'sha2_unittest.cc', 'shared_memory_unittest.cc', - 'simple_thread_unittest.cc', 'singleton_unittest.cc', 'stack_container_unittest.cc', 'string16_unittest.cc', @@ -136,16 +129,27 @@ 'string_util_unittest.cc', 'stringize_macros_unittest.cc', 'stringprintf_unittest.cc', + 'synchronization/cancellation_flag_unittest.cc', + 'synchronization/condition_variable_unittest.cc', + 'synchronization/lock_unittest.cc', + 'synchronization/waitable_event_unittest.cc', + 'synchronization/waitable_event_watcher_unittest.cc', 'sys_info_unittest.cc', 'sys_string_conversions_mac_unittest.mm', 'sys_string_conversions_unittest.cc', 'task_queue_unittest.cc', 'task_unittest.cc', - 'thread_checker_unittest.cc', - 'thread_collision_warner_unittest.cc', - 'thread_local_storage_unittest.cc', - 'thread_local_unittest.cc', - 'thread_unittest.cc', + 'threading/non_thread_safe_unittest.cc', + 'threading/platform_thread_unittest.cc', + 'threading/simple_thread_unittest.cc', + 'threading/thread_checker_unittest.cc', + 'threading/thread_collision_warner_unittest.cc', + 'threading/thread_local_storage_unittest.cc', + 'threading/thread_local_unittest.cc', + 'threading/thread_unittest.cc', + 'threading/watchdog_unittest.cc', + 'threading/worker_pool_posix_unittest.cc', + 'threading/worker_pool_unittest.cc', 'time_unittest.cc', 'time_win_unittest.cc', 'timer_unittest.cc', @@ -157,22 +161,18 @@ 'values_unittest.cc', 'version_unittest.cc', 'vlog_unittest.cc', - 'waitable_event_unittest.cc', - 'waitable_event_watcher_unittest.cc', - 'watchdog_unittest.cc', 'weak_ptr_unittest.cc', - 'win_util_unittest.cc', 'win/event_trace_consumer_unittest.cc', 'win/event_trace_controller_unittest.cc', 'win/event_trace_provider_unittest.cc', 'win/i18n_unittest.cc', + 'win/object_watcher_unittest.cc', 'win/pe_image_unittest.cc', 'win/registry_unittest.cc', 'win/scoped_bstr_unittest.cc', 'win/scoped_comptr_unittest.cc', 'win/scoped_variant_unittest.cc', - 'worker_pool_posix_unittest.cc', - 'worker_pool_unittest.cc', + 'win/win_util_unittest.cc', ], 'dependencies': [ 'base', @@ -217,14 +217,13 @@ 'sources!': [ 'dir_reader_posix_unittest.cc', 'file_descriptor_shuffle_unittest.cc', - 'worker_pool_posix_unittest.cc', + 'threading/worker_pool_posix_unittest.cc', ], }, { # OS != "win" 'sources/': [ ['exclude', '^win/'], ], 'sources!': [ - 'object_watcher_unittest.cc', 'system_monitor_unittest.cc', 'time_win_unittest.cc', 'trace_event_win_unittest.cc', diff --git a/base/base.gypi b/base/base.gypi index 3eaedfa..f241967 100644 --- a/base/base.gypi +++ b/base/base.gypi @@ -1,4 +1,4 @@ -# Copyright (c) 2010 The Chromium Authors. All rights reserved. +# 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. @@ -39,21 +39,13 @@ 'bits.h', 'bzip2_error_handler.cc', 'callback.h', - 'cancellation_flag.cc', - 'cancellation_flag.h', 'command_line.cc', 'command_line.h', 'compiler_specific.h', - 'condition_variable.h', - 'condition_variable_posix.cc', - 'condition_variable_win.cc', 'cpu.cc', 'cpu.h', - 'debug_on_start.cc', - 'debug_on_start.h', - 'debug_util.cc', - 'debug_util.h', - 'debug_util_mac.cc', + 'debug/debug_on_start_win.cc', + 'debug/debug_on_start_win.h', 'debug/debugger.cc', 'debug/debugger.h', 'debug/debugger_posix.cc', @@ -106,17 +98,15 @@ 'lazy_instance.h', 'linked_list.h', 'linked_ptr.h', - 'lock.cc', 'lock.h', - 'lock_impl.h', - 'lock_impl_posix.cc', - 'lock_impl_win.cc', 'logging.cc', 'logging.h', 'logging_win.cc', - 'mac_util.h', - 'mac_util.mm', 'mac/cocoa_protocols.h', + 'mac/mac_util.h', + 'mac/mac_util.mm', + 'mac/os_crash_dumps.cc', + 'mac/os_crash_dumps.h', 'mac/scoped_aedesc.h', 'mac/scoped_cftyperef.h', 'mac/scoped_nsautorelease_pool.h', @@ -151,24 +141,16 @@ 'native_library_linux.cc', 'native_library_mac.mm', 'native_library_win.cc', - 'non_thread_safe.cc', - 'non_thread_safe.h', - 'nullable_string16.h', - 'object_watcher.cc', - 'object_watcher.h', 'observer_list.h', 'observer_list_threadsafe.h', 'path_service.cc', 'path_service.h', 'pickle.cc', 'pickle.h', + 'platform_file.cc', 'platform_file.h', 'platform_file_posix.cc', 'platform_file_win.cc', - 'platform_thread.h', - 'platform_thread_mac.mm', - 'platform_thread_posix.cc', - 'platform_thread_win.cc', 'port.h', 'process.h', 'process_linux.cc', @@ -209,8 +191,6 @@ 'shared_memory.h', 'shared_memory_posix.cc', 'shared_memory_win.cc', - 'simple_thread.cc', - 'simple_thread.h', 'singleton.h', 'spin_wait.h', 'stack_container.h', @@ -228,6 +208,22 @@ 'stringize_macros.h', 'stringprintf.cc', 'stringprintf.h', + 'synchronization/cancellation_flag.cc', + 'synchronization/cancellation_flag.h', + 'synchronization/condition_variable.h', + 'synchronization/condition_variable_posix.cc', + 'synchronization/condition_variable_win.cc', + 'synchronization/lock.cc', + 'synchronization/lock.h', + 'synchronization/lock_impl.h', + 'synchronization/lock_impl_posix.cc', + 'synchronization/lock_impl_win.cc', + 'synchronization/waitable_event.h', + 'synchronization/waitable_event_posix.cc', + 'synchronization/waitable_event_watcher.h', + 'synchronization/waitable_event_watcher_posix.cc', + 'synchronization/waitable_event_watcher_win.cc', + 'synchronization/waitable_event_win.cc', 'sys_info.h', 'sys_info_chromeos.cc', 'sys_info_freebsd.cc', @@ -245,20 +241,34 @@ 'task_queue.cc', 'task_queue.h', 'template_util.h', - 'thread.cc', - 'thread.h', - 'thread_checker.cc', - 'thread_checker.h', - 'thread_collision_warner.cc', - 'thread_collision_warner.h', - 'thread_local.h', - 'thread_local_posix.cc', - 'thread_local_storage.h', - 'thread_local_storage_posix.cc', - 'thread_local_storage_win.cc', - 'thread_local_win.cc', - 'thread_restrictions.h', - 'thread_restrictions.cc', + 'threading/non_thread_safe.cc', + 'threading/non_thread_safe.h', + 'threading/platform_thread.h', + 'threading/platform_thread_mac.mm', + 'threading/platform_thread_posix.cc', + 'threading/platform_thread_win.cc', + 'threading/simple_thread.cc', + 'threading/simple_thread.h', + 'threading/thread.cc', + 'threading/thread.h', + 'threading/thread_checker.cc', + 'threading/thread_checker.h', + 'threading/thread_collision_warner.cc', + 'threading/thread_collision_warner.h', + 'threading/thread_local.h', + 'threading/thread_local_posix.cc', + 'threading/thread_local_storage.h', + 'threading/thread_local_storage_posix.cc', + 'threading/thread_local_storage_win.cc', + 'threading/thread_local_win.cc', + 'threading/thread_restrictions.h', + 'threading/thread_restrictions.cc', + 'threading/watchdog.cc', + 'threading/watchdog.h', + 'threading/worker_pool.h', + 'threading/worker_pool_posix.cc', + 'threading/worker_pool_posix.h', + 'threading/worker_pool_win.cc', 'time.cc', 'time.h', 'time_win.cc', @@ -283,18 +293,12 @@ 'version.h', 'vlog.cc', 'vlog.h', - 'waitable_event.h', - 'waitable_event_posix.cc', - 'waitable_event_watcher.h', - 'waitable_event_watcher_posix.cc', - 'waitable_event_watcher_win.cc', - 'waitable_event_win.cc', - 'watchdog.cc', - 'watchdog.h', 'weak_ptr.cc', 'weak_ptr.h', 'win/i18n.cc', 'win/i18n.h', + 'win/object_watcher.cc', + 'win/object_watcher.h', 'win/pe_image.cc', 'win/event_trace_consumer.h', 'win/event_trace_controller.cc', @@ -304,7 +308,6 @@ 'win/pe_image.h', 'win/registry.cc', 'win/registry.h', - 'win/rgs_helper.h', 'win/scoped_bstr.cc', 'win/scoped_bstr.h', 'win/scoped_comptr.h', @@ -314,14 +317,10 @@ 'win/scoped_hglobal.h', 'win/scoped_variant.cc', 'win/scoped_variant.h', + 'win/win_util.cc', + 'win/win_util.h', 'win/windows_version.cc', 'win/windows_version.h', - 'win_util.cc', - 'win_util.h', - 'worker_pool.h', - 'worker_pool_posix.cc', - 'worker_pool_posix.h', - 'worker_pool_win.cc', 'nix/xdg_util.h', 'nix/xdg_util.cc', ], @@ -352,8 +351,6 @@ 'gtk_util.cc', 'gtk_util.h', 'linux_util.cc', - 'setproctitle_linux.c', - 'setproctitle_linux.h', ], }, ], @@ -515,10 +512,8 @@ 'cpu.cc', 'crypto/capi_util.h', 'crypto/capi_util.cc', - 'debug_on_start.cc', 'event_recorder.cc', 'file_version_info.cc', - 'object_watcher.cc', 'pe_image.cc', 'registry.cc', 'resource_util.cc', @@ -634,8 +629,6 @@ 'nss_util.h', 'openssl_util.cc', 'openssl_util.h', - 'setproctitle_linux.c', - 'setproctitle_linux.h', 'sha2.cc', 'sha2.h', 'sha2_openssl.cc', diff --git a/base/base_paths_mac.mm b/base/base_paths_mac.mm index 97413ba..1210834 100644 --- a/base/base_paths_mac.mm +++ b/base/base_paths_mac.mm @@ -11,7 +11,7 @@ #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" -#include "base/mac_util.h" +#include "base/mac/mac_util.h" #include "base/path_service.h" #include "base/string_util.h" @@ -48,15 +48,15 @@ bool PathProviderMac(int key, FilePath* result) { return GetNSExecutablePath(result); } case base::DIR_CACHE: - return mac_util::GetUserDirectory(NSCachesDirectory, result); + return base::mac::GetUserDirectory(NSCachesDirectory, result); case base::DIR_APP_DATA: - return mac_util::GetUserDirectory(NSApplicationSupportDirectory, result); + return base::mac::GetUserDirectory(NSApplicationSupportDirectory, result); case base::DIR_SOURCE_ROOT: { // Go through PathService to catch overrides. if (PathService::Get(base::FILE_EXE, result)) { // Start with the executable's directory. *result = result->DirName(); - if (mac_util::AmIBundled()) { + if (base::mac::AmIBundled()) { // The bundled app executables (Chromium, TestShell, etc) live five // levels down, eg: // src/xcodebuild/{Debug|Release}/Chromium.app/Contents/MacOS/Chromium diff --git a/base/base_switches.cc b/base/base_switches.cc index d907a3a..a1d688a 100644 --- a/base/base_switches.cc +++ b/base/base_switches.cc @@ -6,9 +6,10 @@ namespace switches { -// If the program includes chrome/common/debug_on_start.h, the process will -// start the JIT system-registered debugger on itself and will wait for 60 -// seconds for the debugger to attach to itself. Then a break point will be hit. +// If the program includes base/debug/debug_on_start_win.h, the process will +// (on Windows only) start the JIT system-registered debugger on itself and +// will wait for 60 seconds for the debugger to attach to itself. Then a break +// point will be hit. const char kDebugOnStart[] = "debug-on-start"; // Disables the crash reporting. @@ -23,7 +24,7 @@ const char kFullMemoryCrashReport[] = "full-memory-crash-report"; // Suppresses all error dialogs when present. const char kNoErrorDialogs[] = "noerrdialogs"; -// Disable win_util::MessageBox. This is useful when running as part of +// Disable app::win::MessageBox. This is useful when running as part of // scripts that do not have a user interface. const char kNoMessageBox[] = "no-message-box"; diff --git a/base/command_line.cc b/base/command_line.cc index 70d6872..66b4437 100644 --- a/base/command_line.cc +++ b/base/command_line.cc @@ -4,18 +4,6 @@ #include "base/command_line.h" -#if defined(OS_WIN) -#include <windows.h> -#include <shellapi.h> -#elif defined(OS_POSIX) -#include <limits.h> -#include <stdlib.h> -#include <unistd.h> -#endif -#if defined(OS_LINUX) -#include <sys/prctl.h> -#endif - #include <algorithm> #include "base/file_path.h" @@ -26,10 +14,15 @@ #include "base/string_util.h" #include "base/sys_string_conversions.h" #include "base/utf_string_conversions.h" +#include "build/build_config.h" -#if defined(OS_LINUX) -// Linux/glibc doesn't natively have setproctitle(). -#include "base/setproctitle_linux.h" +#if defined(OS_WIN) +#include <windows.h> +#include <shellapi.h> +#elif defined(OS_POSIX) +#include <limits.h> +#include <stdlib.h> +#include <unistd.h> #endif CommandLine* CommandLine::current_process_commandline_ = NULL; @@ -218,55 +211,8 @@ void CommandLine::Init(int argc, const char* const* argv) { #elif defined(OS_POSIX) current_process_commandline_->InitFromArgv(argc, argv); #endif - -#if defined(OS_LINUX) - if (argv) - setproctitle_init(const_cast<char**>(argv)); -#endif } -#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_NACL) -// static -void CommandLine::SetProcTitle() { - // Build a single string which consists of all the arguments separated - // by spaces. We can't actually keep them separate due to the way the - // setproctitle() function works. - std::string title; - bool have_argv0 = false; -#if defined(OS_LINUX) - // In Linux we sometimes exec ourselves from /proc/self/exe, but this makes us - // show up as "exe" in process listings. Read the symlink /proc/self/exe and - // use the path it points at for our process title. Note that this is only for - // display purposes and has no TOCTTOU security implications. - FilePath target; - FilePath self_exe("/proc/self/exe"); - if (file_util::ReadSymbolicLink(self_exe, &target)) { - have_argv0 = true; - title = target.value(); - // If the binary has since been deleted, Linux appends " (deleted)" to the - // symlink target. Remove it, since this is not really part of our name. - const std::string kDeletedSuffix = " (deleted)"; - if (EndsWith(title, kDeletedSuffix, true)) - title.resize(title.size() - kDeletedSuffix.size()); -#if defined(PR_SET_NAME) - // If PR_SET_NAME is available at compile time, we try using it. We ignore - // any errors if the kernel does not support it at runtime though. When - // available, this lets us set the short process name that shows when the - // full command line is not being displayed in most process listings. - prctl(PR_SET_NAME, FilePath(title).BaseName().value().c_str()); -#endif - } -#endif - for (size_t i = 1; i < current_process_commandline_->argv_.size(); ++i) { - if (!title.empty()) - title += " "; - title += current_process_commandline_->argv_[i]; - } - // Disable prepending argv[0] with '-' if we prepended it ourselves above. - setproctitle(have_argv0 ? "-%s" : "%s", title.c_str()); -} -#endif - void CommandLine::Reset() { DCHECK(current_process_commandline_ != NULL); delete current_process_commandline_; diff --git a/base/command_line.h b/base/command_line.h index df0293c..b8bbba9 100644 --- a/base/command_line.h +++ b/base/command_line.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. @@ -17,62 +17,62 @@ #define BASE_COMMAND_LINE_H_ #pragma once -#include "build/build_config.h" - #include <map> #include <string> #include <vector> #include "base/basictypes.h" +#include "build/build_config.h" class FilePath; class InProcessBrowserTest; class CommandLine { public: +#if defined(OS_WIN) + // The type of native command line arguments. + typedef std::wstring StringType; +#elif defined(OS_POSIX) + // The type of native command line arguments. + typedef std::string StringType; +#endif + + // The type of map for parsed-out switch key and values. + typedef std::map<std::string, StringType> SwitchMap; + // A constructor for CommandLines that are used only to carry switches and // arguments. enum NoProgram { NO_PROGRAM }; explicit CommandLine(NoProgram no_program); + + // Construct a new, empty command line. + // |program| is the name of the program to run (aka argv[0]). + explicit CommandLine(const FilePath& program); + +#if defined(OS_POSIX) + CommandLine(int argc, const char* const* argv); + explicit CommandLine(const std::vector<std::string>& argv); +#endif + ~CommandLine(); #if defined(OS_WIN) - // The type of native command line arguments. - typedef std::wstring StringType; - // Initialize by parsing the given command-line string. // The program name is assumed to be the first item in the string. void ParseFromString(const std::wstring& command_line); static CommandLine FromString(const std::wstring& command_line); #elif defined(OS_POSIX) - // The type of native command line arguments. - typedef std::string StringType; - // Initialize from an argv vector. void InitFromArgv(int argc, const char* const* argv); void InitFromArgv(const std::vector<std::string>& argv); - - CommandLine(int argc, const char* const* argv); - explicit CommandLine(const std::vector<std::string>& argv); #endif - // Construct a new, empty command line. - // |program| is the name of the program to run (aka argv[0]). - explicit CommandLine(const FilePath& program); - // Initialize the current process CommandLine singleton. On Windows, // ignores its arguments (we instead parse GetCommandLineW() // directly) because we don't trust the CRT's parsing of the command // line, but it still must be called to set up the command line. static void Init(int argc, const char* const* argv); -#if defined(OS_POSIX) && !defined(OS_MACOSX) - // Sets the current process' arguments that show in "ps" etc. to those - // in |current_process_commandline_|. Used by the zygote host so that - // renderers show up with --type=renderer. - static void SetProcTitle(); -#endif - // Destroys the current process CommandLine singleton. This is necessary if // you want to reset the base library to its initial state (for example in an // outer library that needs to be able to terminate, and be re-initialized). @@ -99,9 +99,6 @@ class CommandLine { // Get the number of switches in this process. size_t GetSwitchCount() const { return switches_.size(); } - // The type of map for parsed-out switch key and values. - typedef std::map<std::string, StringType> SwitchMap; - // Get a copy of all switches, along with their values const SwitchMap& GetSwitches() const { return switches_; @@ -169,6 +166,12 @@ class CommandLine { // Used by InProcessBrowserTest. static CommandLine* ForCurrentProcessMutable(); + // Returns true and fills in |switch_string| and |switch_value| + // if |parameter_string| represents a switch. + static bool IsSwitch(const StringType& parameter_string, + std::string* switch_string, + StringType* switch_value); + // The singleton CommandLine instance representing the current process's // command line. static CommandLine* current_process_commandline_; @@ -186,12 +189,6 @@ class CommandLine { std::vector<std::string> argv_; #endif - // Returns true and fills in |switch_string| and |switch_value| - // if |parameter_string| represents a switch. - static bool IsSwitch(const StringType& parameter_string, - std::string* switch_string, - StringType* switch_value); - // Parsed-out values. SwitchMap switches_; diff --git a/base/compiler_specific.h b/base/compiler_specific.h index 5917882..017b869 100644 --- a/base/compiler_specific.h +++ b/base/compiler_specific.h @@ -84,6 +84,8 @@ // virtual void foo() OVERRIDE; #if defined(COMPILER_MSVC) #define OVERRIDE override +#elif defined(__clang__) +#define OVERRIDE __attribute__((override)) #else #define OVERRIDE #endif diff --git a/base/crypto/cssm_init.cc b/base/crypto/cssm_init.cc index 46a6ffe..f588f30 100644 --- a/base/crypto/cssm_init.cc +++ b/base/crypto/cssm_init.cc @@ -6,9 +6,9 @@ #include <Security/SecBase.h> -#include "base/lock.h" #include "base/logging.h" #include "base/singleton.h" +#include "base/synchronization/lock.h" #include "base/sys_string_conversions.h" // When writing crypto code for Mac OS X, you may find the following @@ -92,7 +92,7 @@ class SecurityServicesSingleton { ~SecurityServicesSingleton() {} - Lock& lock() { return lock_; } + base::Lock& lock() { return lock_; } private: friend class Singleton<SecurityServicesSingleton>; @@ -100,7 +100,7 @@ class SecurityServicesSingleton { SecurityServicesSingleton() {} - Lock lock_; + base::Lock lock_; DISALLOW_COPY_AND_ASSIGN(SecurityServicesSingleton); }; @@ -154,7 +154,7 @@ void LogCSSMError(const char *fn_name, CSSM_RETURN err) { } } -Lock& GetMacSecurityServicesLock() { +base::Lock& GetMacSecurityServicesLock() { return SecurityServicesSingleton::GetInstance()->lock(); } diff --git a/base/crypto/cssm_init.h b/base/crypto/cssm_init.h index e457083..5644d7e 100644 --- a/base/crypto/cssm_init.h +++ b/base/crypto/cssm_init.h @@ -10,10 +10,10 @@ #include "base/scoped_ptr.h" -class Lock; - namespace base { +class Lock; + // Initialize CSSM if it isn't already initialized. This must be called before // any other CSSM functions. This function is thread-safe, and CSSM will only // ever be initialized once. CSSM will be properly shut down on program exit. diff --git a/base/crypto/rsa_private_key.h b/base/crypto/rsa_private_key.h index bac4250..9b8b4fd 100644 --- a/base/crypto/rsa_private_key.h +++ b/base/crypto/rsa_private_key.h @@ -1,4 +1,4 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// 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. @@ -168,6 +168,8 @@ class PrivateKeyInfoCodec { // TODO(hclam): This class should be ref-counted so it can be reused easily. class RSAPrivateKey { public: + ~RSAPrivateKey(); + // Create a new random instance. Can return NULL if initialization fails. static RSAPrivateKey* Create(uint16 num_bits); @@ -203,8 +205,6 @@ class RSAPrivateKey { static RSAPrivateKey* FindFromPublicKeyInfo( const std::vector<uint8>& input); - ~RSAPrivateKey(); - #if defined(USE_OPENSSL) EVP_PKEY* key() { return key_; } #elif defined(USE_NSS) diff --git a/base/crypto/signature_creator.h b/base/crypto/signature_creator.h index c405560..3e3afd2 100644 --- a/base/crypto/signature_creator.h +++ b/base/crypto/signature_creator.h @@ -1,4 +1,4 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// 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. @@ -33,12 +33,12 @@ namespace base { // Currently can only sign data using SHA-1 with RSA encryption. class SignatureCreator { public: + ~SignatureCreator(); + // Create an instance. The caller must ensure that the provided PrivateKey // instance outlives the created SignatureCreator. static SignatureCreator* Create(RSAPrivateKey* key); - ~SignatureCreator(); - // Update the signature with more data. bool Update(const uint8* data_part, int data_part_len); diff --git a/base/debug_on_start.cc b/base/debug/debug_on_start_win.cc index 15dab05..b5c1094 100644 --- a/base/debug_on_start.cc +++ b/base/debug/debug_on_start_win.cc @@ -1,15 +1,18 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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 <windows.h> +#include "base/debug/debug_on_start_win.h" -#include "base/debug_on_start.h" +#include <windows.h> #include "base/base_switches.h" #include "base/basictypes.h" #include "base/debug/debugger.h" +namespace base { +namespace debug { + // Minimalist implementation to try to find a command line argument. We can use // kernel32 exported functions but not the CRT functions because we're too early // in the process startup. @@ -66,3 +69,6 @@ int __cdecl DebugOnStart::Init() { } return 0; } + +} // namespace debug +} // namespace base diff --git a/base/debug_on_start.h b/base/debug/debug_on_start_win.h index 1774415..5a1081d 100644 --- a/base/debug_on_start.h +++ b/base/debug/debug_on_start_win.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. @@ -6,19 +6,24 @@ // line argument. When the command line argument is detected, it invokes the // debugger, if no system-wide debugger is registered, a debug break is done. -#ifndef BASE_DEBUG_ON_START_H_ -#define BASE_DEBUG_ON_START_H_ +#ifndef BASE_DEBUG_DEBUG_ON_START_WIN_H_ +#define BASE_DEBUG_DEBUG_ON_START_WIN_H_ #pragma once #include "base/basictypes.h" +#include "build/build_config.h" -// This only works on Windows. +// This only works on Windows. It's legal to include on other platforms, but +// will be a NOP. #if defined(OS_WIN) #ifndef DECLSPEC_SELECTANY #define DECLSPEC_SELECTANY __declspec(selectany) #endif +namespace base { +namespace debug { + // Debug on start functions and data. class DebugOnStart { public: @@ -63,6 +68,10 @@ DECLSPEC_SELECTANY DebugOnStart::PIFV debug_on_start = &DebugOnStart::Init; #pragma data_seg(pop) #endif // _WIN64 + +} // namespace debug +} // namespace base + #endif // defined(OS_WIN) -#endif // BASE_DEBUG_ON_START_H_ +#endif // BASE_DEBUG_DEBUG_ON_START_WIN_H_ diff --git a/base/debug/debugger.cc b/base/debug/debugger.cc index 9ca7e8d..8674f1f 100644 --- a/base/debug/debugger.cc +++ b/base/debug/debugger.cc @@ -4,11 +4,13 @@ #include "base/debug/debugger.h" -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" namespace base { namespace debug { +static bool is_debug_ui_suppressed = false; + bool WaitForDebugger(int wait_seconds, bool silent) { for (int i = 0; i < wait_seconds * 10; ++i) { if (BeingDebugged()) { @@ -21,5 +23,13 @@ bool WaitForDebugger(int wait_seconds, bool silent) { return false; } +void SetSuppressDebugUI(bool suppress) { + is_debug_ui_suppressed = suppress; +} + +bool IsDebugUISuppressed() { + return is_debug_ui_suppressed; +} + } // namespace debug } // namespace base diff --git a/base/debug/debugger.h b/base/debug/debugger.h index 008d77d..77bde0d 100644 --- a/base/debug/debugger.h +++ b/base/debug/debugger.h @@ -33,6 +33,14 @@ bool BeingDebugged(); // Break into the debugger, assumes a debugger is present. void BreakDebugger(); +// Used in test code, this controls whether showing dialogs and breaking into +// the debugger is suppressed for debug errors, even in debug mode (normally +// release mode doesn't do this stuff -- this is controlled separately). +// Normally UI is not suppressed. This is normally used when running automated +// tests where we want a crash rather than a dialog or a debugger. +void SetSuppressDebugUI(bool suppress); +bool IsDebugUISuppressed(); + } // namespace debug } // namespace base diff --git a/base/debug/debugger_posix.cc b/base/debug/debugger_posix.cc index 1e0c2ba..b865e65 100644 --- a/base/debug/debugger_posix.cc +++ b/base/debug/debugger_posix.cc @@ -6,6 +6,7 @@ #include "build/build_config.h" #include <errno.h> +#include <execinfo.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> @@ -30,7 +31,6 @@ #include <iostream> #include "base/basictypes.h" -#include "base/compat_execinfo.h" #include "base/eintr_wrapper.h" #include "base/logging.h" #include "base/safe_strerror_posix.h" @@ -137,7 +137,7 @@ bool BeingDebugged() { #elif defined(OS_FREEBSD) -bool DebugUtil::BeingDebugged() { +bool BeingDebugged() { // TODO(benl): can we determine this under FreeBSD? NOTIMPLEMENTED(); return false; diff --git a/base/debug/debugger_win.cc b/base/debug/debugger_win.cc index d1d47cd..3323b61 100644 --- a/base/debug/debugger_win.cc +++ b/base/debug/debugger_win.cc @@ -8,7 +8,6 @@ #include <dbghelp.h> #include "base/basictypes.h" -#include "base/debug_util.h" #include "base/logging.h" namespace base { @@ -103,7 +102,7 @@ bool BeingDebugged() { } void BreakDebugger() { - if (DebugUtil::AreDialogsSuppressed()) + if (IsDebugUISuppressed()) _exit(1); __debugbreak(); } diff --git a/base/debug/stack_trace_posix.cc b/base/debug/stack_trace_posix.cc index 90e302e..879110d 100644 --- a/base/debug/stack_trace_posix.cc +++ b/base/debug/stack_trace_posix.cc @@ -5,6 +5,7 @@ #include "base/debug/stack_trace.h" #include <errno.h> +#include <execinfo.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> @@ -27,7 +28,6 @@ #include <iostream> #include "base/basictypes.h" -#include "base/compat_execinfo.h" #include "base/eintr_wrapper.h" #include "base/logging.h" #include "base/safe_strerror_posix.h" diff --git a/base/debug/trace_event.cc b/base/debug/trace_event.cc index 9b9ed1f..a6fddee 100644 --- a/base/debug/trace_event.cc +++ b/base/debug/trace_event.cc @@ -8,9 +8,9 @@ #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" -#include "base/platform_thread.h" #include "base/process_util.h" #include "base/stringprintf.h" +#include "base/threading/platform_thread.h" #include "base/utf_string_conversions.h" #include "base/time.h" diff --git a/base/debug_util.cc b/base/debug_util.cc deleted file mode 100644 index 4773de3..0000000 --- a/base/debug_util.cc +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/debug_util.h" - -bool DebugUtil::suppress_dialogs_ = false; diff --git a/base/debug_util.h b/base/debug_util.h deleted file mode 100644 index a643ccf..0000000 --- a/base/debug_util.h +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_DEBUG_UTIL_H_ -#define BASE_DEBUG_UTIL_H_ -#pragma once - -#include "build/build_config.h" - -class DebugUtil { - public: -#if defined(OS_MACOSX) - // On Mac OS X, it can take a really long time for the OS crash handler to - // process a Chrome crash when debugging symbols are available. This - // translates into a long wait until the process actually dies. This call - // disables Apple Crash Reporter entirely. - static void DisableOSCrashDumps(); -#endif // defined(OS_MACOSX) - - // This should be used only in test code. - static void SuppressDialogs() { - suppress_dialogs_ = true; - } - - static bool AreDialogsSuppressed() { - return suppress_dialogs_; - } - - private: - // If true, avoid displaying any dialogs that could cause problems - // in non-interactive environments. - static bool suppress_dialogs_; -}; - -#endif // BASE_DEBUG_UTIL_H_ diff --git a/base/file_path.cc b/base/file_path.cc index eba9afe..cddb17e 100644 --- a/base/file_path.cc +++ b/base/file_path.cc @@ -174,6 +174,23 @@ FilePath& FilePath::operator=(const FilePath& that) { return *this; } +bool FilePath::operator==(const FilePath& that) const { +#if defined(FILE_PATH_USES_DRIVE_LETTERS) + return EqualDriveLetterCaseInsensitive(this->path_, that.path_); +#else // defined(FILE_PATH_USES_DRIVE_LETTERS) + return path_ == that.path_; +#endif // defined(FILE_PATH_USES_DRIVE_LETTERS) +} + +bool FilePath::operator!=(const FilePath& that) const { +#if defined(FILE_PATH_USES_DRIVE_LETTERS) + return !EqualDriveLetterCaseInsensitive(this->path_, that.path_); +#else // defined(FILE_PATH_USES_DRIVE_LETTERS) + return path_ != that.path_; +#endif // defined(FILE_PATH_USES_DRIVE_LETTERS) +} + +// static bool FilePath::IsSeparator(CharType character) { for (size_t i = 0; i < arraysize(kSeparators) - 1; ++i) { if (character == kSeparators[i]) { @@ -219,22 +236,6 @@ void FilePath::GetComponents(std::vector<StringType>* components) const { *components = std::vector<StringType>(ret_val.rbegin(), ret_val.rend()); } -bool FilePath::operator==(const FilePath& that) const { -#if defined(FILE_PATH_USES_DRIVE_LETTERS) - return EqualDriveLetterCaseInsensitive(this->path_, that.path_); -#else // defined(FILE_PATH_USES_DRIVE_LETTERS) - return path_ == that.path_; -#endif // defined(FILE_PATH_USES_DRIVE_LETTERS) -} - -bool FilePath::operator!=(const FilePath& that) const { -#if defined(FILE_PATH_USES_DRIVE_LETTERS) - return !EqualDriveLetterCaseInsensitive(this->path_, that.path_); -#else // defined(FILE_PATH_USES_DRIVE_LETTERS) - return path_ != that.path_; -#endif // defined(FILE_PATH_USES_DRIVE_LETTERS) -} - bool FilePath::IsParent(const FilePath& child) const { return AppendRelativePath(child, NULL); } @@ -489,6 +490,87 @@ bool FilePath::IsAbsolute() const { return IsPathAbsolute(path_); } +FilePath FilePath::StripTrailingSeparators() const { + FilePath new_path(path_); + new_path.StripTrailingSeparatorsInternal(); + + return new_path; +} + +bool FilePath::ReferencesParent() const { + std::vector<StringType> components; + GetComponents(&components); + + std::vector<StringType>::const_iterator it = components.begin(); + for (; it != components.end(); ++it) { + const StringType& component = *it; + if (component == kParentDirectory) + return true; + } + return false; +} + +#if defined(OS_POSIX) + +// See file_path.h for a discussion of the encoding of paths on POSIX +// platforms. These *Hack() functions are not quite correct, but they're +// only temporary while we fix the remainder of the code. +// Remember to remove the #includes at the top when you remove these. + +// static +FilePath FilePath::FromWStringHack(const std::wstring& wstring) { + return FilePath(base::SysWideToNativeMB(wstring)); +} +std::wstring FilePath::ToWStringHack() const { + return base::SysNativeMBToWide(path_); +} +#elif defined(OS_WIN) +// static +FilePath FilePath::FromWStringHack(const std::wstring& wstring) { + return FilePath(wstring); +} +std::wstring FilePath::ToWStringHack() const { + return path_; +} +#endif + +// static. +void FilePath::WriteStringTypeToPickle(Pickle* pickle, + const StringType& path) { +#if defined(WCHAR_T_IS_UTF16) + pickle->WriteWString(path); +#elif defined(WCHAR_T_IS_UTF32) + pickle->WriteString(path); +#else + NOTIMPLEMENTED() << "Impossible encoding situation!"; +#endif +} + +// static. +bool FilePath::ReadStringTypeFromPickle(Pickle* pickle, void** iter, + StringType* path) { +#if defined(WCHAR_T_IS_UTF16) + if (!pickle->ReadWString(iter, path)) + return false; +#elif defined(WCHAR_T_IS_UTF32) + if (!pickle->ReadString(iter, path)) + return false; +#else + NOTIMPLEMENTED() << "Impossible encoding situation!"; + return false; +#endif + + return true; +} + +void FilePath::WriteToPickle(Pickle* pickle) { + WriteStringTypeToPickle(pickle, value()); +} + +bool FilePath::ReadFromPickle(Pickle* pickle, void** iter) { + return ReadStringTypeFromPickle(pickle, iter, &path_); +} + #if defined(OS_WIN) // Windows specific implementation of file string comparisons @@ -1078,73 +1160,6 @@ int FilePath::CompareIgnoreCase(const StringType& string1, #endif // OS versions of CompareIgnoreCase() -#if defined(OS_POSIX) - -// See file_path.h for a discussion of the encoding of paths on POSIX -// platforms. These *Hack() functions are not quite correct, but they're -// only temporary while we fix the remainder of the code. -// Remember to remove the #includes at the top when you remove these. - -// static -FilePath FilePath::FromWStringHack(const std::wstring& wstring) { - return FilePath(base::SysWideToNativeMB(wstring)); -} -std::wstring FilePath::ToWStringHack() const { - return base::SysNativeMBToWide(path_); -} -#elif defined(OS_WIN) -// static -FilePath FilePath::FromWStringHack(const std::wstring& wstring) { - return FilePath(wstring); -} -std::wstring FilePath::ToWStringHack() const { - return path_; -} -#endif - -FilePath FilePath::StripTrailingSeparators() const { - FilePath new_path(path_); - new_path.StripTrailingSeparatorsInternal(); - - return new_path; -} - -// static. -void FilePath::WriteStringTypeToPickle(Pickle* pickle, - const StringType& path) { -#if defined(WCHAR_T_IS_UTF16) - pickle->WriteWString(path); -#elif defined(WCHAR_T_IS_UTF32) - pickle->WriteString(path); -#else - NOTIMPLEMENTED() << "Impossible encoding situation!"; -#endif -} - -// static. -bool FilePath::ReadStringTypeFromPickle(Pickle* pickle, void** iter, - StringType* path) { -#if defined(WCHAR_T_IS_UTF16) - if (!pickle->ReadWString(iter, path)) - return false; -#elif defined(WCHAR_T_IS_UTF32) - if (!pickle->ReadString(iter, path)) - return false; -#else - NOTIMPLEMENTED() << "Impossible encoding situation!"; - return false; -#endif - - return true; -} - -void FilePath::WriteToPickle(Pickle* pickle) { - WriteStringTypeToPickle(pickle, value()); -} - -bool FilePath::ReadFromPickle(Pickle* pickle, void** iter) { - return ReadStringTypeFromPickle(pickle, iter, &path_); -} void FilePath::StripTrailingSeparatorsInternal() { // If there is no drive letter, start will be 1, which will prevent stripping @@ -1168,19 +1183,6 @@ void FilePath::StripTrailingSeparatorsInternal() { } } -bool FilePath::ReferencesParent() const { - std::vector<StringType> components; - GetComponents(&components); - - std::vector<StringType>::const_iterator it = components.begin(); - for (; it != components.end(); ++it) { - const StringType& component = *it; - if (component == kParentDirectory) - return true; - } - return false; -} - #if defined(FILE_PATH_USES_WIN_SEPARATORS) FilePath FilePath::NormalizeWindowsPathSeparators() const { StringType copy = path_; diff --git a/base/file_util.cc b/base/file_util.cc index 2b5dc84..d1a46c9 100644 --- a/base/file_util.cc +++ b/base/file_util.cc @@ -386,12 +386,6 @@ std::wstring GetFileExtensionFromPath(const std::wstring& path) { GetFileExtensionFromPath(FilePath::FromWStringHack(path)); return extension; } -std::wstring GetFilenameFromPath(const std::wstring& path) { - if (path.empty() || EndsWithSeparator(FilePath::FromWStringHack(path))) - return std::wstring(); - - return FilePath::FromWStringHack(path).BaseName().ToWStringHack(); -} FILE* OpenFile(const std::wstring& filename, const char* mode) { return OpenFile(FilePath::FromWStringHack(filename), mode); } diff --git a/base/file_util.h b/base/file_util.h index e34d0de..ab6906d 100644 --- a/base/file_util.h +++ b/base/file_util.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -462,10 +462,10 @@ class FileEnumerator { WIN32_FIND_DATA find_data_; HANDLE find_handle_; #elif defined(OS_POSIX) - typedef struct { + struct DirectoryEntryInfo { FilePath filename; struct stat stat; - } DirectoryEntryInfo; + }; // Read the filenames in source into the vector of DirectoryEntryInfo's static bool ReadDirectory(std::vector<DirectoryEntryInfo>* entries, diff --git a/base/file_util_deprecated.h b/base/file_util_deprecated.h index 9bafb31..dac4b45 100644 --- a/base/file_util_deprecated.h +++ b/base/file_util_deprecated.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -27,21 +27,6 @@ namespace file_util { FILE* OpenFile(const std::string& filename, const char* mode); FILE* OpenFile(const std::wstring& filename, const char* mode); -// Use FilePath::BaseName instead. -std::wstring GetFilenameFromPath(const std::wstring& path); - -// Returns the directory component of a path, without the trailing -// path separator, or an empty string on error. The function does not -// check for the existence of the path, so if it is passed a directory -// without the trailing \, it will interpret the last component of the -// path as a file and chomp it. This does not support relative paths. -// Examples: -// path == "C:\pics\jojo.jpg", returns "C:\pics" -// path == "C:\Windows\system32\", returns "C:\Windows\system32" -// path == "C:\Windows\system32", returns "C:\Windows" -// Deprecated. Use FilePath's DirName() instead. -std::wstring GetDirectoryFromPath(const std::wstring& path); - // Appends new_ending to path, adding a separator between the two if necessary. void AppendToPath(std::wstring* path, const std::wstring& new_ending); diff --git a/base/file_util_mac.mm b/base/file_util_mac.mm index ca0284c..95d4f25 100644 --- a/base/file_util_mac.mm +++ b/base/file_util_mac.mm @@ -10,7 +10,7 @@ #include "base/basictypes.h" #include "base/file_path.h" #include "base/string_util.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" namespace file_util { diff --git a/base/file_util_posix.cc b/base/file_util_posix.cc index ac6dabb..475918e 100644 --- a/base/file_util_posix.cc +++ b/base/file_util_posix.cc @@ -38,7 +38,7 @@ #include "base/singleton.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" #include "base/time.h" #include "base/utf_string_conversions.h" diff --git a/base/file_util_proxy.h b/base/file_util_proxy.h index f266562..4181a26 100644 --- a/base/file_util_proxy.h +++ b/base/file_util_proxy.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -33,14 +33,27 @@ class FileUtilProxy { // StatusCallback, in which case the operation will complete silently. typedef Callback1<PlatformFileError /* error code */>::Type StatusCallback; + typedef Callback3<PlatformFileError /* error code */, + PassPlatformFile, + bool /* created */>::Type CreateOrOpenCallback; + typedef Callback3<PlatformFileError /* error code */, + PassPlatformFile, + FilePath>::Type CreateTemporaryCallback; + typedef Callback2<PlatformFileError /* error code */, + bool /* created */>::Type EnsureFileExistsCallback; + typedef Callback2<PlatformFileError /* error code */, + const PlatformFileInfo& /* file_info */ + >::Type GetFileInfoCallback; + typedef Callback2<PlatformFileError /* error code */, + const std::vector<Entry>&>::Type ReadDirectoryCallback; + typedef Callback2<PlatformFileError /* error code */, + int /* bytes read/written */>::Type ReadWriteCallback; + // Creates or opens a file with the given flags. It is invalid to pass NULL // for the callback. // If PLATFORM_FILE_CREATE is set in |file_flags| it always tries to create // a new file at the given |file_path| and calls back with // PLATFORM_FILE_ERROR_FILE_EXISTS if the |file_path| already exists. - typedef Callback3<PlatformFileError /* error code */, - PassPlatformFile, - bool /* created */>::Type CreateOrOpenCallback; static bool CreateOrOpen(scoped_refptr<MessageLoopProxy> message_loop_proxy, const FilePath& file_path, int file_flags, @@ -48,9 +61,6 @@ class FileUtilProxy { // Creates a temporary file for writing. The path and an open file handle // are returned. It is invalid to pass NULL for the callback. - typedef Callback3<PlatformFileError /* error code */, - PassPlatformFile, - FilePath>::Type CreateTemporaryCallback; static bool CreateTemporary( scoped_refptr<MessageLoopProxy> message_loop_proxy, CreateTemporaryCallback* callback); @@ -69,8 +79,6 @@ class FileUtilProxy { // is set PLATFORM_FILE_OK. // If the file hasn't existed but it couldn't be created for some other // reasons, |created| is set false and |error code| indicates the error. - typedef Callback2<PlatformFileError /* error code */, - bool /* created */>::Type EnsureFileExistsCallback; static bool EnsureFileExists( scoped_refptr<MessageLoopProxy> message_loop_proxy, const FilePath& file_path, @@ -78,9 +86,6 @@ class FileUtilProxy { // Retrieves the information about a file. It is invalid to pass NULL for the // callback. - typedef Callback2<PlatformFileError /* error code */, - const PlatformFileInfo& /* file_info */ - >::Type GetFileInfoCallback; static bool GetFileInfo( scoped_refptr<MessageLoopProxy> message_loop_proxy, const FilePath& file_path, @@ -91,8 +96,6 @@ class FileUtilProxy { PlatformFile file, GetFileInfoCallback* callback); - typedef Callback2<PlatformFileError /* error code */, - const std::vector<Entry>&>::Type ReadDirectoryCallback; static bool ReadDirectory(scoped_refptr<MessageLoopProxy> message_loop_proxy, const FilePath& file_path, ReadDirectoryCallback* callback); @@ -142,8 +145,6 @@ class FileUtilProxy { // Reads from a file. On success, the file pointer is moved to position // |offset + bytes_to_read| in the file. The callback can be NULL. - typedef Callback2<PlatformFileError /* error code */, - int /* bytes read/written */>::Type ReadWriteCallback; static bool Read( scoped_refptr<MessageLoopProxy> message_loop_proxy, PlatformFile file, diff --git a/base/file_util_unittest.cc b/base/file_util_unittest.cc index cb77828..6ea94e4 100644 --- a/base/file_util_unittest.cc +++ b/base/file_util_unittest.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -19,14 +19,17 @@ #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" -#include "base/platform_thread.h" -#include "base/scoped_handle.h" #include "base/scoped_temp_dir.h" +#include "base/threading/platform_thread.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" +#if defined(OS_WIN) +#include "base/win/scoped_handle.h" +#endif + // This macro helps avoid wrapped lines in the test structs. #define FPL(x) FILE_PATH_LITERAL(x) @@ -251,17 +254,6 @@ static const struct filename_case { #endif }; -#if defined(OS_WIN) -// This function is deprecated on non-Windows. -TEST_F(FileUtilTest, GetFilenameFromPath) { - for (unsigned int i = 0; i < arraysize(filename_cases); ++i) { - const filename_case& value = filename_cases[i]; - std::wstring result = file_util::GetFilenameFromPath(value.path); - EXPECT_EQ(value.filename, result); - } -} -#endif - // Test finding the file type from a path name static const struct extension_case { const wchar_t* path; @@ -326,18 +318,6 @@ static const struct dir_case { #endif }; -#if defined(OS_WIN) -// This function is deprecated, and only exists on Windows anymore. -TEST_F(FileUtilTest, GetDirectoryFromPath) { - for (unsigned int i = 0; i < arraysize(dir_cases); ++i) { - const dir_case& dir = dir_cases[i]; - const std::wstring parent = - file_util::GetDirectoryFromPath(dir.full_path); - EXPECT_EQ(dir.directory, parent); - } -} -#endif - // Flaky, http://crbug.com/46246 TEST_F(FileUtilTest, FLAKY_CountFilesCreatedAfter) { // Create old file (that we don't want to count) @@ -347,11 +327,11 @@ TEST_F(FileUtilTest, FLAKY_CountFilesCreatedAfter) { // Age to perfection #if defined(OS_WIN) - PlatformThread::Sleep(100); + base::PlatformThread::Sleep(100); #elif defined(OS_POSIX) // We need to wait at least one second here because the precision of // file creation time is one second. - PlatformThread::Sleep(1500); + base::PlatformThread::Sleep(1500); #endif // Establish our cutoff time @@ -494,7 +474,7 @@ TEST_F(FileUtilTest, NormalizeFilePathReparsePoints) { FilePath to_sub_a = base_b.Append(FPL("to_sub_a")); ASSERT_TRUE(file_util::CreateDirectory(to_sub_a)); - ScopedHandle reparse_to_sub_a( + base::win::ScopedHandle reparse_to_sub_a( ::CreateFile(to_sub_a.value().c_str(), FILE_ALL_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, @@ -507,7 +487,7 @@ TEST_F(FileUtilTest, NormalizeFilePathReparsePoints) { FilePath to_base_b = base_b.Append(FPL("to_base_b")); ASSERT_TRUE(file_util::CreateDirectory(to_base_b)); - ScopedHandle reparse_to_base_b( + base::win::ScopedHandle reparse_to_base_b( ::CreateFile(to_base_b.value().c_str(), FILE_ALL_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, @@ -520,7 +500,7 @@ TEST_F(FileUtilTest, NormalizeFilePathReparsePoints) { FilePath to_sub_long = base_b.Append(FPL("to_sub_long")); ASSERT_TRUE(file_util::CreateDirectory(to_sub_long)); - ScopedHandle reparse_to_sub_long( + base::win::ScopedHandle reparse_to_sub_long( ::CreateFile(to_sub_long.value().c_str(), FILE_ALL_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, diff --git a/base/file_util_win.cc b/base/file_util_win.cc index 3ca52ae..7476b53 100644 --- a/base/file_util_win.cc +++ b/base/file_util_win.cc @@ -19,11 +19,11 @@ #include "base/win/scoped_handle.h" #include "base/string_number_conversions.h" #include "base/string_util.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" #include "base/time.h" #include "base/utf_string_conversions.h" -#include "base/win_util.h" #include "base/win/scoped_comptr.h" +#include "base/win/win_util.h" #include "base/win/windows_version.h" namespace file_util { @@ -77,19 +77,6 @@ bool DevicePathToDriveLetterPath(const FilePath& device_path, } // namespace -std::wstring GetDirectoryFromPath(const std::wstring& path) { - base::ThreadRestrictions::AssertIOAllowed(); - wchar_t path_buffer[MAX_PATH]; - wchar_t* file_ptr = NULL; - if (GetFullPathName(path.c_str(), MAX_PATH, path_buffer, &file_ptr) == 0) - return L""; - - std::wstring::size_type length = - file_ptr ? file_ptr - path_buffer : path.length(); - std::wstring directory(path, 0, length); - return FilePath(directory).StripTrailingSeparators().value(); -} - bool AbsolutePath(FilePath* path) { base::ThreadRestrictions::AssertIOAllowed(); wchar_t file_path_buf[MAX_PATH]; @@ -447,7 +434,7 @@ bool CreateShortcutLink(const wchar_t *source, const wchar_t *destination, if (FAILED(property_store.QueryFrom(i_shell_link))) return false; - if (!win_util::SetAppIdForPropertyStore(property_store, app_id)) + if (!base::win::SetAppIdForPropertyStore(property_store, app_id)) return false; } @@ -499,7 +486,7 @@ bool UpdateShortcutLink(const wchar_t *source, const wchar_t *destination, if (FAILED(property_store.QueryFrom(i_shell_link))) return false; - if (!win_util::SetAppIdForPropertyStore(property_store, app_id)) + if (!base::win::SetAppIdForPropertyStore(property_store, app_id)) return false; } @@ -757,9 +744,8 @@ int WriteFile(const FilePath& filename, const char* data, int size) { 0, NULL)); if (!file) { - LOG(WARNING) << "CreateFile failed for path " << filename.value() << - " error code=" << GetLastError() << - " error text=" << win_util::FormatLastWin32Error(); + LOG(WARNING) << "CreateFile failed for path " << filename.value() + << " error code=" << GetLastError(); return -1; } @@ -770,9 +756,8 @@ int WriteFile(const FilePath& filename, const char* data, int size) { if (!result) { // WriteFile failed. - LOG(WARNING) << "writing file " << filename.value() << - " failed, error code=" << GetLastError() << - " description=" << win_util::FormatLastWin32Error(); + LOG(WARNING) << "writing file " << filename.value() + << " failed, error code=" << GetLastError(); } else { // Didn't write all the bytes. LOG(WARNING) << "wrote" << written << " bytes to " << diff --git a/base/file_version_info_mac.mm b/base/file_version_info_mac.mm index fa97df8..f716ccc 100644 --- a/base/file_version_info_mac.mm +++ b/base/file_version_info_mac.mm @@ -8,15 +8,15 @@ #include "base/file_path.h" #include "base/logging.h" +#include "base/mac/mac_util.h" #include "base/sys_string_conversions.h" -#include "base/mac_util.h" FileVersionInfoMac::FileVersionInfoMac(NSBundle *bundle) : bundle_(bundle) { } // static FileVersionInfo* FileVersionInfo::CreateFileVersionInfoForCurrentModule() { - return CreateFileVersionInfo(mac_util::MainAppBundlePath()); + return CreateFileVersionInfo(base::mac::MainAppBundlePath()); } // static @@ -97,7 +97,7 @@ bool FileVersionInfoMac::is_official_build() { string16 FileVersionInfoMac::GetString16Value(CFStringRef name) { if (bundle_) { - NSString *ns_name = mac_util::CFToNSCast(name); + NSString *ns_name = base::mac::CFToNSCast(name); NSString* value = [bundle_ objectForInfoDictionaryKey:ns_name]; if (value) { return base::SysNSStringToUTF16(value); diff --git a/base/file_version_info_win.cc b/base/file_version_info_win.cc index e2bc84b..953caa9 100644 --- a/base/file_version_info_win.cc +++ b/base/file_version_info_win.cc @@ -10,7 +10,7 @@ #include "base/file_version_info.h" #include "base/logging.h" #include "base/path_service.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" // This has to be last. #include <strsafe.h> diff --git a/base/global_descriptors_posix.h b/base/global_descriptors_posix.h index ab2b86b..0cb5b4f 100644 --- a/base/global_descriptors_posix.h +++ b/base/global_descriptors_posix.h @@ -1,4 +1,4 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// 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. @@ -37,6 +37,8 @@ namespace base { class GlobalDescriptors { public: typedef uint32_t Key; + typedef std::vector<std::pair<Key, int> > Mapping; + // Often we want a canonical descriptor for a given Key. In this case, we add // the following constant to the key value: static const int kBaseDescriptor = 3; // 0, 1, 2 are already taken. @@ -46,11 +48,10 @@ class GlobalDescriptors { // Get a descriptor given a key. It is a fatal error if the key is not known. int Get(Key key) const; + // Get a descriptor give a key. Returns -1 on error. int MaybeGet(Key key) const; - typedef std::vector<std::pair<Key, int> > Mapping; - // Set the descriptor for the given key. void Set(Key key, int fd); @@ -59,9 +60,9 @@ class GlobalDescriptors { } private: + friend struct DefaultSingletonTraits<GlobalDescriptors>; GlobalDescriptors(); ~GlobalDescriptors(); - friend struct DefaultSingletonTraits<GlobalDescriptors>; Mapping descriptors_; }; diff --git a/base/i18n/icu_string_conversions_unittest.cc b/base/i18n/icu_string_conversions_unittest.cc index 40b0fed..eb9d2cd 100644 --- a/base/i18n/icu_string_conversions_unittest.cc +++ b/base/i18n/icu_string_conversions_unittest.cc @@ -9,8 +9,10 @@ #include <sstream> #include "base/basictypes.h" +#include "base/format_macros.h" #include "base/i18n/icu_string_conversions.h" #include "base/logging.h" +#include "base/stringprintf.h" #include "base/string_piece.h" #include "base/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" @@ -72,6 +74,9 @@ const wchar_t* const kConvertRoundtripCases[] = { TEST(ICUStringConversionsTest, ConvertCodepageUTF8) { // Make sure WideToCodepage works like WideToUTF8. for (size_t i = 0; i < arraysize(kConvertRoundtripCases); ++i) { + SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %ls", + i, kConvertRoundtripCases[i])); + std::string expected(WideToUTF8(kConvertRoundtripCases[i])); std::string utf8; EXPECT_TRUE(WideToCodepage(kConvertRoundtripCases[i], kCodepageUTF8, @@ -237,6 +242,11 @@ static const struct { TEST(ICUStringConversionsTest, ConvertBetweenCodepageAndWide) { for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kConvertCodepageCases); ++i) { + SCOPED_TRACE(base::StringPrintf( + "Test[%" PRIuS "]: <encoded: %s> <codepage: %s>", i, + kConvertCodepageCases[i].encoded, + kConvertCodepageCases[i].codepage_name)); + std::wstring wide; bool success = CodepageToWide(kConvertCodepageCases[i].encoded, kConvertCodepageCases[i].codepage_name, @@ -299,6 +309,11 @@ TEST(ICUStringConversionsTest, ConvertBetweenCodepageAndWide) { TEST(ICUStringConversionsTest, ConvertBetweenCodepageAndUTF16) { for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kConvertCodepageCases); ++i) { + SCOPED_TRACE(base::StringPrintf( + "Test[%" PRIuS "]: <encoded: %s> <codepage: %s>", i, + kConvertCodepageCases[i].encoded, + kConvertCodepageCases[i].codepage_name)); + string16 utf16; bool success = CodepageToUTF16(kConvertCodepageCases[i].encoded, kConvertCodepageCases[i].codepage_name, @@ -347,6 +362,11 @@ static const struct { TEST(ICUStringConversionsTest, ConvertToUtf8AndNormalize) { std::string result; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kConvertAndNormalizeCases); ++i) { + SCOPED_TRACE(base::StringPrintf( + "Test[%" PRIuS "]: <encoded: %s> <codepage: %s>", i, + kConvertAndNormalizeCases[i].encoded, + kConvertAndNormalizeCases[i].codepage_name)); + bool success = ConvertToUtf8AndNormalize( kConvertAndNormalizeCases[i].encoded, kConvertAndNormalizeCases[i].codepage_name, &result); diff --git a/base/json/json_reader.h b/base/json/json_reader.h index 33bd8f2..77c4e74 100644 --- a/base/json/json_reader.h +++ b/base/json/json_reader.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. // @@ -69,6 +69,11 @@ class JSONReader { Token(Type t, const wchar_t* b, int len) : type(t), begin(b), length(len) {} + // Get the character that's one past the end of this token. + wchar_t NextChar() { + return *(begin + length); + } + Type type; // A pointer into JSONReader::json_pos_ that's the beginning of this token. @@ -76,11 +81,6 @@ class JSONReader { // End should be one char past the end of the token. int length; - - // Get the character that's one past the end of this token. - wchar_t NextChar() { - return *(begin + length); - } }; // Error codes during parsing. diff --git a/base/lazy_instance.cc b/base/lazy_instance.cc index eb71061..32bb788 100644 --- a/base/lazy_instance.cc +++ b/base/lazy_instance.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -7,7 +7,7 @@ #include "base/at_exit.h" #include "base/atomicops.h" #include "base/basictypes.h" -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" namespace base { diff --git a/base/lazy_instance.h b/base/lazy_instance.h index bdf5ce3..f4cfda0 100644 --- a/base/lazy_instance.h +++ b/base/lazy_instance.h @@ -41,7 +41,7 @@ #include "base/atomicops.h" #include "base/basictypes.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" namespace base { diff --git a/base/lazy_instance_unittest.cc b/base/lazy_instance_unittest.cc index 1731381..28bf04e 100644 --- a/base/lazy_instance_unittest.cc +++ b/base/lazy_instance_unittest.cc @@ -5,7 +5,7 @@ #include "base/at_exit.h" #include "base/atomic_sequence_num.h" #include "base/lazy_instance.h" -#include "base/simple_thread.h" +#include "base/threading/simple_thread.h" #include "testing/gtest/include/gtest/gtest.h" namespace { @@ -26,7 +26,8 @@ class ConstructAndDestructLogger { class SlowConstructor { public: SlowConstructor() : some_int_(0) { - PlatformThread::Sleep(1000); // Sleep for 1 second to try to cause a race. + // Sleep for 1 second to try to cause a race. + base::PlatformThread::Sleep(1000); ++constructed; some_int_ = 12; } diff --git a/base/linux_util.h b/base/linux_util.h index 0d2f20e..c1135ce 100644 --- a/base/linux_util.h +++ b/base/linux_util.h @@ -19,8 +19,7 @@ static const char kFindInodeSwitch[] = "--find-inode"; // in compromised context without going through the standard library. extern char g_linux_distro[]; -// Get the Linux Distro if we can, or return "Unknown", similar to -// GetWinVersion() in base/win_util.h. +// Get the Linux Distro if we can, or return "Unknown". std::string GetLinuxDistro(); // Set the Linux Distro string. diff --git a/base/lock.h b/base/lock.h index ba34964..7c90d86 100644 --- a/base/lock.h +++ b/base/lock.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -6,122 +6,13 @@ #define BASE_LOCK_H_ #pragma once -#include "base/lock_impl.h" -#include "base/platform_thread.h" +// This is a temporary forwarding file so not every user of lock needs to +// be updated at once. +// TODO(brettw) remove this and fix everybody up to using the new location. +#include "base/synchronization/lock.h" -// 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: -#if defined(NDEBUG) // 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 {} -#else - Lock(); - ~Lock() {} - - // NOTE: Although windows critical sections support recursive locks, we do not - // allow this, and we will commonly fire a DCHECK() if a thread attempts to - // acquire the lock a second time (while already holding it). - void Acquire() { - lock_.Lock(); - CheckUnheldAndMark(); - } - void Release() { - CheckHeldAndUnmark(); - lock_.Unlock(); - } - - bool Try() { - bool rv = lock_.Try(); - if (rv) { - CheckUnheldAndMark(); - } - return rv; - } - - void AssertAcquired() const; -#endif // NDEBUG - -#if defined(OS_POSIX) - // The posix implementation of ConditionVariable needs to be able - // to see our lock and tweak our debugging counters, as it releases - // and acquires locks inside of pthread_cond_{timed,}wait. - // Windows doesn't need to do this as it calls the Lock::* methods. - friend class ConditionVariable; -#endif - - private: -#if !defined(NDEBUG) - // Members and routines taking care of locks assertions. - // Note that this checks for recursive locks and allows them - // if the variable is set. This is allowed by the underlying implementation - // on windows but not on Posix, so we're doing unneeded checks on Posix. - // It's worth it to share the code. - void CheckHeldAndUnmark(); - void CheckUnheldAndMark(); - - // All private data is implicitly protected by lock_. - // Be VERY careful to only access members under that lock. - - // Determines validity of owning_thread_id_. Needed as we don't have - // a null owning_thread_id_ value. - bool owned_by_thread_; - PlatformThreadId owning_thread_id_; -#endif // NDEBUG - - LockImpl lock_; // Platform specific underlying lock implementation. - - DISALLOW_COPY_AND_ASSIGN(Lock); -}; - -// A helper class that acquires the given Lock while the AutoLock is in scope. -class AutoLock { - public: - explicit AutoLock(Lock& lock) : lock_(lock) { - lock_.Acquire(); - } - - ~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); -}; +using base::AutoLock; +using base::AutoUnlock; +using base::Lock; #endif // BASE_LOCK_H_ diff --git a/base/logging.cc b/base/logging.cc index 26cc0c5..a736590 100644 --- a/base/logging.cc +++ b/base/logging.cc @@ -50,8 +50,8 @@ typedef pthread_mutex_t* MutexHandle; #include "base/debug/debugger.h" #include "base/debug/stack_trace.h" #include "base/eintr_wrapper.h" -#include "base/lock_impl.h" #include "base/string_piece.h" +#include "base/synchronization/lock_impl.h" #include "base/utf_string_conversions.h" #include "base/vlog.h" #if defined(OS_POSIX) @@ -243,7 +243,7 @@ class LoggingLock { } #endif } else { - log_lock = new LockImpl(); + log_lock = new base::internal::LockImpl(); } initialized = true; } @@ -282,7 +282,7 @@ class LoggingLock { // 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 LockImpl* log_lock; + 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. @@ -299,7 +299,7 @@ class LoggingLock { // static bool LoggingLock::initialized = false; // static -LockImpl* LoggingLock::log_lock = NULL; +base::internal::LockImpl* LoggingLock::log_lock = NULL; // static LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE; diff --git a/base/logging.h b/base/logging.h index 6689eec..a097568 100644 --- a/base/logging.h +++ b/base/logging.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -803,11 +803,11 @@ class Win32ErrorLogMessage { LogSeverity severity, SystemErrorCode err); - std::ostream& stream() { return log_message_.stream(); } - // Appends the error message before destructing the encapsulated class. ~Win32ErrorLogMessage(); + std::ostream& stream() { return log_message_.stream(); } + private: SystemErrorCode err_; // Optional name of the module defining the error. @@ -825,11 +825,11 @@ class ErrnoLogMessage { LogSeverity severity, SystemErrorCode err); - std::ostream& stream() { return log_message_.stream(); } - // Appends the error message before destructing the encapsulated class. ~ErrnoLogMessage(); + std::ostream& stream() { return log_message_.stream(); } + private: SystemErrorCode err_; LogMessage log_message_; diff --git a/base/mac_util.h b/base/mac/mac_util.h index 076865d..7e5dddb 100644 --- a/base/mac_util.h +++ b/base/mac/mac_util.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_MAC_UTIL_H_ -#define BASE_MAC_UTIL_H_ +#ifndef BASE_MAC_MAC_UTIL_H_ +#define BASE_MAC_MAC_UTIL_H_ #pragma once #include <Carbon/Carbon.h> @@ -34,7 +34,8 @@ typedef unsigned int NSSearchPathDirectory; typedef unsigned int NSSearchPathDomainMask; #endif -namespace mac_util { +namespace base { +namespace mac { // Full screen modes, in increasing order of priority. More permissive modes // take predecence. @@ -242,6 +243,7 @@ CF_TO_NS_CAST(CFWriteStreamRef, NSOutputStream); #endif // __OBJC__ -} // namespace mac_util +} // namespace mac +} // namespace base -#endif // BASE_MAC_UTIL_H_ +#endif // BASE_MAC_MAC_UTIL_H_ diff --git a/base/mac_util.mm b/base/mac/mac_util.mm index 598f69b..21213ba 100644 --- a/base/mac_util.mm +++ b/base/mac/mac_util.mm @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/mac_util.h" +#include "base/mac/mac_util.h" #import <Cocoa/Cocoa.h> @@ -13,13 +13,14 @@ #include "base/scoped_nsobject.h" #include "base/sys_string_conversions.h" -using base::mac::ScopedCFTypeRef; +namespace base { +namespace mac { namespace { // a count of currently outstanding requests for full screen mode from browser // windows, plugins, etc. -int g_full_screen_requests[mac_util::kNumFullScreenModes] = { 0, 0, 0}; +int g_full_screen_requests[kNumFullScreenModes] = { 0, 0, 0}; // Sets the appropriate SystemUIMode based on the current full screen requests. // Since only one SystemUIMode can be active at a given time, full screen @@ -39,12 +40,12 @@ void SetUIMode() { // HideDock. SystemUIMode desired_mode = kUIModeNormal; SystemUIOptions desired_options = 0; - if (g_full_screen_requests[mac_util::kFullScreenModeAutoHideAll] > 0) { + if (g_full_screen_requests[kFullScreenModeAutoHideAll] > 0) { desired_mode = kUIModeAllHidden; desired_options = kUIOptionAutoShowMenuBar; - } else if (g_full_screen_requests[mac_util::kFullScreenModeHideDock] > 0) { + } else if (g_full_screen_requests[kFullScreenModeHideDock] > 0) { desired_mode = kUIModeContentHidden; - } else if (g_full_screen_requests[mac_util::kFullScreenModeHideAll] > 0) { + } else if (g_full_screen_requests[kFullScreenModeHideAll] > 0) { desired_mode = kUIModeAllHidden; } @@ -56,16 +57,16 @@ bool WasLaunchedAsLoginItem() { ProcessSerialNumber psn = { 0, kCurrentProcess }; scoped_nsobject<NSDictionary> process_info( - mac_util::CFToNSCast(ProcessInformationCopyDictionary(&psn, - kProcessDictionaryIncludeAllInformationMask))); + CFToNSCast(ProcessInformationCopyDictionary(&psn, + kProcessDictionaryIncludeAllInformationMask))); long long temp = [[process_info objectForKey:@"ParentPSN"] longLongValue]; ProcessSerialNumber parent_psn = { (temp >> 32) & 0x00000000FFFFFFFFLL, temp & 0x00000000FFFFFFFFLL }; scoped_nsobject<NSDictionary> parent_info( - mac_util::CFToNSCast(ProcessInformationCopyDictionary(&parent_psn, - kProcessDictionaryIncludeAllInformationMask))); + CFToNSCast(ProcessInformationCopyDictionary(&parent_psn, + kProcessDictionaryIncludeAllInformationMask))); // Check that creator process code is that of loginwindow. BOOL result = @@ -87,7 +88,7 @@ LSSharedFileListItemRef GetLoginItemForApp() { } scoped_nsobject<NSArray> login_items_array( - mac_util::CFToNSCast(LSSharedFileListCopySnapshot(login_items, NULL))); + CFToNSCast(LSSharedFileListCopySnapshot(login_items, NULL))); NSURL* url = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]; @@ -125,9 +126,7 @@ bool IsHiddenLoginItem(LSSharedFileListItemRef item) { return hidden && hidden == kCFBooleanTrue; } -} // end namespace - -namespace mac_util { +} // namespace std::string PathFromFSRef(const FSRef& ref) { ScopedCFTypeRef<CFURLRef> url( @@ -713,4 +712,5 @@ void NSObjectRelease(void* obj) { [nsobj release]; } -} // namespace mac_util +} // namespace mac +} // namespace base diff --git a/base/mac_util_unittest.mm b/base/mac/mac_util_unittest.mm index 63ea9b2..47ecebf 100644 --- a/base/mac_util_unittest.mm +++ b/base/mac/mac_util_unittest.mm @@ -5,7 +5,7 @@ #import <Cocoa/Cocoa.h> #include <vector> -#include "base/mac_util.h" +#include "base/mac/mac_util.h" #include "base/file_path.h" #include "base/file_util.h" @@ -16,7 +16,8 @@ #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" -namespace mac_util { +namespace base { +namespace mac { namespace { @@ -151,7 +152,7 @@ TEST_F(MacUtilTest, TestExcludeFileFromBackups) { } TEST_F(MacUtilTest, TestGetValueFromDictionary) { - base::mac::ScopedCFTypeRef<CFMutableDictionaryRef> dict( + ScopedCFTypeRef<CFMutableDictionaryRef> dict( CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -175,8 +176,7 @@ TEST_F(MacUtilTest, CopyNSImageToCGImage) { NSRectFill(rect); [nsImage unlockFocus]; - base::mac::ScopedCFTypeRef<CGImageRef> cgImage( - mac_util::CopyNSImageToCGImage(nsImage.get())); + ScopedCFTypeRef<CGImageRef> cgImage(CopyNSImageToCGImage(nsImage.get())); EXPECT_TRUE(cgImage.get()); } @@ -184,13 +184,14 @@ TEST_F(MacUtilTest, NSObjectRetainRelease) { scoped_nsobject<NSArray> array([[NSArray alloc] initWithObjects:@"foo", nil]); EXPECT_EQ(1U, [array retainCount]); - mac_util::NSObjectRetain(array); + NSObjectRetain(array); EXPECT_EQ(2U, [array retainCount]); - mac_util::NSObjectRelease(array); + NSObjectRelease(array); EXPECT_EQ(1U, [array retainCount]); } } // namespace -} // namespace mac_util +} // namespace mac +} // namespace base diff --git a/base/debug_util_mac.cc b/base/mac/os_crash_dumps.cc index a4eed66..e82fd73 100644 --- a/base/debug_util_mac.cc +++ b/base/mac/os_crash_dumps.cc @@ -1,23 +1,29 @@ -// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/debug_util.h" +#include "base/mac/os_crash_dumps.h" #include <signal.h> #include <unistd.h> #include "base/basictypes.h" -static void ExitSignalHandler(int sig) { +namespace base { +namespace mac { + +namespace { + +void ExitSignalHandler(int sig) { // A call to exit() can call atexit() handlers. If we SIGSEGV due // to a corrupt heap, and if we have an atexit handler that // allocates or frees memory, we are in trouble if we do not _exit. _exit(128 + sig); } -// static -void DebugUtil::DisableOSCrashDumps() { +} // namespace + +void DisableOSCrashDumps() { // These are the POSIX signals corresponding to the Mach exceptions that // Apple Crash Reporter handles. See ux_exception() in xnu's // bsd/uxkern/ux_exception.c and machine_exception() in xnu's @@ -31,7 +37,9 @@ void DebugUtil::DisableOSCrashDumps() { }; // For all these signals, just wire things up so we exit immediately. - for (size_t i = 0; i < arraysize(signals_to_intercept); ++i) { + for (size_t i = 0; i < arraysize(signals_to_intercept); ++i) signal(signals_to_intercept[i], ExitSignalHandler); - } } + +} // namespace mac +} // namespace base diff --git a/base/mac/os_crash_dumps.h b/base/mac/os_crash_dumps.h new file mode 100644 index 0000000..9758575 --- /dev/null +++ b/base/mac/os_crash_dumps.h @@ -0,0 +1,20 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_MAC_OS_CRASH_DUMPS_H_ +#define BASE_MAC_OS_CRASH_DUMPS_H_ + +namespace base { +namespace mac { + +// On Mac OS X, it can take a really long time for the OS crash handler to +// process a Chrome crash when debugging symbols are available. This +// translates into a long wait until the process actually dies. This call +// disables Apple Crash Reporter entirely. +void DisableOSCrashDumps(); + +} // namespace mac +} // namespace base + +#endif // BASE_MAC_OS_CRASH_DUMPS_H_ diff --git a/base/message_loop.cc b/base/message_loop.cc index d3766b1..7e35d9f 100644 --- a/base/message_loop.cc +++ b/base/message_loop.cc @@ -11,7 +11,8 @@ #include "base/logging.h" #include "base/message_pump_default.h" #include "base/metrics/histogram.h" -#include "base/thread_local.h" +#include "base/third_party/dynamic_annotations/dynamic_annotations.h" +#include "base/threading/thread_local.h" #if defined(OS_MACOSX) #include "base/message_pump_mac.h" @@ -112,14 +113,6 @@ MessageLoop::DestructionObserver::~DestructionObserver() { //------------------------------------------------------------------------------ -// static -MessageLoop* MessageLoop::current() { - // TODO(darin): sadly, we cannot enable this yet since people call us even - // when they have no intention of using us. - // DCHECK(loop) << "Ouch, did you forget to initialize me?"; - return lazy_tls_ptr.Pointer()->Get(); -} - MessageLoop::MessageLoop(Type type) : type_(type), nestable_tasks_allowed_(true), @@ -194,6 +187,19 @@ MessageLoop::~MessageLoop() { lazy_tls_ptr.Pointer()->Set(NULL); } +// static +MessageLoop* MessageLoop::current() { + // TODO(darin): sadly, we cannot enable this yet since people call us even + // when they have no intention of using us. + // DCHECK(loop) << "Ouch, did you forget to initialize me?"; + return lazy_tls_ptr.Pointer()->Get(); +} + +// static +void MessageLoop::EnableHistogrammer(bool enable) { + enable_histogrammer_ = enable; +} + void MessageLoop::AddDestructionObserver( DestructionObserver* destruction_observer) { DCHECK_EQ(this, current()); @@ -206,14 +212,24 @@ void MessageLoop::RemoveDestructionObserver( destruction_observers_.RemoveObserver(destruction_observer); } -void MessageLoop::AddTaskObserver(TaskObserver* task_observer) { - DCHECK_EQ(this, current()); - task_observers_.AddObserver(task_observer); +void MessageLoop::PostTask( + const tracked_objects::Location& from_here, Task* task) { + PostTask_Helper(from_here, task, 0, true); } -void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) { - DCHECK_EQ(this, current()); - task_observers_.RemoveObserver(task_observer); +void MessageLoop::PostDelayedTask( + const tracked_objects::Location& from_here, Task* task, int64 delay_ms) { + PostTask_Helper(from_here, task, delay_ms, true); +} + +void MessageLoop::PostNonNestableTask( + const tracked_objects::Location& from_here, Task* task) { + PostTask_Helper(from_here, task, 0, false); +} + +void MessageLoop::PostNonNestableDelayedTask( + const tracked_objects::Location& from_here, Task* task, int64 delay_ms) { + PostTask_Helper(from_here, task, delay_ms, false); } void MessageLoop::Run() { @@ -227,6 +243,54 @@ void MessageLoop::RunAllPending() { RunHandler(); } +void MessageLoop::Quit() { + DCHECK_EQ(this, current()); + if (state_) { + state_->quit_received = true; + } else { + NOTREACHED() << "Must be inside Run to call Quit"; + } +} + +void MessageLoop::QuitNow() { + DCHECK_EQ(this, current()); + if (state_) { + pump_->Quit(); + } else { + NOTREACHED() << "Must be inside Run to call Quit"; + } +} + +void MessageLoop::SetNestableTasksAllowed(bool allowed) { + if (nestable_tasks_allowed_ != allowed) { + nestable_tasks_allowed_ = allowed; + if (!nestable_tasks_allowed_) + return; + // Start the native pump if we are not already pumping. + pump_->ScheduleWork(); + } +} + +bool MessageLoop::NestableTasksAllowed() const { + return nestable_tasks_allowed_; +} + +bool MessageLoop::IsNested() { + return state_->run_depth > 1; +} + +void MessageLoop::AddTaskObserver(TaskObserver* task_observer) { + DCHECK_EQ(this, current()); + task_observers_.AddObserver(task_observer); +} + +void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) { + DCHECK_EQ(this, current()); + task_observers_.RemoveObserver(task_observer); +} + +//------------------------------------------------------------------------------ + // Runs the loop in two different SEH modes: // enable_SEH_restoration_ = false : any unhandled exception goes to the last // one that calls SetUnhandledExceptionFilter(). @@ -242,7 +306,7 @@ void MessageLoop::RunHandler() { RunInternal(); } -//------------------------------------------------------------------------------ + #if defined(OS_WIN) __declspec(noinline) void MessageLoop::RunInternalInSEHFrame() { LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter(); @@ -253,7 +317,6 @@ __declspec(noinline) void MessageLoop::RunInternalInSEHFrame() { return; } #endif -//------------------------------------------------------------------------------ void MessageLoop::RunInternal() { DCHECK_EQ(this, current()); @@ -273,9 +336,6 @@ void MessageLoop::RunInternal() { pump_->Run(this); } -//------------------------------------------------------------------------------ -// Wrapper functions for use in above message loop framework. - bool MessageLoop::ProcessNextDelayedNonNestableTask() { if (state_->run_depth != 1) return false; @@ -290,130 +350,6 @@ bool MessageLoop::ProcessNextDelayedNonNestableTask() { return true; } -//------------------------------------------------------------------------------ - -void MessageLoop::Quit() { - DCHECK_EQ(this, current()); - if (state_) { - state_->quit_received = true; - } else { - NOTREACHED() << "Must be inside Run to call Quit"; - } -} - -void MessageLoop::QuitNow() { - DCHECK_EQ(this, current()); - if (state_) { - pump_->Quit(); - } else { - NOTREACHED() << "Must be inside Run to call Quit"; - } -} - -void MessageLoop::PostTask( - const tracked_objects::Location& from_here, Task* task) { - PostTask_Helper(from_here, task, 0, true); -} - -void MessageLoop::PostDelayedTask( - const tracked_objects::Location& from_here, Task* task, int64 delay_ms) { - PostTask_Helper(from_here, task, delay_ms, true); -} - -void MessageLoop::PostNonNestableTask( - const tracked_objects::Location& from_here, Task* task) { - PostTask_Helper(from_here, task, 0, false); -} - -void MessageLoop::PostNonNestableDelayedTask( - const tracked_objects::Location& from_here, Task* task, int64 delay_ms) { - PostTask_Helper(from_here, task, delay_ms, false); -} - -// Possibly called on a background thread! -void MessageLoop::PostTask_Helper( - const tracked_objects::Location& from_here, Task* task, int64 delay_ms, - bool nestable) { - task->SetBirthPlace(from_here); - - PendingTask pending_task(task, nestable); - - if (delay_ms > 0) { - pending_task.delayed_run_time = - TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms); - -#if defined(OS_WIN) - if (high_resolution_timer_expiration_.is_null()) { - // Windows timers are granular to 15.6ms. If we only set high-res - // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms, - // which as a percentage is pretty inaccurate. So enable high - // res timers for any timer which is within 2x of the granularity. - // This is a tradeoff between accuracy and power management. - bool needs_high_res_timers = - delay_ms < (2 * base::Time::kMinLowResolutionThresholdMs); - if (needs_high_res_timers) { - base::Time::ActivateHighResolutionTimer(true); - high_resolution_timer_expiration_ = TimeTicks::Now() + - TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs); - } - } -#endif - } else { - DCHECK_EQ(delay_ms, 0) << "delay should not be negative"; - } - -#if defined(OS_WIN) - if (!high_resolution_timer_expiration_.is_null()) { - if (TimeTicks::Now() > high_resolution_timer_expiration_) { - base::Time::ActivateHighResolutionTimer(false); - high_resolution_timer_expiration_ = TimeTicks(); - } - } -#endif - - // Warning: Don't try to short-circuit, and handle this thread's tasks more - // directly, as it could starve handling of foreign threads. Put every task - // into this queue. - - scoped_refptr<base::MessagePump> pump; - { - AutoLock locked(incoming_queue_lock_); - - bool was_empty = incoming_queue_.empty(); - incoming_queue_.push(pending_task); - if (!was_empty) - return; // Someone else should have started the sub-pump. - - pump = pump_; - } - // Since the incoming_queue_ may contain a task that destroys this message - // loop, we cannot exit incoming_queue_lock_ until we are done with |this|. - // We use a stack-based reference to the message pump so that we can call - // ScheduleWork outside of incoming_queue_lock_. - - pump->ScheduleWork(); -} - -void MessageLoop::SetNestableTasksAllowed(bool allowed) { - if (nestable_tasks_allowed_ != allowed) { - nestable_tasks_allowed_ = allowed; - if (!nestable_tasks_allowed_) - return; - // Start the native pump if we are not already pumping. - pump_->ScheduleWork(); - } -} - -bool MessageLoop::NestableTasksAllowed() const { - return nestable_tasks_allowed_; -} - -bool MessageLoop::IsNested() { - return state_->run_depth > 1; -} - -//------------------------------------------------------------------------------ - void MessageLoop::RunTask(Task* task) { DCHECK(nestable_tasks_allowed_); // Execute the task and assume the worst: It is probably not reentrant. @@ -487,8 +423,8 @@ bool MessageLoop::DeletePendingTasks() { // Valgrind. #if defined(PURIFY) || defined(USE_HEAPCHECKER) delete pending_task.task; -#elif defined(OS_POSIX) - if (RUNNING_ON_VALGRIND) +#else + if (RunningOnValgrind()) delete pending_task.task; #endif // defined(OS_POSIX) } @@ -500,8 +436,8 @@ bool MessageLoop::DeletePendingTasks() { Task* task = NULL; #if defined(PURIFY) || defined(USE_HEAPCHECKER) task = deferred_non_nestable_work_queue_.front().task; -#elif defined(OS_POSIX) - if (RUNNING_ON_VALGRIND) +#else + if (RunningOnValgrind()) task = deferred_non_nestable_work_queue_.front().task; #endif deferred_non_nestable_work_queue_.pop(); @@ -517,6 +453,92 @@ bool MessageLoop::DeletePendingTasks() { return did_work; } +// Possibly called on a background thread! +void MessageLoop::PostTask_Helper( + const tracked_objects::Location& from_here, Task* task, int64 delay_ms, + bool nestable) { + task->SetBirthPlace(from_here); + + PendingTask pending_task(task, nestable); + + if (delay_ms > 0) { + pending_task.delayed_run_time = + TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms); + +#if defined(OS_WIN) + if (high_resolution_timer_expiration_.is_null()) { + // Windows timers are granular to 15.6ms. If we only set high-res + // timers for those under 15.6ms, then a 18ms timer ticks at ~32ms, + // which as a percentage is pretty inaccurate. So enable high + // res timers for any timer which is within 2x of the granularity. + // This is a tradeoff between accuracy and power management. + bool needs_high_res_timers = + delay_ms < (2 * base::Time::kMinLowResolutionThresholdMs); + if (needs_high_res_timers) { + base::Time::ActivateHighResolutionTimer(true); + high_resolution_timer_expiration_ = TimeTicks::Now() + + TimeDelta::FromMilliseconds(kHighResolutionTimerModeLeaseTimeMs); + } + } +#endif + } else { + DCHECK_EQ(delay_ms, 0) << "delay should not be negative"; + } + +#if defined(OS_WIN) + if (!high_resolution_timer_expiration_.is_null()) { + if (TimeTicks::Now() > high_resolution_timer_expiration_) { + base::Time::ActivateHighResolutionTimer(false); + high_resolution_timer_expiration_ = TimeTicks(); + } + } +#endif + + // Warning: Don't try to short-circuit, and handle this thread's tasks more + // directly, as it could starve handling of foreign threads. Put every task + // into this queue. + + scoped_refptr<base::MessagePump> pump; + { + AutoLock locked(incoming_queue_lock_); + + bool was_empty = incoming_queue_.empty(); + incoming_queue_.push(pending_task); + if (!was_empty) + return; // Someone else should have started the sub-pump. + + pump = pump_; + } + // Since the incoming_queue_ may contain a task that destroys this message + // loop, we cannot exit incoming_queue_lock_ until we are done with |this|. + // We use a stack-based reference to the message pump so that we can call + // ScheduleWork outside of incoming_queue_lock_. + + pump->ScheduleWork(); +} + +//------------------------------------------------------------------------------ +// Method and data for histogramming events and actions taken by each instance +// on each thread. + +void MessageLoop::StartHistogrammer() { + if (enable_histogrammer_ && !message_histogram_.get() + && base::StatisticsRecorder::IsActive()) { + DCHECK(!thread_name_.empty()); + message_histogram_ = base::LinearHistogram::FactoryGet( + "MsgLoop:" + thread_name_, + kLeastNonZeroMessageId, kMaxMessageId, + kNumberOfDistinctMessagesDisplayed, + message_histogram_->kHexRangePrintingFlag); + message_histogram_->SetRangeDescriptions(event_descriptions_); + } +} + +void MessageLoop::HistogramEvent(int event) { + if (message_histogram_.get()) + message_histogram_->Add(event); +} + bool MessageLoop::DoWork() { if (!nestable_tasks_allowed_) { // Task can't be executed right now. @@ -633,33 +655,6 @@ bool MessageLoop::PendingTask::operator<(const PendingTask& other) const { } //------------------------------------------------------------------------------ -// Method and data for histogramming events and actions taken by each instance -// on each thread. - -// static -void MessageLoop::EnableHistogrammer(bool enable) { - enable_histogrammer_ = enable; -} - -void MessageLoop::StartHistogrammer() { - if (enable_histogrammer_ && !message_histogram_.get() - && base::StatisticsRecorder::IsActive()) { - DCHECK(!thread_name_.empty()); - message_histogram_ = base::LinearHistogram::FactoryGet( - "MsgLoop:" + thread_name_, - kLeastNonZeroMessageId, kMaxMessageId, - kNumberOfDistinctMessagesDisplayed, - message_histogram_->kHexRangePrintingFlag); - message_histogram_->SetRangeDescriptions(event_descriptions_); - } -} - -void MessageLoop::HistogramEvent(int event) { - if (message_histogram_.get()) - message_histogram_->Add(event); -} - -//------------------------------------------------------------------------------ // MessageLoopForUI #if defined(OS_WIN) diff --git a/base/message_loop.h b/base/message_loop.h index a5a94bc..d5093a9 100644 --- a/base/message_loop.h +++ b/base/message_loop.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. @@ -66,23 +66,45 @@ class Histogram; // class MessageLoop : public base::MessagePump::Delegate { public: - // A TaskObserver is an object that receives task notifications from the - // MessageLoop. - // - // NOTE: A TaskObserver implementation should be extremely fast! - class TaskObserver { - public: - TaskObserver(); +#if defined(OS_WIN) + typedef base::MessagePumpWin::Dispatcher Dispatcher; + typedef base::MessagePumpForUI::Observer Observer; +#elif !defined(OS_MACOSX) +#if defined(TOUCH_UI) + typedef base::MessagePumpGlibXDispatcher Dispatcher; +#else + typedef base::MessagePumpForUI::Dispatcher Dispatcher; +#endif + typedef base::MessagePumpForUI::Observer Observer; +#endif - // This method is called before processing a task. - virtual void WillProcessTask(const Task* task) = 0; + // A MessageLoop has a particular type, which indicates the set of + // asynchronous events it may process in addition to tasks and timers. + // + // TYPE_DEFAULT + // This type of ML only supports tasks and timers. + // + // TYPE_UI + // This type of ML also supports native UI events (e.g., Windows messages). + // See also MessageLoopForUI. + // + // TYPE_IO + // This type of ML also supports asynchronous IO. See also + // MessageLoopForIO. + // + enum Type { + TYPE_DEFAULT, + TYPE_UI, + TYPE_IO + }; - // This method is called after processing a task. - virtual void DidProcessTask(const Task* task) = 0; + // Normally, it is not necessary to instantiate a MessageLoop. Instead, it + // is typical to make use of the current thread's MessageLoop instance. + explicit MessageLoop(Type type = TYPE_DEFAULT); + ~MessageLoop(); - protected: - virtual ~TaskObserver(); - }; + // Returns the MessageLoop object for the current thread, or null if none. + static MessageLoop* current(); static void EnableHistogrammer(bool enable_histogrammer); @@ -200,31 +222,6 @@ class MessageLoop : public base::MessagePump::Delegate { } }; - // A MessageLoop has a particular type, which indicates the set of - // asynchronous events it may process in addition to tasks and timers. - // - // TYPE_DEFAULT - // This type of ML only supports tasks and timers. - // - // TYPE_UI - // This type of ML also supports native UI events (e.g., Windows messages). - // See also MessageLoopForUI. - // - // TYPE_IO - // This type of ML also supports asynchronous IO. See also - // MessageLoopForIO. - // - enum Type { - TYPE_DEFAULT, - TYPE_UI, - TYPE_IO - }; - - // Normally, it is not necessary to instantiate a MessageLoop. Instead, it - // is typical to make use of the current thread's MessageLoop instance. - explicit MessageLoop(Type type = TYPE_DEFAULT); - ~MessageLoop(); - // Returns the type passed to the constructor. Type type() const { return type_; } @@ -235,9 +232,6 @@ class MessageLoop : public base::MessagePump::Delegate { } const std::string& thread_name() const { return thread_name_; } - // Returns the MessageLoop object for the current thread, or null if none. - static MessageLoop* current(); - // Enables or disables the recursive task processing. This happens in the case // of recursive message loops. Some unwanted message loop may occurs when // using common controls or printer functions. By default, recursive task @@ -284,23 +278,29 @@ class MessageLoop : public base::MessagePump::Delegate { // Returns true if we are currently running a nested message loop. bool IsNested(); + // A TaskObserver is an object that receives task notifications from the + // MessageLoop. + // + // NOTE: A TaskObserver implementation should be extremely fast! + class TaskObserver { + public: + TaskObserver(); + + // This method is called before processing a task. + virtual void WillProcessTask(const Task* task) = 0; + + // This method is called after processing a task. + virtual void DidProcessTask(const Task* task) = 0; + + protected: + virtual ~TaskObserver(); + }; + // These functions can only be called on the same thread that |this| is // running on. void AddTaskObserver(TaskObserver* task_observer); void RemoveTaskObserver(TaskObserver* task_observer); -#if defined(OS_WIN) - typedef base::MessagePumpWin::Dispatcher Dispatcher; - typedef base::MessagePumpForUI::Observer Observer; -#elif !defined(OS_MACOSX) -#if defined(TOUCH_UI) - typedef base::MessagePumpGlibXDispatcher Dispatcher; -#else - typedef base::MessagePumpForUI::Dispatcher Dispatcher; -#endif - typedef base::MessagePumpForUI::Observer Observer; -#endif - // Returns true if the message loop has high resolution timers enabled. // Provided for testing. bool high_resolution_timers_enabled() { @@ -341,17 +341,17 @@ class MessageLoop : public base::MessagePump::Delegate { // This structure is copied around by value. struct PendingTask { - Task* task; // The task to run. - base::TimeTicks delayed_run_time; // The time when the task should be run. - int sequence_num; // Secondary sort key for run time. - bool nestable; // OK to dispatch from a nested loop. - PendingTask(Task* task, bool nestable) : task(task), sequence_num(0), nestable(nestable) { } // Used to support sorting. bool operator<(const PendingTask& other) const; + + Task* task; // The task to run. + base::TimeTicks delayed_run_time; // The time when the task should be run. + int sequence_num; // Secondary sort key for run time. + bool nestable; // OK to dispatch from a nested loop. }; class TaskQueue : public std::queue<PendingTask> { @@ -391,18 +391,6 @@ class MessageLoop : public base::MessagePump::Delegate { // Called to process any delayed non-nestable tasks. bool ProcessNextDelayedNonNestableTask(); - //---------------------------------------------------------------------------- - // Run a work_queue_ task or new_task, and delete it (if it was processed by - // PostTask). If there are queued tasks, the oldest one is executed and - // new_task is queued. new_task is optional and can be NULL. In this NULL - // case, the method will run one pending task (if any exist). Returns true if - // it executes a task. Queued tasks accumulate only when there is a - // non-nestable task currently processing, in which case the new_task is - // appended to the list work_queue_. Such re-entrancy generally happens when - // an unrequested message pump (typical of a native dialog) is executing in - // the context of a task. - bool QueueOrRunTask(Task* new_task); - // Runs the specified task and deletes it. void RunTask(Task* task); @@ -427,11 +415,6 @@ class MessageLoop : public base::MessagePump::Delegate { void PostTask_Helper(const tracked_objects::Location& from_here, Task* task, int64 delay_ms, bool nestable); - // base::MessagePump::Delegate methods: - virtual bool DoWork(); - virtual bool DoDelayedWork(base::TimeTicks* next_delayed_work_time); - virtual bool DoIdleWork(); - // Start recording histogram info about events and action IF it was enabled // and IF the statistics recorder can accept a registration of our histogram. void StartHistogrammer(); @@ -441,6 +424,11 @@ class MessageLoop : public base::MessagePump::Delegate { // If message_histogram_ is NULL, this is a no-op. void HistogramEvent(int event); + // base::MessagePump::Delegate methods: + virtual bool DoWork(); + virtual bool DoDelayedWork(base::TimeTicks* next_delayed_work_time); + virtual bool DoIdleWork(); + Type type_; // A list of tasks that need to be processed by this instance. Note that diff --git a/base/message_loop_proxy_impl.cc b/base/message_loop_proxy_impl.cc index c0619aa..3b01fd6 100644 --- a/base/message_loop_proxy_impl.cc +++ b/base/message_loop_proxy_impl.cc @@ -3,7 +3,7 @@ // found in the LICENSE file. #include "base/message_loop_proxy_impl.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" namespace base { diff --git a/base/message_loop_proxy_impl_unittest.cc b/base/message_loop_proxy_impl_unittest.cc index 8d8ef4e..61c7850 100644 --- a/base/message_loop_proxy_impl_unittest.cc +++ b/base/message_loop_proxy_impl_unittest.cc @@ -5,7 +5,7 @@ #include "base/message_loop.h" #include "base/message_loop_proxy_impl.h" #include "base/scoped_ptr.h" -#include "base/thread.h" +#include "base/threading/thread.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" diff --git a/base/message_loop_unittest.cc b/base/message_loop_unittest.cc index a196519..c471e38 100644 --- a/base/message_loop_unittest.cc +++ b/base/message_loop_unittest.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -7,20 +7,21 @@ #include "base/eintr_wrapper.h" #include "base/logging.h" #include "base/message_loop.h" -#include "base/platform_thread.h" #include "base/ref_counted.h" #include "base/task.h" -#include "base/thread.h" +#include "base/threading/platform_thread.h" +#include "base/threading/thread.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_WIN) #include "base/message_pump_win.h" -#include "base/scoped_handle.h" +#include "base/win/scoped_handle.h" #endif #if defined(OS_POSIX) #include "base/message_pump_libevent.h" #endif +using base::PlatformThread; using base::Thread; using base::Time; using base::TimeDelta; @@ -936,7 +937,7 @@ void RunTest_RecursiveDenial2(MessageLoop::Type message_loop_type) { options.message_loop_type = message_loop_type; ASSERT_EQ(true, worker.StartWithOptions(options)); TaskList order; - ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL)); + base::win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL)); worker.message_loop()->PostTask(FROM_HERE, new Recursive2Tasks(MessageLoop::current(), event, @@ -979,7 +980,7 @@ void RunTest_RecursiveSupport2(MessageLoop::Type message_loop_type) { options.message_loop_type = message_loop_type; ASSERT_EQ(true, worker.StartWithOptions(options)); TaskList order; - ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL)); + base::win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL)); worker.message_loop()->PostTask(FROM_HERE, new Recursive2Tasks(MessageLoop::current(), event, @@ -1186,7 +1187,7 @@ class TestIOHandler : public MessageLoopForIO::IOHandler { char buffer_[48]; MessageLoopForIO::IOContext context_; HANDLE signal_; - ScopedHandle file_; + base::win::ScopedHandle file_; bool wait_; }; @@ -1234,12 +1235,12 @@ class IOHandlerTask : public Task { }; void RunTest_IOHandler() { - ScopedHandle callback_called(CreateEvent(NULL, TRUE, FALSE, NULL)); + base::win::ScopedHandle callback_called(CreateEvent(NULL, TRUE, FALSE, NULL)); ASSERT_TRUE(callback_called.IsValid()); const wchar_t* kPipeName = L"\\\\.\\pipe\\iohandler_pipe"; - ScopedHandle server(CreateNamedPipe(kPipeName, PIPE_ACCESS_OUTBOUND, 0, 1, - 0, 0, 0, NULL)); + base::win::ScopedHandle server( + CreateNamedPipe(kPipeName, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL)); ASSERT_TRUE(server.IsValid()); Thread thread("IOHandler test"); @@ -1266,17 +1267,19 @@ void RunTest_IOHandler() { } void RunTest_WaitForIO() { - ScopedHandle callback1_called(CreateEvent(NULL, TRUE, FALSE, NULL)); - ScopedHandle callback2_called(CreateEvent(NULL, TRUE, FALSE, NULL)); + base::win::ScopedHandle callback1_called( + CreateEvent(NULL, TRUE, FALSE, NULL)); + base::win::ScopedHandle callback2_called( + CreateEvent(NULL, TRUE, FALSE, NULL)); ASSERT_TRUE(callback1_called.IsValid()); ASSERT_TRUE(callback2_called.IsValid()); const wchar_t* kPipeName1 = L"\\\\.\\pipe\\iohandler_pipe1"; const wchar_t* kPipeName2 = L"\\\\.\\pipe\\iohandler_pipe2"; - ScopedHandle server1(CreateNamedPipe(kPipeName1, PIPE_ACCESS_OUTBOUND, 0, 1, - 0, 0, 0, NULL)); - ScopedHandle server2(CreateNamedPipe(kPipeName2, PIPE_ACCESS_OUTBOUND, 0, 1, - 0, 0, 0, NULL)); + base::win::ScopedHandle server1( + CreateNamedPipe(kPipeName1, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL)); + base::win::ScopedHandle server2( + CreateNamedPipe(kPipeName2, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL)); ASSERT_TRUE(server1.IsValid()); ASSERT_TRUE(server2.IsValid()); diff --git a/base/message_pump_default.h b/base/message_pump_default.h index 3dfbf1c..5030aa9 100644 --- a/base/message_pump_default.h +++ b/base/message_pump_default.h @@ -8,7 +8,7 @@ #include "base/message_pump.h" #include "base/time.h" -#include "base/waitable_event.h" +#include "base/synchronization/waitable_event.h" namespace base { diff --git a/base/message_pump_glib.cc b/base/message_pump_glib.cc index fd24285..b9dcc46 100644 --- a/base/message_pump_glib.cc +++ b/base/message_pump_glib.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -12,7 +12,7 @@ #include "base/eintr_wrapper.h" #include "base/logging.h" -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" namespace { @@ -177,8 +177,8 @@ void MessagePumpForUI::RunWithDispatcher(Delegate* delegate, #ifndef NDEBUG // Make sure we only run this on one thread. GTK only has one message pump // so we can only have one UI loop per process. - static PlatformThreadId thread_id = PlatformThread::CurrentId(); - DCHECK(thread_id == PlatformThread::CurrentId()) << + static base::PlatformThreadId thread_id = base::PlatformThread::CurrentId(); + DCHECK(thread_id == base::PlatformThread::CurrentId()) << "Running MessagePumpForUI on two different threads; " "this is unsupported by GLib!"; #endif diff --git a/base/message_pump_glib.h b/base/message_pump_glib.h index c118155..70bf108 100644 --- a/base/message_pump_glib.h +++ b/base/message_pump_glib.h @@ -1,4 +1,4 @@ -// Copyright (c) 2008 The Chromium Authors. All rights reserved. +// 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. @@ -62,11 +62,6 @@ class MessagePumpForUI : public MessagePump { // is ready for processing. virtual bool RunOnce(GMainContext* context, bool block); - virtual void Run(Delegate* delegate); - virtual void Quit(); - virtual void ScheduleWork(); - virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time); - // Internal methods used for processing the pump callbacks. They are // public for simplicity but should not be used directly. HandlePrepare // is called during the prepare step of glib, and returns a timeout that @@ -88,6 +83,12 @@ class MessagePumpForUI : public MessagePump { // some task before/after calling the default handler (EventDispatcher). virtual void DispatchEvents(GdkEvent* event); + // Overridden from MessagePump: + virtual void Run(Delegate* delegate); + virtual void Quit(); + virtual void ScheduleWork(); + virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time); + protected: // Returns the dispatcher for the current run state (|state_->dispatcher|). Dispatcher* GetDispatcher(); diff --git a/base/message_pump_glib_unittest.cc b/base/message_pump_glib_unittest.cc index 72d2fbf..9c9f288 100644 --- a/base/message_pump_glib_unittest.cc +++ b/base/message_pump_glib_unittest.cc @@ -11,9 +11,8 @@ #include <vector> #include "base/message_loop.h" -#include "base/platform_thread.h" #include "base/ref_counted.h" -#include "base/thread.h" +#include "base/threading/thread.h" #include "testing/gtest/include/gtest/gtest.h" namespace { diff --git a/base/message_pump_glib_x.cc b/base/message_pump_glib_x.cc index 26c4b87..775e940 100644 --- a/base/message_pump_glib_x.cc +++ b/base/message_pump_glib_x.cc @@ -84,6 +84,9 @@ MessagePumpGlibX::~MessagePumpGlibX() { bool MessagePumpGlibX::RunOnce(GMainContext* context, bool block) { GdkDisplay* gdisp = gdk_display_get_default(); + if (!gdisp) + return MessagePumpForUI::RunOnce(context, block); + Display* display = GDK_DISPLAY_XDISPLAY(gdisp); bool should_quit = false; @@ -189,6 +192,9 @@ void MessagePumpGlibX::InitializeEventsToCapture(void) { #if defined(HAVE_XINPUT2) void MessagePumpGlibX::InitializeXInput2(void) { GdkDisplay* display = gdk_display_get_default(); + if (!display) + return; + Display* xdisplay = GDK_DISPLAY_XDISPLAY(display); int event, err; diff --git a/base/message_pump_glib_x.h b/base/message_pump_glib_x.h index fc3f3b1..e94b797 100644 --- a/base/message_pump_glib_x.h +++ b/base/message_pump_glib_x.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -22,9 +22,6 @@ class MessagePumpGlibX : public MessagePumpForUI { MessagePumpGlibX(); virtual ~MessagePumpGlibX(); - // MessagePumpForUI implementation. - virtual bool RunOnce(GMainContext* context, bool block); - // Indicates whether a GDK event was injected by chrome (when |true|) or if it // was captured and being processed by GDK (when |false|). bool IsDispatchingEvent(void) { return dispatching_event_; } @@ -34,6 +31,9 @@ class MessagePumpGlibX : public MessagePumpForUI { void SetupXInput2ForXWindow(Window xid); #endif + // Overridden from MessagePumpForUI: + virtual bool RunOnce(GMainContext* context, bool block); + private: static void EventDispatcherX(GdkEvent* event, gpointer data); diff --git a/base/message_pump_glib_x_dispatch.h b/base/message_pump_glib_x_dispatch.h index faee5b5..4a97372 100644 --- a/base/message_pump_glib_x_dispatch.h +++ b/base/message_pump_glib_x_dispatch.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -18,13 +18,12 @@ namespace base { // GdkEvents. This class provides additional mechanism for dispatching XEvents. class MessagePumpGlibXDispatcher : public MessagePumpForUI::Dispatcher { public: - - typedef enum { + enum DispatchStatus { EVENT_IGNORED, // The event was not processed. EVENT_PROCESSED, // The event has been processed. EVENT_QUIT // The event was processed and the message-loop should // terminate. - } DispatchStatus; + }; // Dispatches the event. EVENT_IGNORED is returned if the event was ignored // (i.e. not processed). EVENT_PROCESSED is returned if the event was diff --git a/base/message_pump_libevent.h b/base/message_pump_libevent.h index d8d000d..2ade511 100644 --- a/base/message_pump_libevent.h +++ b/base/message_pump_libevent.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. @@ -86,15 +86,15 @@ class MessagePumpLibevent : public MessagePump { DISALLOW_COPY_AND_ASSIGN(FileDescriptorWatcher); }; - MessagePumpLibevent(); - virtual ~MessagePumpLibevent(); - enum Mode { WATCH_READ = 1 << 0, WATCH_WRITE = 1 << 1, WATCH_READ_WRITE = WATCH_READ | WATCH_WRITE }; + MessagePumpLibevent(); + virtual ~MessagePumpLibevent(); + // Have the current thread's message loop watch for a a situation in which // reading/writing to the FD can be performed without blocking. // Callers must provide a preallocated FileDescriptorWatcher object which @@ -128,6 +128,14 @@ class MessagePumpLibevent : public MessagePump { // Risky part of constructor. Returns true on success. bool Init(); + // Called by libevent to tell us a registered FD can be read/written to. + static void OnLibeventNotification(int fd, short flags, + void* context); + + // Unix pipe used to implement ScheduleWork() + // ... callback; called by libevent inside Run() when pipe is ready to read + static void OnWakeup(int socket, short flags, void* context); + // This flag is set to false when Run should return. bool keep_running_; @@ -141,13 +149,6 @@ class MessagePumpLibevent : public MessagePump { // readiness callbacks when a socket is ready for I/O. event_base* event_base_; - // Called by libevent to tell us a registered FD can be read/written to. - static void OnLibeventNotification(int fd, short flags, - void* context); - - // Unix pipe used to implement ScheduleWork() - // ... callback; called by libevent inside Run() when pipe is ready to read - static void OnWakeup(int socket, short flags, void* context); // ... write end; ScheduleWork() writes a single byte to it int wakeup_pipe_in_; // ... read end; OnWakeup reads it and then breaks Run() out of its sleep diff --git a/base/message_pump_win.h b/base/message_pump_win.h index ea7dd39..af97530 100644 --- a/base/message_pump_win.h +++ b/base/message_pump_win.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. @@ -13,8 +13,8 @@ #include "base/basictypes.h" #include "base/message_pump.h" #include "base/observer_list.h" -#include "base/scoped_handle.h" #include "base/time.h" +#include "base/win/scoped_handle.h" namespace base { @@ -356,7 +356,7 @@ class MessagePumpForIO : public MessagePumpWin { void DidProcessIOEvent(); // The completion port associated with this thread. - ScopedHandle port_; + win::ScopedHandle port_; // This list will be empty almost always. It stores IO completions that have // not been delivered yet because somebody was doing cleanup. std::list<IOItem> completed_io_; diff --git a/base/metrics/field_trial.h b/base/metrics/field_trial.h index 1f0af9e..8902077 100644 --- a/base/metrics/field_trial.h +++ b/base/metrics/field_trial.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -217,12 +217,12 @@ class FieldTrialList { static size_t GetFieldTrialCount(); private: - // Helper function should be called only while holding lock_. - FieldTrial* PreLockedFind(const std::string& name); - // A map from FieldTrial names to the actual instances. typedef std::map<std::string, FieldTrial*> RegistrationList; + // Helper function should be called only while holding lock_. + FieldTrial* PreLockedFind(const std::string& name); + static FieldTrialList* global_; // The singleton of this class. // This will tell us if there is an attempt to register a field trial without diff --git a/base/metrics/histogram.cc b/base/metrics/histogram.cc index 75df12e..1526cd8 100644 --- a/base/metrics/histogram.cc +++ b/base/metrics/histogram.cc @@ -14,10 +14,10 @@ #include <algorithm> #include <string> -#include "base/lock.h" #include "base/logging.h" #include "base/pickle.h" #include "base/stringprintf.h" +#include "base/synchronization/lock.h" namespace base { @@ -911,9 +911,9 @@ StatisticsRecorder::StatisticsRecorder() { // during the termination phase. Since it's a static data member, we will // leak one per process, which would be similar to the instance allocated // during static initialization and released only on process termination. - lock_ = new Lock; + lock_ = new base::Lock; } - AutoLock auto_lock(*lock_); + base::AutoLock auto_lock(*lock_); histograms_ = new HistogramMap; } @@ -928,7 +928,7 @@ StatisticsRecorder::~StatisticsRecorder() { // Clean up. HistogramMap* histograms = NULL; { - AutoLock auto_lock(*lock_); + base::AutoLock auto_lock(*lock_); histograms = histograms_; histograms_ = NULL; } @@ -941,7 +941,7 @@ StatisticsRecorder::~StatisticsRecorder() { bool StatisticsRecorder::IsActive() { if (lock_ == NULL) return false; - AutoLock auto_lock(*lock_); + base::AutoLock auto_lock(*lock_); return NULL != histograms_; } @@ -954,7 +954,7 @@ bool StatisticsRecorder::IsActive() { void StatisticsRecorder::Register(Histogram* histogram) { if (lock_ == NULL) return; - AutoLock auto_lock(*lock_); + base::AutoLock auto_lock(*lock_); if (!histograms_) return; const std::string name = histogram->histogram_name(); @@ -1011,7 +1011,7 @@ void StatisticsRecorder::WriteGraph(const std::string& query, void StatisticsRecorder::GetHistograms(Histograms* output) { if (lock_ == NULL) return; - AutoLock auto_lock(*lock_); + base::AutoLock auto_lock(*lock_); if (!histograms_) return; for (HistogramMap::iterator it = histograms_->begin(); @@ -1026,7 +1026,7 @@ bool StatisticsRecorder::FindHistogram(const std::string& name, scoped_refptr<Histogram>* histogram) { if (lock_ == NULL) return false; - AutoLock auto_lock(*lock_); + base::AutoLock auto_lock(*lock_); if (!histograms_) return false; HistogramMap::iterator it = histograms_->find(name); @@ -1041,7 +1041,7 @@ void StatisticsRecorder::GetSnapshot(const std::string& query, Histograms* snapshot) { if (lock_ == NULL) return; - AutoLock auto_lock(*lock_); + base::AutoLock auto_lock(*lock_); if (!histograms_) return; for (HistogramMap::iterator it = histograms_->begin(); @@ -1055,7 +1055,7 @@ void StatisticsRecorder::GetSnapshot(const std::string& query, // static StatisticsRecorder::HistogramMap* StatisticsRecorder::histograms_ = NULL; // static -Lock* StatisticsRecorder::lock_ = NULL; +base::Lock* StatisticsRecorder::lock_ = NULL; // static bool StatisticsRecorder::dump_on_exit_ = false; diff --git a/base/metrics/histogram.h b/base/metrics/histogram.h index 6b09aa3..3bb3f03 100644 --- a/base/metrics/histogram.h +++ b/base/metrics/histogram.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -41,11 +41,12 @@ #include "base/logging.h" #include "base/time.h" -class Lock; class Pickle; namespace base { +class Lock; + //------------------------------------------------------------------------------ // Provide easy general purpose histogram in a macro, just like stats counters. // The first four macros use 50 buckets. @@ -541,11 +542,7 @@ class Histogram : public base::RefCountedThreadSafe<Histogram> { // buckets. class LinearHistogram : public Histogram { public: - virtual ClassType histogram_type() const; - - // Store a list of number/text values for use in rendering the histogram. - // The last element in the array has a null in its "description" slot. - virtual void SetRangeDescriptions(const DescriptionPair descriptions[]); + virtual ~LinearHistogram(); /* minimum should start from 1. 0 is as minimum is invalid. 0 is an implicit default underflow bucket. */ @@ -555,7 +552,12 @@ class LinearHistogram : public Histogram { TimeDelta minimum, TimeDelta maximum, size_t bucket_count, Flags flags); - virtual ~LinearHistogram(); + // Overridden from Histogram: + virtual ClassType histogram_type() const; + + // Store a list of number/text values for use in rendering the histogram. + // The last element in the array has a null in its "description" slot. + virtual void SetRangeDescriptions(const DescriptionPair descriptions[]); protected: LinearHistogram(const std::string& name, Sample minimum, @@ -609,11 +611,13 @@ class BooleanHistogram : public LinearHistogram { // CustomHistogram is a histogram for a set of custom integers. class CustomHistogram : public Histogram { public: - virtual ClassType histogram_type() const; static scoped_refptr<Histogram> FactoryGet(const std::string& name, const std::vector<Sample>& custom_ranges, Flags flags); + // Overridden from Histogram: + virtual ClassType histogram_type() const; + protected: CustomHistogram(const std::string& name, const std::vector<Sample>& custom_ranges); @@ -681,7 +685,7 @@ class StatisticsRecorder { static HistogramMap* histograms_; // lock protects access to the above map. - static Lock* lock_; + static base::Lock* lock_; // Dump all known histograms to log. static bool dump_on_exit_; diff --git a/base/metrics/stats_table.cc b/base/metrics/stats_table.cc index bf93395..757c08e 100644 --- a/base/metrics/stats_table.cc +++ b/base/metrics/stats_table.cc @@ -5,13 +5,13 @@ #include "base/metrics/stats_table.h" #include "base/logging.h" -#include "base/platform_thread.h" #include "base/process_util.h" #include "base/scoped_ptr.h" #include "base/shared_memory.h" #include "base/string_piece.h" #include "base/string_util.h" -#include "base/thread_local_storage.h" +#include "base/threading/platform_thread.h" +#include "base/threading/thread_local_storage.h" #include "base/utf_string_conversions.h" #if defined(OS_POSIX) diff --git a/base/metrics/stats_table.h b/base/metrics/stats_table.h index e83039c..32b22eb 100644 --- a/base/metrics/stats_table.h +++ b/base/metrics/stats_table.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. // @@ -26,7 +26,7 @@ #include "base/basictypes.h" #include "base/hash_tables.h" #include "base/lock.h" -#include "base/thread_local_storage.h" +#include "base/threading/thread_local_storage.h" namespace base { @@ -132,6 +132,7 @@ class StatsTable { private: class Private; struct TLSData; + typedef hash_map<std::string, int> CountersMap; // Returns the space occupied by a thread in the table. Generally used // if a thread terminates but the process continues. This function @@ -171,8 +172,6 @@ class StatsTable { // initialized. TLSData* GetTLSData() const; - typedef hash_map<std::string, int> CountersMap; - Private* impl_; // The counters_lock_ protects the counters_ hash table. @@ -184,7 +183,7 @@ class StatsTable { // we don't have a counter in our hash table, another process may // have created it. CountersMap counters_; - TLSSlot tls_index_; + ThreadLocalStorage::Slot tls_index_; static StatsTable* global_table_; diff --git a/base/metrics/stats_table_unittest.cc b/base/metrics/stats_table_unittest.cc index c9eb9a2..944813d 100644 --- a/base/metrics/stats_table_unittest.cc +++ b/base/metrics/stats_table_unittest.cc @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/platform_thread.h" -#include "base/simple_thread.h" -#include "base/shared_memory.h" -#include "base/metrics/stats_table.h" #include "base/metrics/stats_counters.h" +#include "base/metrics/stats_table.h" +#include "base/shared_memory.h" #include "base/string_piece.h" #include "base/string_util.h" #include "base/test/multiprocess_test.h" +#include "base/threading/platform_thread.h" +#include "base/threading/simple_thread.h" #include "base/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" diff --git a/base/native_library_linux.cc b/base/native_library_linux.cc index d5ab128..e282bce 100644 --- a/base/native_library_linux.cc +++ b/base/native_library_linux.cc @@ -8,7 +8,7 @@ #include "base/file_path.h" #include "base/logging.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" #include "base/utf_string_conversions.h" namespace base { diff --git a/base/native_library_mac.mm b/base/native_library_mac.mm index 0669bee..742d92a 100644 --- a/base/native_library_mac.mm +++ b/base/native_library_mac.mm @@ -10,7 +10,7 @@ #include "base/file_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/string_util.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" #include "base/utf_string_conversions.h" namespace base { diff --git a/base/native_library_win.cc b/base/native_library_win.cc index b8a806b..b77fbe1 100644 --- a/base/native_library_win.cc +++ b/base/native_library_win.cc @@ -7,7 +7,7 @@ #include <windows.h> #include "base/file_util.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" #include "base/utf_string_conversions.h" namespace base { diff --git a/base/nss_util.cc b/base/nss_util.cc index 36394da..b411422 100644 --- a/base/nss_util.cc +++ b/base/nss_util.cc @@ -22,7 +22,7 @@ #include "base/lazy_instance.h" #include "base/logging.h" #include "base/stringprintf.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" // USE_NSS means we use NSS for everything crypto-related. If USE_NSS is not // defined, such as on Mac and Windows, we use NSS for SSL only -- we don't diff --git a/base/nss_util.h b/base/nss_util.h index d1e36ac..2b0139e 100644 --- a/base/nss_util.h +++ b/base/nss_util.h @@ -10,7 +10,6 @@ #if defined(USE_NSS) class FilePath; -class Lock; #endif // defined(USE_NSS) // This file specifically doesn't depend on any NSS or NSPR headers because it @@ -18,6 +17,7 @@ class Lock; // initialization functions. namespace base { +class Lock; class Time; // Initialize NRPR if it isn't already initialized. This function is diff --git a/base/observer_list_unittest.cc b/base/observer_list_unittest.cc index 6b57550..652d358 100644 --- a/base/observer_list_unittest.cc +++ b/base/observer_list_unittest.cc @@ -8,17 +8,15 @@ #include <vector> #include "base/message_loop.h" -#include "base/platform_thread.h" #include "base/ref_counted.h" +#include "base/threading/platform_thread.h" #include "testing/gtest/include/gtest/gtest.h" +using base::PlatformThread; using base::Time; namespace { -class ObserverListTest : public testing::Test { -}; - class Foo { public: virtual void Observe(int x) = 0; @@ -291,7 +289,7 @@ static void ThreadSafeObserverHarness(int num_threads, observer_list->AddObserver(&b); AddRemoveThread* threaded_observer[kMaxThreads]; - PlatformThreadHandle threads[kMaxThreads]; + base::PlatformThreadHandle threads[kMaxThreads]; for (int index = 0; index < num_threads; index++) { threaded_observer[index] = new AddRemoveThread(observer_list.get(), false); EXPECT_TRUE(PlatformThread::Create(0, diff --git a/base/pickle.cc b/base/pickle.cc index 3f376e3..a05df28 100644 --- a/base/pickle.cc +++ b/base/pickle.cc @@ -140,12 +140,6 @@ bool Pickle::ReadLong(void** iter, long* result) const { return true; } -bool Pickle::ReadLength(void** iter, int* result) const { - if (!ReadInt(iter, result)) - return false; - return ((*result) >= 0); -} - bool Pickle::ReadSize(void** iter, size_t* result) const { DCHECK(iter); if (!*iter) @@ -256,22 +250,6 @@ bool Pickle::ReadString16(void** iter, string16* result) const { return true; } -bool Pickle::ReadBytes(void** iter, const char** data, int length) const { - DCHECK(iter); - DCHECK(data); - *data = 0; - if (!*iter) - *iter = const_cast<char*>(payload()); - - if (!IteratorHasRoomFor(*iter, length)) - return false; - - *data = reinterpret_cast<const char*>(*iter); - - UpdateIter(iter, length); - return true; -} - bool Pickle::ReadData(void** iter, const char** data, int* length) const { DCHECK(iter); DCHECK(data); @@ -285,41 +263,26 @@ bool Pickle::ReadData(void** iter, const char** data, int* length) const { return ReadBytes(iter, data, *length); } -char* Pickle::BeginWrite(size_t length) { - // write at a uint32-aligned offset from the beginning of the header - size_t offset = AlignInt(header_->payload_size, sizeof(uint32)); - - size_t new_size = offset + length; - size_t needed_size = header_size_ + new_size; - if (needed_size > capacity_ && !Resize(std::max(capacity_ * 2, needed_size))) - return NULL; +bool Pickle::ReadBytes(void** iter, const char** data, int length) const { + DCHECK(iter); + DCHECK(data); + *data = 0; + if (!*iter) + *iter = const_cast<char*>(payload()); -#ifdef ARCH_CPU_64_BITS - DCHECK_LE(length, std::numeric_limits<uint32>::max()); -#endif + if (!IteratorHasRoomFor(*iter, length)) + return false; - header_->payload_size = static_cast<uint32>(new_size); - return payload() + offset; -} + *data = reinterpret_cast<const char*>(*iter); -void Pickle::EndWrite(char* dest, int length) { - // Zero-pad to keep tools like purify from complaining about uninitialized - // memory. - if (length % sizeof(uint32)) - memset(dest + length, 0, sizeof(uint32) - (length % sizeof(uint32))); + UpdateIter(iter, length); + return true; } -bool Pickle::WriteBytes(const void* data, int data_len) { - DCHECK(capacity_ != kCapacityReadOnly) << "oops: pickle is readonly"; - - char* dest = BeginWrite(data_len); - if (!dest) +bool Pickle::ReadLength(void** iter, int* result) const { + if (!ReadInt(iter, result)) return false; - - memcpy(dest, data, data_len); - - EndWrite(dest, data_len); - return true; + return ((*result) >= 0); } bool Pickle::WriteString(const std::string& value) { @@ -349,6 +312,19 @@ bool Pickle::WriteData(const char* data, int length) { return length >= 0 && WriteInt(length) && WriteBytes(data, length); } +bool Pickle::WriteBytes(const void* data, int data_len) { + DCHECK(capacity_ != kCapacityReadOnly) << "oops: pickle is readonly"; + + char* dest = BeginWrite(data_len); + if (!dest) + return false; + + memcpy(dest, data, data_len); + + EndWrite(dest, data_len); + return true; +} + char* Pickle::BeginWriteData(int length) { DCHECK_EQ(variable_buffer_offset_, 0U) << "There can only be one variable buffer in a Pickle"; @@ -386,6 +362,30 @@ void Pickle::TrimWriteData(int new_length) { *cur_length = new_length; } +char* Pickle::BeginWrite(size_t length) { + // write at a uint32-aligned offset from the beginning of the header + size_t offset = AlignInt(header_->payload_size, sizeof(uint32)); + + size_t new_size = offset + length; + size_t needed_size = header_size_ + new_size; + if (needed_size > capacity_ && !Resize(std::max(capacity_ * 2, needed_size))) + return NULL; + +#ifdef ARCH_CPU_64_BITS + DCHECK_LE(length, std::numeric_limits<uint32>::max()); +#endif + + header_->payload_size = static_cast<uint32>(new_size); + return payload() + offset; +} + +void Pickle::EndWrite(char* dest, int length) { + // Zero-pad to keep tools like purify from complaining about uninitialized + // memory. + if (length % sizeof(uint32)) + memset(dest + length, 0, sizeof(uint32) - (length % sizeof(uint32))); +} + bool Pickle::Resize(size_t new_capacity) { new_capacity = AlignInt(new_capacity, kPayloadUnit); diff --git a/base/pickle.h b/base/pickle.h index 6006e62..bbe5d34 100644 --- a/base/pickle.h +++ b/base/pickle.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. @@ -32,8 +32,6 @@ // class Pickle { public: - virtual ~Pickle(); - // Initialize a Pickle object using the default header size. Pickle(); @@ -51,6 +49,8 @@ class Pickle { // Initializes a Pickle as a deep copy of another Pickle. Pickle(const Pickle& other); + virtual ~Pickle(); + // Performs a deep copy. Pickle& operator=(const Pickle& other); diff --git a/base/platform_file.cc b/base/platform_file.cc new file mode 100644 index 0000000..70700fc --- /dev/null +++ b/base/platform_file.cc @@ -0,0 +1,17 @@ +// 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/platform_file.h" + +namespace base { + +PlatformFileInfo::PlatformFileInfo() + : size(0), + is_directory(false), + is_symbolic_link(false) { +} + +PlatformFileInfo::~PlatformFileInfo() {} + +} // namespace base diff --git a/base/platform_file.h b/base/platform_file.h index 1ca9868..dd3028b 100644 --- a/base/platform_file.h +++ b/base/platform_file.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. @@ -71,6 +71,9 @@ enum PlatformFileError { // too, and the ParamTraits<base::PlatformFileInfo> implementation in // chrome/common/common_param_traits.cc. struct PlatformFileInfo { + PlatformFileInfo(); + ~PlatformFileInfo(); + // The size of the file in bytes. Undefined when is_directory is true. int64 size; diff --git a/base/platform_file_win.cc b/base/platform_file_win.cc index 1398397..f9eb234 100644 --- a/base/platform_file_win.cc +++ b/base/platform_file_win.cc @@ -6,7 +6,7 @@ #include "base/file_path.h" #include "base/logging.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" namespace base { diff --git a/base/process_util.h b/base/process_util.h index ce4b0bb..a7f8496 100644 --- a/base/process_util.h +++ b/base/process_util.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -76,12 +76,6 @@ struct ProcessEntry { ProcessEntry(); ~ProcessEntry(); - ProcessId pid_; - ProcessId ppid_; - ProcessId gid_; - std::string exe_file_; - std::vector<std::string> cmd_line_args_; - ProcessId pid() const { return pid_; } ProcessId parent_pid() const { return ppid_; } ProcessId gid() const { return gid_; } @@ -89,6 +83,12 @@ struct ProcessEntry { const std::vector<std::string>& cmd_line_args() const { return cmd_line_args_; } + + ProcessId pid_; + ProcessId ppid_; + ProcessId gid_; + std::string exe_file_; + std::vector<std::string> cmd_line_args_; }; struct IoCounters { @@ -528,6 +528,8 @@ int64 TimeValToMicroseconds(const struct timeval& tv); // methods. class ProcessMetrics { public: + ~ProcessMetrics(); + // Creates a ProcessMetrics for the specified process. // The caller owns the returned object. #if !defined(OS_MACOSX) @@ -549,8 +551,6 @@ class ProcessMetrics { PortProvider* port_provider); #endif // !defined(OS_MACOSX) - ~ProcessMetrics(); - // Returns the current space allocated for the pagefile, in bytes (these pages // may or may not be in memory). On Linux, this returns the total virtual // memory size. diff --git a/base/process_util_linux.cc b/base/process_util_linux.cc index 670de6a..dcaeeb4 100644 --- a/base/process_util_linux.cc +++ b/base/process_util_linux.cc @@ -22,7 +22,7 @@ #include "base/string_tokenizer.h" #include "base/string_util.h" #include "base/sys_info.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" namespace { diff --git a/base/process_util_posix.cc b/base/process_util_posix.cc index f31ffdd..ce19bc6 100644 --- a/base/process_util_posix.cc +++ b/base/process_util_posix.cc @@ -22,13 +22,13 @@ #include "base/dir_reader_posix.h" #include "base/eintr_wrapper.h" #include "base/logging.h" -#include "base/platform_thread.h" #include "base/process_util.h" #include "base/scoped_ptr.h" #include "base/stringprintf.h" -#include "base/thread_restrictions.h" +#include "base/synchronization/waitable_event.h" +#include "base/threading/platform_thread.h" +#include "base/threading/thread_restrictions.h" #include "base/time.h" -#include "base/waitable_event.h" #if defined(OS_MACOSX) #include <crt_externs.h> @@ -898,7 +898,7 @@ bool WaitForProcessesToExit(const FilePath::StringType& executable_name, result = true; break; } - PlatformThread::Sleep(100); + base::PlatformThread::Sleep(100); } while ((base::Time::Now() - end_time) > base::TimeDelta()); return result; diff --git a/base/process_util_unittest.cc b/base/process_util_unittest.cc index 0eaf5d4..672e396 100644 --- a/base/process_util_unittest.cc +++ b/base/process_util_unittest.cc @@ -7,16 +7,15 @@ #include <limits> #include "base/command_line.h" -#include "base/debug_util.h" #include "base/eintr_wrapper.h" #include "base/file_path.h" #include "base/logging.h" #include "base/path_service.h" -#include "base/platform_thread.h" #include "base/process_util.h" #include "base/scoped_ptr.h" #include "base/test/multiprocess_test.h" #include "base/test/test_timeouts.h" +#include "base/threading/platform_thread.h" #include "base/utf_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" @@ -67,7 +66,7 @@ const int kMaxWaitTimeMs = TestTimeouts::action_max_timeout_ms(); void WaitToDie(const char* filename) { FILE *fp; do { - PlatformThread::Sleep(10); + base::PlatformThread::Sleep(10); fp = fopen(filename, "r"); } while (!fp); fclose(fp); @@ -92,7 +91,7 @@ base::TerminationStatus WaitForChildTermination(base::ProcessHandle handle, int waited = 0; do { status = base::GetTerminationStatus(handle, exit_code); - PlatformThread::Sleep(kIntervalMs); + base::PlatformThread::Sleep(kIntervalMs); waited += kIntervalMs; } while (status == base::TERMINATION_STATUS_STILL_RUNNING && waited < kMaxWaitTimeMs); diff --git a/base/ref_counted.cc b/base/ref_counted.cc index f1dffa4..2f795ea 100644 --- a/base/ref_counted.cc +++ b/base/ref_counted.cc @@ -1,11 +1,11 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/ref_counted.h" #include "base/logging.h" -#include "base/thread_collision_warner.h" +#include "base/threading/thread_collision_warner.h" namespace base { diff --git a/base/ref_counted.h b/base/ref_counted.h index 9c84efa..4c3aeb8 100644 --- a/base/ref_counted.h +++ b/base/ref_counted.h @@ -7,7 +7,7 @@ #pragma once #include "base/atomic_ref_count.h" -#include "base/thread_collision_warner.h" +#include "base/threading/thread_collision_warner.h" namespace base { diff --git a/base/ref_counted_memory.cc b/base/ref_counted_memory.cc index 0a4a613..dc244b9 100644 --- a/base/ref_counted_memory.cc +++ b/base/ref_counted_memory.cc @@ -18,13 +18,6 @@ size_t RefCountedStaticMemory::size() const { return length_; } -RefCountedBytes* RefCountedBytes::TakeVector( - std::vector<unsigned char>* to_destroy) { - RefCountedBytes* bytes = new RefCountedBytes; - bytes->data.swap(*to_destroy); - return bytes; -} - RefCountedBytes::RefCountedBytes() { } @@ -32,7 +25,11 @@ RefCountedBytes::RefCountedBytes(const std::vector<unsigned char>& initializer) : data(initializer) { } -RefCountedBytes::~RefCountedBytes() { +RefCountedBytes* RefCountedBytes::TakeVector( + std::vector<unsigned char>* to_destroy) { + RefCountedBytes* bytes = new RefCountedBytes; + bytes->data.swap(*to_destroy); + return bytes; } const unsigned char* RefCountedBytes::front() const { @@ -44,3 +41,6 @@ const unsigned char* RefCountedBytes::front() const { size_t RefCountedBytes::size() const { return data.size(); } + +RefCountedBytes::~RefCountedBytes() { +} diff --git a/base/ref_counted_memory.h b/base/ref_counted_memory.h index 08400ec..fe7427e 100644 --- a/base/ref_counted_memory.h +++ b/base/ref_counted_memory.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -40,6 +40,7 @@ class RefCountedStaticMemory : public RefCountedMemory { RefCountedStaticMemory(const unsigned char* data, size_t length) : data_(data), length_(length) {} + // Overriden from RefCountedMemory: virtual const unsigned char* front() const; virtual size_t size() const; @@ -54,16 +55,17 @@ class RefCountedStaticMemory : public RefCountedMemory { // vector. class RefCountedBytes : public RefCountedMemory { public: - // Constructs a RefCountedBytes object by performing a swap. (To non - // destructively build a RefCountedBytes, use the constructor that takes a - // vector.) - static RefCountedBytes* TakeVector(std::vector<unsigned char>* to_destroy); - RefCountedBytes(); // Constructs a RefCountedBytes object by _copying_ from |initializer|. RefCountedBytes(const std::vector<unsigned char>& initializer); + // Constructs a RefCountedBytes object by performing a swap. (To non + // destructively build a RefCountedBytes, use the constructor that takes a + // vector.) + static RefCountedBytes* TakeVector(std::vector<unsigned char>* to_destroy); + + // Overriden from RefCountedMemory: virtual const unsigned char* front() const; virtual size_t size() const; diff --git a/base/scoped_handle.h b/base/scoped_handle.h index 43ee975..90cb5d5 100644 --- a/base/scoped_handle.h +++ b/base/scoped_handle.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -10,10 +10,6 @@ #include "base/basictypes.h" -#if defined(OS_WIN) -#include "base/scoped_handle_win.h" -#endif - class ScopedStdioHandle { public: ScopedStdioHandle() diff --git a/base/scoped_handle_win.h b/base/scoped_handle_win.h deleted file mode 100644 index 09bb2cb..0000000 --- a/base/scoped_handle_win.h +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// TODO(brettw) remove this file when all callers are converted to using the -// new location/namespace -#include "base/win/scoped_gdi_object.h" -#include "base/win/scoped_handle.h" -#include "base/win/scoped_handle.h" -#include "base/win/scoped_hdc.h" -#include "base/win/scoped_hglobal.h" - -using base::win::ScopedBitmap; -using base::win::ScopedHandle; -using base::win::ScopedHDC; -using base::win::ScopedHFONT; -using base::win::ScopedHGlobal; -using base::win::ScopedHICON; -using base::win::ScopedRegion; diff --git a/base/setproctitle_linux.c b/base/setproctitle_linux.c deleted file mode 100644 index 9924c99..0000000 --- a/base/setproctitle_linux.c +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file implements BSD-style setproctitle() for Linux. -// It is written such that it can easily be compiled outside Chromium. -// -// The Linux kernel sets up two locations in memory to pass arguments and -// environment variables to processes. First, there are two char* arrays stored -// one after another: argv and environ. A pointer to argv is passed to main(), -// while glibc sets the global variable |environ| to point at the latter. Both -// of these arrays are terminated by a NULL pointer; the environment array is -// also followed by some empty space to allow additional variables to be added. -// -// These arrays contain pointers to a second location in memory, where the -// strings themselves are stored one after another: first all the arguments, -// then the environment variables. The kernel will allocate a single page of -// memory for this purpose, so the end of the page containing argv[0] is the -// end of the storage potentially available to store the process title. -// -// When the kernel reads the command line arguments for a process, it looks at -// the range of memory within this page that it initially used for the argument -// list. If the terminating '\0' character is still where it expects, nothing -// further is done. If it has been overwritten, the kernel will scan up to the -// size of a page looking for another. (Note, however, that in general not that -// much space is actually mapped, since argv[0] is rarely page-aligned and only -// one page is mapped.) -// -// Thus to change the process title, we must move any environment variables out -// of the way to make room for a potentially longer title, and then overwrite -// the memory pointed to by argv[0] with a single replacement string, making -// sure its size does not exceed the available space. -// -// It is perhaps worth noting that patches to add a system call to Linux for -// this, like in BSD, have never made it in: this is the "official" way to do -// this on Linux. Presumably it is not in glibc due to some disagreement over -// this position within the glibc project, leaving applications caught in the -// middle. (Also, only a very few applications need or want this anyway.) - -#include "base/setproctitle_linux.h" - -#include <stdarg.h> -#include <stdint.h> -#include <stdio.h> -#include <string.h> -#include <unistd.h> - -extern char** environ; - -static char** g_main_argv = NULL; -static char* g_orig_argv0 = NULL; - -void setproctitle(const char* fmt, ...) { - va_list ap; - size_t i, avail_size; - uintptr_t page_size, page, page_end; - // Sanity check before we try and set the process title. - // The BSD version allows fmt == NULL to restore the original title. - if (!g_main_argv || !environ || !fmt) - return; - if (!g_orig_argv0) { - // Save the original argv[0]. - g_orig_argv0 = strdup(g_main_argv[0]); - if (!g_orig_argv0) - return; - } - page_size = sysconf(_SC_PAGESIZE); - // Get the page on which the argument list and environment live. - page = (uintptr_t) g_main_argv[0]; - page -= page % page_size; - page_end = page + page_size; - // Move the environment out of the way. Note that we are moving the values, - // not the environment array itself (which may not be on the page we need - // to overwrite anyway). - for (i = 0; environ[i]; ++i) { - uintptr_t env_i = (uintptr_t) environ[i]; - // Only move the value if it's actually in the way. This avoids - // leaking copies of the values if this function is called again. - if (page <= env_i && env_i < page_end) { - char* copy = strdup(environ[i]); - // Be paranoid. Check for allocation failure and bail out. - if (!copy) - return; - environ[i] = copy; - } - } - // Put the title in argv[0]. We have to zero out the space first since the - // kernel doesn't actually look for a null terminator unless we make the - // argument list longer than it started. - avail_size = page_end - (uintptr_t) g_main_argv[0]; - memset(g_main_argv[0], 0, avail_size); - va_start(ap, fmt); - if (fmt[0] == '-') { - vsnprintf(g_main_argv[0], avail_size, &fmt[1], ap); - } else { - size_t size = snprintf(g_main_argv[0], avail_size, "%s ", g_orig_argv0); - if (size < avail_size) - vsnprintf(g_main_argv[0] + size, avail_size - size, fmt, ap); - } - va_end(ap); - g_main_argv[1] = NULL; -} - -// A version of this built into glibc would not need this function, since -// it could stash the argv pointer in __libc_start_main(). But we need it. -void setproctitle_init(char** main_argv) { - if (g_main_argv) - return; - - uintptr_t page_size = sysconf(_SC_PAGESIZE); - // Check that the argv array is in fact on the same page of memory - // as the environment array just as an added measure of protection. - if (((uintptr_t) environ) / page_size == ((uintptr_t) main_argv) / page_size) - g_main_argv = main_argv; -} diff --git a/base/setproctitle_linux.h b/base/setproctitle_linux.h deleted file mode 100644 index 769338c..0000000 --- a/base/setproctitle_linux.h +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2009 The Chromium 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_SETPROCTITLE_LINUX_H_ -#define BASE_SETPROCTITLE_LINUX_H_ -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -// Set the process title that will show in "ps" and similar tools. Takes -// printf-style format string and arguments. After calling setproctitle() -// the original main() argv[] array should not be used. By default, the -// original argv[0] is prepended to the format; this can be disabled by -// including a '-' as the first character of the format string. -void setproctitle(const char* fmt, ...); - -// Initialize state needed for setproctitle() on Linux. Pass the argv pointer -// from main() to setproctitle_init() before calling setproctitle(). -void setproctitle_init(char** main_argv); - -#ifdef __cplusplus -} -#endif - -#endif // BASE_SETPROCTITLE_LINUX_H_ diff --git a/base/shared_memory_posix.cc b/base/shared_memory_posix.cc index 88203dd..e83b982 100644 --- a/base/shared_memory_posix.cc +++ b/base/shared_memory_posix.cc @@ -12,9 +12,9 @@ #include "base/file_util.h" #include "base/logging.h" -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" #include "base/safe_strerror_posix.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" #include "base/utf_string_conversions.h" namespace base { @@ -300,7 +300,7 @@ void SharedMemory::LockOrUnlockCommon(int function) { continue; } else if (errno == ENOLCK) { // temporary kernel resource exaustion - PlatformThread::Sleep(500); + base::PlatformThread::Sleep(500); continue; } else { NOTREACHED() << "lockf() failed." diff --git a/base/shared_memory_unittest.cc b/base/shared_memory_unittest.cc index f646158..b515e79 100644 --- a/base/shared_memory_unittest.cc +++ b/base/shared_memory_unittest.cc @@ -4,10 +4,10 @@ #include "base/basictypes.h" #include "base/mac/scoped_nsautorelease_pool.h" -#include "base/platform_thread.h" #include "base/shared_memory.h" #include "base/scoped_ptr.h" #include "base/test/multiprocess_test.h" +#include "base/threading/platform_thread.h" #include "base/time.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/multiprocess_func_list.h" @@ -327,7 +327,7 @@ TEST(SharedMemoryTest, AnonymousPrivate) { // On POSIX it is especially important we test shmem across processes, // not just across threads. But the test is enabled on all platforms. -class SharedMemoryProcessTest : public base::MultiProcessTest { +class SharedMemoryProcessTest : public MultiProcessTest { public: static void CleanUp() { @@ -380,14 +380,14 @@ const char* const SharedMemoryProcessTest::s_test_name_ = "MPMem"; TEST_F(SharedMemoryProcessTest, MAYBE_Tasks) { SharedMemoryProcessTest::CleanUp(); - base::ProcessHandle handles[kNumTasks]; + ProcessHandle handles[kNumTasks]; for (int index = 0; index < kNumTasks; ++index) { handles[index] = SpawnChild("SharedMemoryTestMain", false); } int exit_code = 0; for (int index = 0; index < kNumTasks; ++index) { - EXPECT_TRUE(base::WaitForExitCode(handles[index], &exit_code)); + EXPECT_TRUE(WaitForExitCode(handles[index], &exit_code)); EXPECT_TRUE(exit_code == 0); } diff --git a/base/singleton.h b/base/singleton.h index e5713c4..5bd5c35 100644 --- a/base/singleton.h +++ b/base/singleton.h @@ -8,9 +8,9 @@ #include "base/at_exit.h" #include "base/atomicops.h" -#include "base/platform_thread.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" -#include "base/thread_restrictions.h" +#include "base/threading/platform_thread.h" +#include "base/threading/thread_restrictions.h" // Default traits for Singleton<Type>. Calls operator new and operator delete on // the object. Registers automatic deletion at process exit. @@ -243,7 +243,7 @@ class Singleton { value = base::subtle::NoBarrier_Load(&instance_); if (value != kBeingCreatedMarker) break; - PlatformThread::YieldCurrentThread(); + base::PlatformThread::YieldCurrentThread(); } // See the corresponding HAPPENS_BEFORE above. diff --git a/base/spin_wait.h b/base/spin_wait.h index 34484d2..1e31b14 100644 --- a/base/spin_wait.h +++ b/base/spin_wait.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -12,11 +12,11 @@ // We provide a simple one argument spin wait (for 1 second), and a generic // spin wait (for longer periods of time). -#ifndef BASE_SPIN_WAIT_H__ -#define BASE_SPIN_WAIT_H__ +#ifndef BASE_SPIN_WAIT_H_ +#define BASE_SPIN_WAIT_H_ #pragma once -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" #include "base/time.h" // Provide a macro that will wait no longer than 1 second for an asynchronous @@ -44,8 +44,8 @@ kTimeout.InMilliseconds()) << "Timed out"; \ break; \ } \ - PlatformThread::Sleep(50); \ + base::PlatformThread::Sleep(50); \ } \ } while (0) -#endif // BASE_SPIN_WAIT_H__ +#endif // BASE_SPIN_WAIT_H_ diff --git a/base/string_piece.h b/base/string_piece.h index 70c0480..80c6cab 100644 --- a/base/string_piece.h +++ b/base/string_piece.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. // Copied from strings/stringpiece.h with modifications @@ -29,11 +29,19 @@ namespace base { class StringPiece { public: + // standard STL container boilerplate typedef size_t size_type; + typedef char value_type; + typedef const char* pointer; + typedef const char& reference; + typedef const char& const_reference; + typedef ptrdiff_t difference_type; + typedef const char* const_iterator; + typedef const char* iterator; + typedef std::reverse_iterator<const_iterator> const_reverse_iterator; + typedef std::reverse_iterator<iterator> reverse_iterator; - private: - const char* ptr_; - size_type length_; + static const size_type npos; public: // We provide non-explicit singleton constructors so users can pass @@ -113,17 +121,6 @@ class StringPiece { (wordmemcmp(ptr_ + (length_-x.length_), x.ptr_, x.length_) == 0)); } - // standard STL container boilerplate - typedef char value_type; - typedef const char* pointer; - typedef const char& reference; - typedef const char& const_reference; - typedef ptrdiff_t difference_type; - static const size_type npos; - typedef const char* const_iterator; - typedef const char* iterator; - typedef std::reverse_iterator<const_iterator> const_reverse_iterator; - typedef std::reverse_iterator<iterator> reverse_iterator; iterator begin() const { return ptr_; } iterator end() const { return ptr_ + length_; } const_reverse_iterator rbegin() const { @@ -161,6 +158,10 @@ class StringPiece { static int wordmemcmp(const char* p, const char* p2, size_type N) { return memcmp(p, p2, N); } + + private: + const char* ptr_; + size_type length_; }; bool operator==(const StringPiece& x, const StringPiece& y); diff --git a/base/string_util.h b/base/string_util.h index f65652c..ed7adec 100644 --- a/base/string_util.h +++ b/base/string_util.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. // @@ -276,7 +276,7 @@ bool WideToLatin1(const std::wstring& wide, std::string* latin1); // first case) or characters that use only 8-bits and whose 8-bit // representation looks like a UTF-8 string (the second case). // -// Note that IsStringUTF8 checks not only if the input is structrually +// Note that IsStringUTF8 checks not only if the input is structurally // valid but also if it doesn't contain any non-character codepoint // (e.g. U+FFFE). It's done on purpose because all the existing callers want // to have the maximum 'discriminating' power from other encodings. If diff --git a/base/cancellation_flag.cc b/base/synchronization/cancellation_flag.cc index 50e30ec..ad3b551 100644 --- a/base/cancellation_flag.cc +++ b/base/synchronization/cancellation_flag.cc @@ -1,8 +1,8 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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/cancellation_flag.h" +#include "base/synchronization/cancellation_flag.h" #include "base/logging.h" diff --git a/base/cancellation_flag.h b/base/synchronization/cancellation_flag.h index 98ca846..29ecd89 100644 --- a/base/cancellation_flag.h +++ b/base/synchronization/cancellation_flag.h @@ -1,13 +1,13 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// 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_CANCELLATION_FLAG_H_ -#define BASE_CANCELLATION_FLAG_H_ +#ifndef BASE_SYNCHRONIZATION_CANCELLATION_FLAG_H_ +#define BASE_SYNCHRONIZATION_CANCELLATION_FLAG_H_ #pragma once #include "base/atomicops.h" -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" namespace base { @@ -40,4 +40,4 @@ class CancellationFlag { } // namespace base -#endif // BASE_CANCELLATION_FLAG_H_ +#endif // BASE_SYNCHRONIZATION_CANCELLATION_FLAG_H_ diff --git a/base/cancellation_flag_unittest.cc b/base/synchronization/cancellation_flag_unittest.cc index eb28b53..c405c79 100644 --- a/base/cancellation_flag_unittest.cc +++ b/base/synchronization/cancellation_flag_unittest.cc @@ -1,22 +1,20 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. // Tests of CancellationFlag class. -#include "base/cancellation_flag.h" +#include "base/synchronization/cancellation_flag.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/spin_wait.h" #include "base/time.h" -#include "base/thread.h" +#include "base/threading/thread.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" -using base::CancellationFlag; -using base::TimeDelta; -using base::Thread; +namespace base { namespace { @@ -65,3 +63,5 @@ TEST(CancellationFlagTest, SetOnDifferentThreadDeathTest) { } } // namespace + +} // namespace base diff --git a/base/condition_variable.h b/base/synchronization/condition_variable.h index 4fe1892..3acd0ac 100644 --- a/base/condition_variable.h +++ b/base/synchronization/condition_variable.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. @@ -62,8 +62,8 @@ // For a discussion of the many very subtle implementation details, see the FAQ // at the end of condition_variable_win.cc. -#ifndef BASE_CONDITION_VARIABLE_H_ -#define BASE_CONDITION_VARIABLE_H_ +#ifndef BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_ +#define BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_ #pragma once #include "build/build_config.h" @@ -78,8 +78,8 @@ #include "base/lock.h" namespace base { - class TimeDelta; -} + +class TimeDelta; class ConditionVariable { public: @@ -91,7 +91,7 @@ class ConditionVariable { // Wait() releases the caller's critical section atomically as it starts to // sleep, and the reacquires it when it is signaled. void Wait(); - void TimedWait(const base::TimeDelta& max_time); + void TimedWait(const TimeDelta& max_time); // Broadcast() revives all waiting threads. void Broadcast(); @@ -184,4 +184,6 @@ class ConditionVariable { DISALLOW_COPY_AND_ASSIGN(ConditionVariable); }; -#endif // BASE_CONDITION_VARIABLE_H_ +} // namespace base + +#endif // BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_ diff --git a/base/condition_variable_posix.cc b/base/synchronization/condition_variable_posix.cc index 5d9ccb4..eff7053 100644 --- a/base/condition_variable_posix.cc +++ b/base/synchronization/condition_variable_posix.cc @@ -1,23 +1,22 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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/condition_variable.h" +#include "base/synchronization/condition_variable.h" #include <errno.h> #include <sys/time.h> -#include "base/lock.h" #include "base/logging.h" +#include "base/synchronization/lock.h" #include "base/time.h" -using base::Time; -using base::TimeDelta; +namespace base { ConditionVariable::ConditionVariable(Lock* user_lock) - : user_mutex_(user_lock->lock_.os_lock()) + : user_mutex_(user_lock->lock_.os_lock()) #if !defined(NDEBUG) - , user_lock_(user_lock) + , user_lock_(user_lock) #endif { int rv = pthread_cond_init(&condition_, NULL); @@ -74,3 +73,5 @@ void ConditionVariable::Signal() { int rv = pthread_cond_signal(&condition_); DCHECK(rv == 0); } + +} // namespace base diff --git a/base/condition_variable_unittest.cc b/base/synchronization/condition_variable_unittest.cc index 67d1839..8cfe4fe 100644 --- a/base/condition_variable_unittest.cc +++ b/base/synchronization/condition_variable_unittest.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. @@ -8,19 +8,18 @@ #include <algorithm> #include <vector> -#include "base/condition_variable.h" +#include "base/synchronization/condition_variable.h" #include "base/lock.h" #include "base/logging.h" -#include "base/platform_thread.h" #include "base/scoped_ptr.h" #include "base/spin_wait.h" -#include "base/thread_collision_warner.h" +#include "base/threading/platform_thread.h" +#include "base/threading/thread_collision_warner.h" #include "base/time.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" -using base::TimeDelta; -using base::TimeTicks; +namespace base { namespace { //------------------------------------------------------------------------------ @@ -37,12 +36,12 @@ class ConditionVariableTest : public PlatformTest { const TimeDelta kOneHundredMs; explicit ConditionVariableTest() - : kZeroMs(TimeDelta::FromMilliseconds(0)), - kTenMs(TimeDelta::FromMilliseconds(10)), - kThirtyMs(TimeDelta::FromMilliseconds(30)), - kFortyFiveMs(TimeDelta::FromMilliseconds(45)), - kSixtyMs(TimeDelta::FromMilliseconds(60)), - kOneHundredMs(TimeDelta::FromMilliseconds(100)) { + : kZeroMs(TimeDelta::FromMilliseconds(0)), + kTenMs(TimeDelta::FromMilliseconds(10)), + kThirtyMs(TimeDelta::FromMilliseconds(30)), + kFortyFiveMs(TimeDelta::FromMilliseconds(45)), + kSixtyMs(TimeDelta::FromMilliseconds(60)), + kOneHundredMs(TimeDelta::FromMilliseconds(100)) { } }; @@ -196,7 +195,7 @@ TEST_F(ConditionVariableTest, MultiThreadConsumerTest) { const int kTaskCount = 10; // Number of tasks in each mini-test here. - base::Time start_time; // Used to time task processing. + Time start_time; // Used to time task processing. { AutoLock auto_lock(*queue.lock()); @@ -224,7 +223,7 @@ TEST_F(ConditionVariableTest, MultiThreadConsumerTest) { queue.SetWorkTime(kThirtyMs); queue.SetAllowHelp(false); - start_time = base::Time::Now(); + start_time = Time::Now(); } queue.work_is_available()->Signal(); // Start up one thread. @@ -239,7 +238,7 @@ TEST_F(ConditionVariableTest, MultiThreadConsumerTest) { // The last of the tasks *might* still be running, but... all but one should // be done by now, since tasks are being done serially. EXPECT_LE(queue.GetWorkTime().InMilliseconds() * (kTaskCount - 1), - (base::Time::Now() - start_time).InMilliseconds()); + (Time::Now() - start_time).InMilliseconds()); EXPECT_EQ(1, queue.GetNumThreadsTakingAssignments()); EXPECT_EQ(1, queue.GetNumThreadsCompletingTasks()); @@ -268,7 +267,7 @@ TEST_F(ConditionVariableTest, MultiThreadConsumerTest) { queue.SetWorkTime(kThirtyMs); queue.SetAllowHelp(true); - start_time = base::Time::Now(); + start_time = Time::Now(); } queue.work_is_available()->Signal(); // But each worker can signal another. @@ -747,3 +746,5 @@ void WorkQueue::ThreadMain() { } } // namespace + +} // namespace base diff --git a/base/condition_variable_win.cc b/base/synchronization/condition_variable_win.cc index 5150c23..3030178 100644 --- a/base/condition_variable_win.cc +++ b/base/synchronization/condition_variable_win.cc @@ -1,22 +1,22 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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/condition_variable.h" +#include "base/synchronization/condition_variable.h" #include <stack> -#include "base/lock.h" #include "base/logging.h" +#include "base/synchronization/lock.h" #include "base/time.h" -using base::TimeDelta; +namespace base { ConditionVariable::ConditionVariable(Lock* user_lock) - : user_lock_(*user_lock), - run_state_(RUNNING), - allocation_counter_(0), - recycling_list_size_(0) { + : user_lock_(*user_lock), + run_state_(RUNNING), + allocation_counter_(0), + recycling_list_size_(0) { DCHECK(user_lock); } @@ -443,3 +443,5 @@ put so many assertions (DCHECKs) into the container class that it is trivial to code review and validate its correctness. */ + +} // namespace base diff --git a/base/lock.cc b/base/synchronization/lock.cc index c73a458..6445ce8 100644 --- a/base/lock.cc +++ b/base/synchronization/lock.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -8,9 +8,11 @@ #if !defined(NDEBUG) -#include "base/lock.h" +#include "base/synchronization/lock.h" #include "base/logging.h" +namespace base { + Lock::Lock() : lock_() { owned_by_thread_ = false; owning_thread_id_ = static_cast<PlatformThreadId>(0); @@ -34,4 +36,6 @@ void Lock::CheckUnheldAndMark() { owning_thread_id_ = PlatformThread::CurrentId(); } +} // namespace base + #endif // NDEBUG diff --git a/base/synchronization/lock.h b/base/synchronization/lock.h new file mode 100644 index 0000000..f7c9c49 --- /dev/null +++ b/base/synchronization/lock.h @@ -0,0 +1,131 @@ +// 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_ +#pragma once + +#include "base/synchronization/lock_impl.h" +#include "base/threading/platform_thread.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: +#if defined(NDEBUG) // 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 {} +#else + Lock(); + ~Lock() {} + + // NOTE: Although windows critical sections support recursive locks, we do not + // allow this, and we will commonly fire a DCHECK() if a thread attempts to + // acquire the lock a second time (while already holding it). + void Acquire() { + lock_.Lock(); + CheckUnheldAndMark(); + } + void Release() { + CheckHeldAndUnmark(); + lock_.Unlock(); + } + + bool Try() { + bool rv = lock_.Try(); + if (rv) { + CheckUnheldAndMark(); + } + return rv; + } + + void AssertAcquired() const; +#endif // NDEBUG + +#if defined(OS_POSIX) + // The posix implementation of ConditionVariable needs to be able + // to see our lock and tweak our debugging counters, as it releases + // and acquires locks inside of pthread_cond_{timed,}wait. + // Windows doesn't need to do this as it calls the Lock::* methods. + friend class ConditionVariable; +#endif + + private: +#if !defined(NDEBUG) + // Members and routines taking care of locks assertions. + // Note that this checks for recursive locks and allows them + // if the variable is set. This is allowed by the underlying implementation + // on windows but not on Posix, so we're doing unneeded checks on Posix. + // It's worth it to share the code. + void CheckHeldAndUnmark(); + void CheckUnheldAndMark(); + + // All private data is implicitly protected by lock_. + // Be VERY careful to only access members under that lock. + + // Determines validity of owning_thread_id_. Needed as we don't have + // a null owning_thread_id_ value. + bool owned_by_thread_; + base::PlatformThreadId owning_thread_id_; +#endif // NDEBUG + + // 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: + explicit AutoLock(Lock& lock) : lock_(lock) { + lock_.Acquire(); + } + + ~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/lock_impl.h b/base/synchronization/lock_impl.h index 6066495..2994610 100644 --- a/base/lock_impl.h +++ b/base/synchronization/lock_impl.h @@ -1,9 +1,9 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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_LOCK_IMPL_H_ -#define BASE_LOCK_IMPL_H_ +#ifndef BASE_SYNCHRONIZATION_LOCK_IMPL_H_ +#define BASE_SYNCHRONIZATION_LOCK_IMPL_H_ #pragma once #include "build/build_config.h" @@ -16,6 +16,9 @@ #include "base/basictypes.h" +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. @@ -54,5 +57,7 @@ class LockImpl { DISALLOW_COPY_AND_ASSIGN(LockImpl); }; +} // namespace internal +} // namespace base -#endif // BASE_LOCK_IMPL_H_ +#endif // BASE_SYNCHRONIZATION_LOCK_IMPL_H_ diff --git a/base/lock_impl_posix.cc b/base/synchronization/lock_impl_posix.cc index 355149f..f638fcd 100644 --- a/base/lock_impl_posix.cc +++ b/base/synchronization/lock_impl_posix.cc @@ -1,13 +1,16 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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/lock_impl.h" +#include "base/synchronization/lock_impl.h" #include <errno.h> #include "base/logging.h" +namespace base { +namespace internal { + LockImpl::LockImpl() { #ifndef NDEBUG // In debug, setup attributes for lock error checking. @@ -46,3 +49,6 @@ void LockImpl::Unlock() { int rv = pthread_mutex_unlock(&os_lock_); DCHECK_EQ(rv, 0); } + +} // namespace internal +} // namespace base diff --git a/base/lock_impl_win.cc b/base/synchronization/lock_impl_win.cc index 8c03b61..bb8a23d 100644 --- a/base/lock_impl_win.cc +++ b/base/synchronization/lock_impl_win.cc @@ -1,8 +1,11 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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/lock_impl.h" +#include "base/synchronization/lock_impl.h" + +namespace base { +namespace internal { LockImpl::LockImpl() { // The second parameter is the spin count, for short-held locks it avoid the @@ -28,3 +31,6 @@ void LockImpl::Lock() { void LockImpl::Unlock() { ::LeaveCriticalSection(&os_lock_); } + +} // namespace internal +} // namespace base diff --git a/base/lock_unittest.cc b/base/synchronization/lock_unittest.cc index cf99df9..5ac3e6b 100644 --- a/base/lock_unittest.cc +++ b/base/synchronization/lock_unittest.cc @@ -1,15 +1,14 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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/lock.h" - #include <stdlib.h> -#include "base/platform_thread.h" +#include "base/synchronization/lock.h" +#include "base/threading/platform_thread.h" #include "testing/gtest/include/gtest/gtest.h" -typedef testing::Test LockTest; +namespace base { // Basic test to make sure that Acquire()/Release()/Try() don't crash ---------- @@ -47,7 +46,7 @@ class BasicLockTestThread : public PlatformThread::Delegate { DISALLOW_COPY_AND_ASSIGN(BasicLockTestThread); }; -TEST_F(LockTest, Basic) { +TEST(LockTest, Basic) { Lock lock; BasicLockTestThread thread(&lock); PlatformThreadHandle handle = kNullThreadHandle; @@ -107,7 +106,7 @@ class TryLockTestThread : public PlatformThread::Delegate { DISALLOW_COPY_AND_ASSIGN(TryLockTestThread); }; -TEST_F(LockTest, TryLock) { +TEST(LockTest, TryLock) { Lock lock; ASSERT_TRUE(lock.Try()); @@ -172,7 +171,7 @@ class MutexLockTestThread : public PlatformThread::Delegate { DISALLOW_COPY_AND_ASSIGN(MutexLockTestThread); }; -TEST_F(LockTest, MutexTwoThreads) { +TEST(LockTest, MutexTwoThreads) { Lock lock; int value = 0; @@ -188,7 +187,7 @@ TEST_F(LockTest, MutexTwoThreads) { EXPECT_EQ(2 * 40, value); } -TEST_F(LockTest, MutexFourThreads) { +TEST(LockTest, MutexFourThreads) { Lock lock; int value = 0; @@ -211,3 +210,5 @@ TEST_F(LockTest, MutexFourThreads) { EXPECT_EQ(4 * 40, value); } + +} // namespace base diff --git a/base/waitable_event.h b/base/synchronization/waitable_event.h index 081ad66..01b5987 100644 --- a/base/waitable_event.h +++ b/base/synchronization/waitable_event.h @@ -1,9 +1,9 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// 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_WAITABLE_EVENT_H_ -#define BASE_WAITABLE_EVENT_H_ +#ifndef BASE_SYNCHRONIZATION_WAITABLE_EVENT_H_ +#define BASE_SYNCHRONIZATION_WAITABLE_EVENT_H_ #pragma once #include "base/basictypes.h" @@ -155,20 +155,21 @@ class WaitableEvent { std::list<Waiter*> waiters_; }; - scoped_refptr<WaitableEventKernel> kernel_; - - bool SignalAll(); - bool SignalOne(); - void Enqueue(Waiter* waiter); + 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. - typedef std::pair<WaitableEvent*, size_t> WaiterAndIndex; 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); @@ -176,4 +177,4 @@ class WaitableEvent { } // namespace base -#endif // BASE_WAITABLE_EVENT_H_ +#endif // BASE_SYNCHRONIZATION_WAITABLE_EVENT_H_ diff --git a/base/waitable_event_posix.cc b/base/synchronization/waitable_event_posix.cc index adc521e..9cbc03a 100644 --- a/base/waitable_event_posix.cc +++ b/base/synchronization/waitable_event_posix.cc @@ -1,11 +1,11 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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/waitable_event.h" +#include "base/synchronization/waitable_event.h" -#include "base/condition_variable.h" -#include "base/lock.h" +#include "base/synchronization/condition_variable.h" +#include "base/synchronization/lock.h" #include "base/message_loop.h" // ----------------------------------------------------------------------------- @@ -42,12 +42,12 @@ WaitableEvent::~WaitableEvent() { } void WaitableEvent::Reset() { - AutoLock locked(kernel_->lock_); + base::AutoLock locked(kernel_->lock_); kernel_->signaled_ = false; } void WaitableEvent::Signal() { - AutoLock locked(kernel_->lock_); + base::AutoLock locked(kernel_->lock_); if (kernel_->signaled_) return; @@ -64,7 +64,7 @@ void WaitableEvent::Signal() { } bool WaitableEvent::IsSignaled() { - AutoLock locked(kernel_->lock_); + base::AutoLock locked(kernel_->lock_); const bool result = kernel_->signaled_; if (result && !kernel_->manual_reset_) @@ -89,7 +89,7 @@ class SyncWaiter : public WaitableEvent::Waiter { } bool Fire(WaitableEvent* signaling_event) { - AutoLock locked(lock_); + base::AutoLock locked(lock_); if (fired_) return false; @@ -134,19 +134,19 @@ class SyncWaiter : public WaitableEvent::Waiter { fired_ = true; } - Lock* lock() { + base::Lock* lock() { return &lock_; } - ConditionVariable* cv() { + base::ConditionVariable* cv() { return &cv_; } private: bool fired_; WaitableEvent* signaling_event_; // The WaitableEvent which woke us - Lock lock_; - ConditionVariable cv_; + base::Lock lock_; + base::ConditionVariable cv_; }; bool WaitableEvent::TimedWait(const TimeDelta& max_time) { diff --git a/base/waitable_event_unittest.cc b/base/synchronization/waitable_event_unittest.cc index b2590a8..47e7ff7 100644 --- a/base/waitable_event_unittest.cc +++ b/base/synchronization/waitable_event_unittest.cc @@ -1,18 +1,13 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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/time.h" -#include "base/waitable_event.h" -#include "base/platform_thread.h" +#include "base/synchronization/waitable_event.h" +#include "base/threading/platform_thread.h" #include "testing/gtest/include/gtest/gtest.h" -using base::TimeDelta; -using base::WaitableEvent; - -namespace { -typedef testing::Test WaitableEventTest; -} +namespace base { TEST(WaitableEventTest, ManualBasics) { WaitableEvent event(true, false); @@ -107,3 +102,5 @@ TEST(WaitableEventTest, WaitMany) { for (unsigned i = 0; i < 5; ++i) delete ev[i]; } + +} // namespace base diff --git a/base/waitable_event_watcher.h b/base/synchronization/waitable_event_watcher.h index 04aa8cf..1b93b66 100644 --- a/base/waitable_event_watcher.h +++ b/base/synchronization/waitable_event_watcher.h @@ -1,18 +1,18 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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_WAITABLE_EVENT_WATCHER_H_ -#define BASE_WAITABLE_EVENT_WATCHER_H_ +#ifndef BASE_SYNCHRONIZATION_WAITABLE_EVENT_WATCHER_H_ +#define BASE_SYNCHRONIZATION_WAITABLE_EVENT_WATCHER_H_ #pragma once #include "build/build_config.h" #if defined(OS_WIN) -#include "base/object_watcher.h" +#include "base/win/object_watcher.h" #else #include "base/message_loop.h" -#include "base/waitable_event.h" +#include "base/synchronization/waitable_event.h" #endif namespace base { @@ -115,8 +115,6 @@ class WaitableEventWatcher } private: - WaitableEvent* event_; - #if defined(OS_WIN) // --------------------------------------------------------------------------- // The helper class exists because, if WaitableEventWatcher were to inherit @@ -124,7 +122,7 @@ class WaitableEventWatcher // called Delegate (at least on Windows). Thus this object exists to proxy // the callback function // --------------------------------------------------------------------------- - class ObjectWatcherHelper : public ObjectWatcher::Delegate { + class ObjectWatcherHelper : public win::ObjectWatcher::Delegate { public: ObjectWatcherHelper(WaitableEventWatcher* watcher); @@ -140,7 +138,7 @@ class WaitableEventWatcher void OnObjectSignaled(); ObjectWatcherHelper helper_; - ObjectWatcher watcher_; + win::ObjectWatcher watcher_; #else // --------------------------------------------------------------------------- // Implementation of MessageLoop::DestructionObserver @@ -154,9 +152,11 @@ class WaitableEventWatcher scoped_refptr<WaitableEvent::WaitableEventKernel> kernel_; #endif + WaitableEvent* event_; + Delegate* delegate_; }; } // namespace base -#endif // BASE_WAITABLE_EVENT_WATCHER_H_ +#endif // BASE_SYNCHRONIZATION_WAITABLE_EVENT_WATCHER_H_ diff --git a/base/waitable_event_watcher_posix.cc b/base/synchronization/waitable_event_watcher_posix.cc index 07ae694..0d6ff26 100644 --- a/base/waitable_event_watcher_posix.cc +++ b/base/synchronization/waitable_event_watcher_posix.cc @@ -1,13 +1,12 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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/waitable_event_watcher.h" +#include "base/synchronization/waitable_event_watcher.h" -#include "base/condition_variable.h" -#include "base/lock.h" #include "base/message_loop.h" -#include "base/waitable_event.h" +#include "base/synchronization/lock.h" +#include "base/synchronization/waitable_event.h" namespace base { @@ -119,11 +118,11 @@ class AsyncCallbackTask : public Task { }; WaitableEventWatcher::WaitableEventWatcher() - : event_(NULL), - message_loop_(NULL), + : message_loop_(NULL), cancel_flag_(NULL), waiter_(NULL), callback_task_(NULL), + event_(NULL), delegate_(NULL) { } diff --git a/base/waitable_event_watcher_unittest.cc b/base/synchronization/waitable_event_watcher_unittest.cc index e6a6ac0..1715dff 100644 --- a/base/waitable_event_watcher_unittest.cc +++ b/base/synchronization/waitable_event_watcher_unittest.cc @@ -1,15 +1,14 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// 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/message_loop.h" -#include "base/platform_thread.h" -#include "base/waitable_event.h" -#include "base/waitable_event_watcher.h" +#include "base/synchronization/waitable_event.h" +#include "base/synchronization/waitable_event_watcher.h" +#include "base/threading/platform_thread.h" #include "testing/gtest/include/gtest/gtest.h" -using base::WaitableEvent; -using base::WaitableEventWatcher; +namespace base { namespace { @@ -81,7 +80,7 @@ void RunTest_CancelAfterSet(MessageLoop::Type message_loop_type) { event.Signal(); // Let the background thread do its business - PlatformThread::Sleep(30); + base::PlatformThread::Sleep(30); watcher.StopWatching(); @@ -162,3 +161,5 @@ TEST(WaitableEventWatcherTest, MAYBE_DeleteUnder) { RunTest_DeleteUnder(MessageLoop::TYPE_IO); RunTest_DeleteUnder(MessageLoop::TYPE_UI); } + +} // namespace base diff --git a/base/waitable_event_watcher_win.cc b/base/synchronization/waitable_event_watcher_win.cc index 7619aa4..43e3c47 100644 --- a/base/waitable_event_watcher_win.cc +++ b/base/synchronization/waitable_event_watcher_win.cc @@ -1,12 +1,12 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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/waitable_event_watcher.h" +#include "base/synchronization/waitable_event_watcher.h" #include "base/compiler_specific.h" -#include "base/object_watcher.h" -#include "base/waitable_event.h" +#include "base/synchronization/waitable_event.h" +#include "base/win/object_watcher.h" namespace base { @@ -21,8 +21,8 @@ void WaitableEventWatcher::ObjectWatcherHelper::OnObjectSignaled(HANDLE h) { WaitableEventWatcher::WaitableEventWatcher() - : event_(NULL), - ALLOW_THIS_IN_INITIALIZER_LIST(helper_(this)), + : ALLOW_THIS_IN_INITIALIZER_LIST(helper_(this)), + event_(NULL), delegate_(NULL) { } diff --git a/base/waitable_event_win.cc b/base/synchronization/waitable_event_win.cc index 3d0eb14..0fcf488 100644 --- a/base/waitable_event_win.cc +++ b/base/synchronization/waitable_event_win.cc @@ -1,8 +1,8 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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/waitable_event.h" +#include "base/synchronization/waitable_event.h" #include <math.h> #include <windows.h> diff --git a/base/sys_info_chromeos.cc b/base/sys_info_chromeos.cc index e554d73..5834389 100644 --- a/base/sys_info_chromeos.cc +++ b/base/sys_info_chromeos.cc @@ -9,7 +9,7 @@ #include "base/file_util.h" #include "base/string_number_conversions.h" #include "base/string_tokenizer.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" namespace base { diff --git a/base/task.h b/base/task.h index e6e0d2d..fc986b2 100644 --- a/base/task.h +++ b/base/task.h @@ -6,7 +6,6 @@ #define BASE_TASK_H_ #pragma once -#include "base/non_thread_safe.h" #include "base/raw_scoped_refptr_mismatch_checker.h" #include "base/tracked.h" #include "base/tuple.h" @@ -228,7 +227,7 @@ template <class T> struct RunnableMethodTraits { RunnableMethodTraits() { #ifndef NDEBUG - origin_thread_id_ = PlatformThread::CurrentId(); + origin_thread_id_ = base::PlatformThread::CurrentId(); #endif } @@ -236,7 +235,7 @@ struct RunnableMethodTraits { #ifndef NDEBUG // If destroyed on a separate thread, then we had better have been using // thread-safe reference counting! - if (origin_thread_id_ != PlatformThread::CurrentId()) + if (origin_thread_id_ != base::PlatformThread::CurrentId()) DCHECK(T::ImplementsThreadSafeReferenceCounting()); #endif } @@ -258,7 +257,7 @@ struct RunnableMethodTraits { private: #ifndef NDEBUG - PlatformThreadId origin_thread_id_; + base::PlatformThreadId origin_thread_id_; #endif }; diff --git a/base/task_queue.cc b/base/task_queue.cc index e3c196b..fdff8ac 100644 --- a/base/task_queue.cc +++ b/base/task_queue.cc @@ -15,6 +15,22 @@ TaskQueue::~TaskQueue() { STLDeleteElements(&queue_); } +void TaskQueue::Push(Task* task) { + DCHECK(task); + + // Add the task to the back of the queue. + queue_.push_back(task); +} + +void TaskQueue::Clear() { + // Delete all the elements in the queue and clear the dead pointers. + STLDeleteElements(&queue_); +} + +bool TaskQueue::IsEmpty() const { + return queue_.empty(); +} + void TaskQueue::Run() { // Nothing to run if our queue is empty. if (queue_.empty()) @@ -31,19 +47,3 @@ void TaskQueue::Run() { delete (*task); } } - -void TaskQueue::Push(Task* task) { - DCHECK(task); - - // Add the task to the back of the queue. - queue_.push_back(task); -} - -void TaskQueue::Clear() { - // Delete all the elements in the queue and clear the dead pointers. - STLDeleteElements(&queue_); -} - -bool TaskQueue::IsEmpty() const { - return queue_.empty(); -} diff --git a/base/task_queue.h b/base/task_queue.h index 5bfc777..75b38b2 100644 --- a/base/task_queue.h +++ b/base/task_queue.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -18,10 +18,6 @@ class TaskQueue : public Task { TaskQueue(); ~TaskQueue(); - // Run all the tasks in the queue. New tasks pushed onto the queue during - // a run will be run next time |Run| is called. - virtual void Run(); - // Push the specified task onto the queue. When the queue is run, the tasks // will be run in the order they are pushed. // @@ -35,6 +31,10 @@ class TaskQueue : public Task { // Returns true if this queue contains no tasks. bool IsEmpty() const; + // Run all the tasks in the queue. New tasks pushed onto the queue during + // a run will be run next time |Run| is called. + virtual void Run(); + private: // The list of tasks we are waiting to run. std::deque<Task*> queue_; diff --git a/base/test/test_file_util_win.cc b/base/test/test_file_util_win.cc index fc3d018..7ca7e84 100644 --- a/base/test/test_file_util_win.cc +++ b/base/test/test_file_util_win.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2008 The Chromium Authors. All rights reserved. +// 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. @@ -12,8 +12,8 @@ #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" -#include "base/platform_thread.h" -#include "base/scoped_handle.h" +#include "base/win/scoped_handle.h" +#include "base/threading/platform_thread.h" namespace file_util { @@ -32,14 +32,14 @@ bool DieFileDie(const FilePath& file, bool recurse) { for (int i = 0; i < 25; ++i) { if (file_util::Delete(file, recurse)) return true; - PlatformThread::Sleep(kTimeoutMs / 25); + base::PlatformThread::Sleep(kTimeoutMs / 25); } return false; } bool EvictFileFromSystemCache(const FilePath& file) { // Request exclusive access to the file and overwrite it with no buffering. - ScopedHandle file_handle( + base::win::ScopedHandle file_handle( CreateFile(file.value().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL)); if (!file_handle) @@ -203,7 +203,7 @@ bool HasInternetZoneIdentifier(const FilePath& full_path) { // Windows does not guarantee that we will get the same contents even after // the other process closes the handle, flushes the buffers, etc. for (int i = 0; i < 20; i++) { - PlatformThread::Sleep(1000); + base::PlatformThread::Sleep(1000); const DWORD kShare = FILE_SHARE_READ | FILE_SHARE_WRITE | diff --git a/base/test/test_suite.cc b/base/test/test_suite.cc index 7d25a60..aa23f04 100644 --- a/base/test/test_suite.cc +++ b/base/test/test_suite.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// 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. @@ -8,9 +8,7 @@ #include "base/base_paths.h" #include "base/base_switches.h" #include "base/command_line.h" -#include "base/debug_on_start.h" -#include "base/debug_util.h" -#include "base/debug/debugger.h" +#include "base/debug/debug_on_start_win.h" #include "base/debug/debugger.h" #include "base/file_path.h" #include "base/i18n/icu_util.h" @@ -196,7 +194,7 @@ void TestSuite::Initialize() { if (!base::debug::BeingDebugged() && !CommandLine::ForCurrentProcess()->HasSwitch("show-error-dialogs")) { SuppressErrorDialogs(); - DebugUtil::SuppressDialogs(); + base::debug::SetSuppressDebugUI(true); logging::SetLogAssertHandler(UnitTestAssertHandler); } diff --git a/base/test/test_timeouts.cc b/base/test/test_timeouts.cc index 046f320..016456e 100644 --- a/base/test/test_timeouts.cc +++ b/base/test/test_timeouts.cc @@ -55,7 +55,7 @@ int TestTimeouts::command_execution_timeout_ms_ = 25000; int TestTimeouts::wait_for_terminate_timeout_ms_ = 15000; // static -int TestTimeouts::live_operation_timeout_ms_ = 30000; +int TestTimeouts::live_operation_timeout_ms_ = 45000; // static void TestTimeouts::Initialize() { diff --git a/base/non_thread_safe.cc b/base/threading/non_thread_safe.cc index b01ed55..8b41bc0 100644 --- a/base/non_thread_safe.cc +++ b/base/threading/non_thread_safe.cc @@ -2,13 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/non_thread_safe.h" +#include "base/threading/non_thread_safe.h" // These checks are only done in debug builds. #ifndef NDEBUG #include "base/logging.h" +namespace base { + NonThreadSafe::~NonThreadSafe() { DCHECK(CalledOnValidThread()); } @@ -21,4 +23,6 @@ void NonThreadSafe::DetachFromThread() { thread_checker_.DetachFromThread(); } +} // namespace base + #endif // NDEBUG diff --git a/base/non_thread_safe.h b/base/threading/non_thread_safe.h index 6f993ee..868a031 100644 --- a/base/non_thread_safe.h +++ b/base/threading/non_thread_safe.h @@ -2,12 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_NON_THREAD_SAFE_H_ -#define BASE_NON_THREAD_SAFE_H_ +#ifndef BASE_THREADING_NON_THREAD_SAFE_H_ +#define BASE_THREADING_NON_THREAD_SAFE_H_ #pragma once -#include "base/platform_thread.h" -#include "base/thread_checker.h" +#include "base/threading/thread_checker.h" + +namespace base { // A helper class used to help verify that methods of a class are // called from the same thread. One can inherit from this class and use @@ -17,7 +18,7 @@ // aren't. For example, a service or a singleton like the preferences system. // // Example: -// class MyClass : public NonThreadSafe { +// class MyClass : public base::NonThreadSafe { // public: // void Foo() { // DCHECK(CalledOnValidThread()); @@ -58,4 +59,6 @@ class NonThreadSafe { }; #endif // NDEBUG +} // namespace base + #endif // BASE_NON_THREAD_SAFE_H_ diff --git a/base/non_thread_safe_unittest.cc b/base/threading/non_thread_safe_unittest.cc index 1db198b..7d158cf 100644 --- a/base/non_thread_safe_unittest.cc +++ b/base/threading/non_thread_safe_unittest.cc @@ -4,13 +4,15 @@ #include "base/basictypes.h" #include "base/logging.h" -#include "base/non_thread_safe.h" #include "base/scoped_ptr.h" -#include "base/simple_thread.h" +#include "base/threading/non_thread_safe.h" +#include "base/threading/simple_thread.h" #include "testing/gtest/include/gtest/gtest.h" #ifndef NDEBUG +namespace base { + // Simple class to exersice the basics of NonThreadSafe. // Both the destructor and DoStuff should verify that they were // called on the same thread as the constructor. @@ -32,7 +34,7 @@ class NonThreadSafeClass : public NonThreadSafe { }; // Calls NonThreadSafeClass::DoStuff on another thread. -class CallDoStuffOnThread : public base::SimpleThread { +class CallDoStuffOnThread : public SimpleThread { public: CallDoStuffOnThread(NonThreadSafeClass* non_thread_safe_class) : SimpleThread("call_do_stuff_on_thread"), @@ -50,7 +52,7 @@ class CallDoStuffOnThread : public base::SimpleThread { }; // Deletes NonThreadSafeClass on a different thread. -class DeleteNonThreadSafeClassOnThread : public base::SimpleThread { +class DeleteNonThreadSafeClassOnThread : public SimpleThread { public: DeleteNonThreadSafeClassOnThread(NonThreadSafeClass* non_thread_safe_class) : SimpleThread("delete_non_thread_safe_class_on_thread"), @@ -123,4 +125,6 @@ TEST(NonThreadSafeDeathTest, DestructorNotAllowedOnDifferentThread) { #endif // GTEST_HAS_DEATH_TEST +} // namespace base + #endif // NDEBUG diff --git a/base/platform_thread.h b/base/threading/platform_thread.h index 43bf298..0a3c75d 100644 --- a/base/platform_thread.h +++ b/base/threading/platform_thread.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -6,30 +6,40 @@ // the low-level platform-specific abstraction to the OS's threading interface. // You should instead be using a message-loop driven Thread, see thread.h. -#ifndef BASE_PLATFORM_THREAD_H_ -#define BASE_PLATFORM_THREAD_H_ +#ifndef BASE_THREADING_PLATFORM_THREAD_H_ +#define BASE_THREADING_PLATFORM_THREAD_H_ #pragma once #include "base/basictypes.h" +#include "build/build_config.h" + +#if defined(OS_WIN) +#include <windows.h> +#elif defined(OS_POSIX) +#include <pthread.h> +#if defined(OS_MACOSX) +#include <mach/mach.h> +#else // OS_POSIX && !OS_MACOSX +#include <unistd.h> +#endif +#endif + +namespace base { // PlatformThreadHandle should not be assumed to be a numeric type, since the // standard intends to allow pthread_t to be a structure. This means you // should not initialize it to a value, like 0. If it's a member variable, the // constructor can safely "value initialize" using () in the initializer list. #if defined(OS_WIN) -#include <windows.h> typedef DWORD PlatformThreadId; typedef void* PlatformThreadHandle; // HANDLE const PlatformThreadHandle kNullThreadHandle = NULL; #elif defined(OS_POSIX) -#include <pthread.h> typedef pthread_t PlatformThreadHandle; const PlatformThreadHandle kNullThreadHandle = 0; #if defined(OS_MACOSX) -#include <mach/mach.h> typedef mach_port_t PlatformThreadId; #else // OS_POSIX && !OS_MACOSX -#include <unistd.h> typedef pid_t PlatformThreadId; #endif #endif @@ -84,4 +94,6 @@ class PlatformThread { DISALLOW_IMPLICIT_CONSTRUCTORS(PlatformThread); }; -#endif // BASE_PLATFORM_THREAD_H_ +} // namespace base + +#endif // BASE_THREADING_PLATFORM_THREAD_H_ diff --git a/base/platform_thread_mac.mm b/base/threading/platform_thread_mac.mm index 36e08be..d77307c 100644 --- a/base/platform_thread_mac.mm +++ b/base/threading/platform_thread_mac.mm @@ -1,8 +1,8 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" #import <Foundation/Foundation.h> #include <dlfcn.h> @@ -32,8 +32,6 @@ void InitThreading() { } } -} // namespace base - // static void PlatformThread::SetName(const char* name) { // pthread_setname_np is only available in 10.6 or later, so test @@ -52,3 +50,5 @@ void PlatformThread::SetName(const char* name) { // See http://crbug.com/47058 dynamic_pthread_setname_np(shortened_name.c_str()); } + +} // namespace base diff --git a/base/platform_thread_posix.cc b/base/threading/platform_thread_posix.cc index 9807ac6..8452909 100644 --- a/base/platform_thread_posix.cc +++ b/base/threading/platform_thread_posix.cc @@ -1,8 +1,8 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" #include <errno.h> #include <sched.h> @@ -10,7 +10,7 @@ #include "base/logging.h" #include "base/safe_strerror_posix.h" #include "base/scoped_ptr.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" #if defined(OS_MACOSX) #include <mach/mach.h> @@ -29,10 +29,10 @@ #include <sys/nacl_syscalls.h> #endif -#if defined(OS_MACOSX) namespace base { + +#if defined(OS_MACOSX) void InitThreading(); -} // namespace base #endif namespace { @@ -42,9 +42,7 @@ struct ThreadParams { bool joinable; }; -} // namespace - -static void* ThreadFunc(void* params) { +void* ThreadFunc(void* params) { ThreadParams* thread_params = static_cast<ThreadParams*>(params); PlatformThread::Delegate* delegate = thread_params->delegate; if (!thread_params->joinable) @@ -54,6 +52,70 @@ static void* ThreadFunc(void* params) { return NULL; } +bool CreateThread(size_t stack_size, bool joinable, + PlatformThread::Delegate* delegate, + PlatformThreadHandle* thread_handle) { +#if defined(OS_MACOSX) + base::InitThreading(); +#endif // OS_MACOSX + + bool success = false; + pthread_attr_t attributes; + pthread_attr_init(&attributes); + + // Pthreads are joinable by default, so only specify the detached attribute if + // the thread should be non-joinable. + if (!joinable) { + pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED); + } + +#if defined(OS_MACOSX) + // The Mac OS X default for a pthread stack size is 512kB. + // Libc-594.1.4/pthreads/pthread.c's pthread_attr_init uses + // DEFAULT_STACK_SIZE for this purpose. + // + // 512kB isn't quite generous enough for some deeply recursive threads that + // otherwise request the default stack size by specifying 0. Here, adopt + // glibc's behavior as on Linux, which is to use the current stack size + // limit (ulimit -s) as the default stack size. See + // glibc-2.11.1/nptl/nptl-init.c's __pthread_initialize_minimal_internal. To + // avoid setting the limit below the Mac OS X default or the minimum usable + // stack size, these values are also considered. If any of these values + // can't be determined, or if stack size is unlimited (ulimit -s unlimited), + // stack_size is left at 0 to get the system default. + // + // Mac OS X normally only applies ulimit -s to the main thread stack. On + // contemporary OS X and Linux systems alike, this value is generally 8MB + // or in that neighborhood. + if (stack_size == 0) { + size_t default_stack_size; + struct rlimit stack_rlimit; + if (pthread_attr_getstacksize(&attributes, &default_stack_size) == 0 && + getrlimit(RLIMIT_STACK, &stack_rlimit) == 0 && + stack_rlimit.rlim_cur != RLIM_INFINITY) { + stack_size = std::max(std::max(default_stack_size, + static_cast<size_t>(PTHREAD_STACK_MIN)), + static_cast<size_t>(stack_rlimit.rlim_cur)); + } + } +#endif // OS_MACOSX + + if (stack_size > 0) + pthread_attr_setstacksize(&attributes, stack_size); + + ThreadParams* params = new ThreadParams; + params->delegate = delegate; + params->joinable = joinable; + success = !pthread_create(thread_handle, &attributes, ThreadFunc, params); + + pthread_attr_destroy(&attributes); + if (!success) + delete params; + return success; +} + +} // namespace + // static PlatformThreadId PlatformThread::CurrentId() { // Pthreads doesn't have the concept of a thread ID, so we have to reach down @@ -135,72 +197,6 @@ void PlatformThread::SetName(const char* name) { } #endif // defined(OS_LINUX) -namespace { - -bool CreateThread(size_t stack_size, bool joinable, - PlatformThread::Delegate* delegate, - PlatformThreadHandle* thread_handle) { -#if defined(OS_MACOSX) - base::InitThreading(); -#endif // OS_MACOSX - - bool success = false; - pthread_attr_t attributes; - pthread_attr_init(&attributes); - - // Pthreads are joinable by default, so only specify the detached attribute if - // the thread should be non-joinable. - if (!joinable) { - pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED); - } - -#if defined(OS_MACOSX) - // The Mac OS X default for a pthread stack size is 512kB. - // Libc-594.1.4/pthreads/pthread.c's pthread_attr_init uses - // DEFAULT_STACK_SIZE for this purpose. - // - // 512kB isn't quite generous enough for some deeply recursive threads that - // otherwise request the default stack size by specifying 0. Here, adopt - // glibc's behavior as on Linux, which is to use the current stack size - // limit (ulimit -s) as the default stack size. See - // glibc-2.11.1/nptl/nptl-init.c's __pthread_initialize_minimal_internal. To - // avoid setting the limit below the Mac OS X default or the minimum usable - // stack size, these values are also considered. If any of these values - // can't be determined, or if stack size is unlimited (ulimit -s unlimited), - // stack_size is left at 0 to get the system default. - // - // Mac OS X normally only applies ulimit -s to the main thread stack. On - // contemporary OS X and Linux systems alike, this value is generally 8MB - // or in that neighborhood. - if (stack_size == 0) { - size_t default_stack_size; - struct rlimit stack_rlimit; - if (pthread_attr_getstacksize(&attributes, &default_stack_size) == 0 && - getrlimit(RLIMIT_STACK, &stack_rlimit) == 0 && - stack_rlimit.rlim_cur != RLIM_INFINITY) { - stack_size = std::max(std::max(default_stack_size, - static_cast<size_t>(PTHREAD_STACK_MIN)), - static_cast<size_t>(stack_rlimit.rlim_cur)); - } - } -#endif // OS_MACOSX - - if (stack_size > 0) - pthread_attr_setstacksize(&attributes, stack_size); - - ThreadParams* params = new ThreadParams; - params->delegate = delegate; - params->joinable = joinable; - success = !pthread_create(thread_handle, &attributes, ThreadFunc, params); - - pthread_attr_destroy(&attributes); - if (!success) - delete params; - return success; -} - -} // anonymous namespace - // static bool PlatformThread::Create(size_t stack_size, Delegate* delegate, PlatformThreadHandle* thread_handle) { @@ -225,3 +221,5 @@ void PlatformThread::Join(PlatformThreadHandle thread_handle) { base::ThreadRestrictions::AssertIOAllowed(); pthread_join(thread_handle, NULL); } + +} // namespace base diff --git a/base/platform_thread_unittest.cc b/base/threading/platform_thread_unittest.cc index 9875aa8..4b49450 100644 --- a/base/platform_thread_unittest.cc +++ b/base/threading/platform_thread_unittest.cc @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" #include "testing/gtest/include/gtest/gtest.h" -typedef testing::Test PlatformThreadTest; +namespace base { // Trivial tests that thread runs and doesn't crash on create and join --------- @@ -26,7 +26,7 @@ class TrivialThread : public PlatformThread::Delegate { DISALLOW_COPY_AND_ASSIGN(TrivialThread); }; -TEST_F(PlatformThreadTest, Trivial) { +TEST(PlatformThreadTest, Trivial) { TrivialThread thread; PlatformThreadHandle handle = kNullThreadHandle; @@ -36,7 +36,7 @@ TEST_F(PlatformThreadTest, Trivial) { ASSERT_TRUE(thread.did_run()); } -TEST_F(PlatformThreadTest, TrivialTimesTen) { +TEST(PlatformThreadTest, TrivialTimesTen) { TrivialThread thread[10]; PlatformThreadHandle handle[arraysize(thread)]; @@ -72,7 +72,7 @@ class FunctionTestThread : public TrivialThread { DISALLOW_COPY_AND_ASSIGN(FunctionTestThread); }; -TEST_F(PlatformThreadTest, Function) { +TEST(PlatformThreadTest, Function) { PlatformThreadId main_thread_id = PlatformThread::CurrentId(); FunctionTestThread thread; @@ -85,7 +85,7 @@ TEST_F(PlatformThreadTest, Function) { EXPECT_NE(thread.thread_id(), main_thread_id); } -TEST_F(PlatformThreadTest, FunctionTimesTen) { +TEST(PlatformThreadTest, FunctionTimesTen) { PlatformThreadId main_thread_id = PlatformThread::CurrentId(); FunctionTestThread thread[10]; @@ -102,3 +102,5 @@ TEST_F(PlatformThreadTest, FunctionTimesTen) { EXPECT_NE(thread[n].thread_id(), main_thread_id); } } + +} // namespace base diff --git a/base/platform_thread_win.cc b/base/threading/platform_thread_win.cc index ac8a5db..734f404 100644 --- a/base/platform_thread_win.cc +++ b/base/threading/platform_thread_win.cc @@ -2,12 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" #include "base/logging.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" #include "base/win/windows_version.h" +namespace base { + namespace { // The information on how to set the thread name comes from @@ -141,3 +143,5 @@ void PlatformThread::Join(PlatformThreadHandle thread_handle) { CloseHandle(thread_handle); } + +} // namespace base diff --git a/base/simple_thread.cc b/base/threading/simple_thread.cc index 086a430..2b030f6 100644 --- a/base/simple_thread.cc +++ b/base/threading/simple_thread.cc @@ -1,11 +1,11 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/simple_thread.h" +#include "base/threading/simple_thread.h" #include "base/logging.h" -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" #include "base/string_number_conversions.h" namespace base { diff --git a/base/simple_thread.h b/base/threading/simple_thread.h index 13c46c0..f55bd62 100644 --- a/base/simple_thread.h +++ b/base/threading/simple_thread.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. @@ -37,8 +37,8 @@ // // The SimpleThread object is still valid, however you may not call Join // // or Start again. -#ifndef BASE_SIMPLE_THREAD_H_ -#define BASE_SIMPLE_THREAD_H_ +#ifndef BASE_THREADING_SIMPLE_THREAD_H_ +#define BASE_THREADING_SIMPLE_THREAD_H_ #pragma once #include <string> @@ -47,8 +47,8 @@ #include "base/basictypes.h" #include "base/lock.h" -#include "base/waitable_event.h" -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" +#include "base/synchronization/waitable_event.h" namespace base { @@ -82,9 +82,6 @@ class SimpleThread : public PlatformThread::Delegate { virtual void Start(); virtual void Join(); - // We follow the PlatformThread Delegate interface. - virtual void ThreadMain(); - // Subclasses should override the Run method. virtual void Run() = 0; @@ -103,6 +100,9 @@ class SimpleThread : public PlatformThread::Delegate { // Return True if Join() has evern been called. bool HasBeenJoined() { return joined_; } + // Overridden from PlatformThread::Delegate: + virtual void ThreadMain(); + private: const std::string name_prefix_; std::string name_; @@ -179,4 +179,4 @@ class DelegateSimpleThreadPool : public DelegateSimpleThread::Delegate { } // namespace base -#endif // BASE_SIMPLE_THREAD_H_ +#endif // BASE_THREADING_SIMPLE_THREAD_H_ diff --git a/base/simple_thread_unittest.cc b/base/threading/simple_thread_unittest.cc index 208290a..4014d70 100644 --- a/base/simple_thread_unittest.cc +++ b/base/threading/simple_thread_unittest.cc @@ -3,14 +3,16 @@ // found in the LICENSE file. #include "base/atomic_sequence_num.h" -#include "base/simple_thread.h" #include "base/string_number_conversions.h" -#include "base/waitable_event.h" +#include "base/threading/simple_thread.h" +#include "base/synchronization/waitable_event.h" #include "testing/gtest/include/gtest/gtest.h" +namespace base { + namespace { -class SetIntRunner : public base::DelegateSimpleThread::Delegate { +class SetIntRunner : public DelegateSimpleThread::Delegate { public: SetIntRunner(int* ptr, int val) : ptr_(ptr), val_(val) { } ~SetIntRunner() { } @@ -24,9 +26,9 @@ class SetIntRunner : public base::DelegateSimpleThread::Delegate { int val_; }; -class WaitEventRunner : public base::DelegateSimpleThread::Delegate { +class WaitEventRunner : public DelegateSimpleThread::Delegate { public: - explicit WaitEventRunner(base::WaitableEvent* event) : event_(event) { } + explicit WaitEventRunner(WaitableEvent* event) : event_(event) { } ~WaitEventRunner() { } virtual void Run() { @@ -35,27 +37,27 @@ class WaitEventRunner : public base::DelegateSimpleThread::Delegate { EXPECT_TRUE(event_->IsSignaled()); } private: - base::WaitableEvent* event_; + WaitableEvent* event_; }; -class SeqRunner : public base::DelegateSimpleThread::Delegate { +class SeqRunner : public DelegateSimpleThread::Delegate { public: - explicit SeqRunner(base::AtomicSequenceNumber* seq) : seq_(seq) { } + explicit SeqRunner(AtomicSequenceNumber* seq) : seq_(seq) { } virtual void Run() { seq_->GetNext(); } private: - base::AtomicSequenceNumber* seq_; + AtomicSequenceNumber* seq_; }; // We count up on a sequence number, firing on the event when we've hit our // expected amount, otherwise we wait on the event. This will ensure that we // have all threads outstanding until we hit our expected thread pool size. -class VerifyPoolRunner : public base::DelegateSimpleThread::Delegate { +class VerifyPoolRunner : public DelegateSimpleThread::Delegate { public: - VerifyPoolRunner(base::AtomicSequenceNumber* seq, - int total, base::WaitableEvent* event) + VerifyPoolRunner(AtomicSequenceNumber* seq, + int total, WaitableEvent* event) : seq_(seq), total_(total), event_(event) { } virtual void Run() { @@ -67,9 +69,9 @@ class VerifyPoolRunner : public base::DelegateSimpleThread::Delegate { } private: - base::AtomicSequenceNumber* seq_; + AtomicSequenceNumber* seq_; int total_; - base::WaitableEvent* event_; + WaitableEvent* event_; }; } // namespace @@ -80,7 +82,7 @@ TEST(SimpleThreadTest, CreateAndJoin) { SetIntRunner runner(&stack_int, 7); EXPECT_EQ(0, stack_int); - base::DelegateSimpleThread thread(&runner, "int_setter"); + DelegateSimpleThread thread(&runner, "int_setter"); EXPECT_FALSE(thread.HasBeenStarted()); EXPECT_FALSE(thread.HasBeenJoined()); EXPECT_EQ(0, stack_int); @@ -97,10 +99,10 @@ TEST(SimpleThreadTest, CreateAndJoin) { TEST(SimpleThreadTest, WaitForEvent) { // Create a thread, and wait for it to signal us. - base::WaitableEvent event(true, false); + WaitableEvent event(true, false); WaitEventRunner runner(&event); - base::DelegateSimpleThread thread(&runner, "event_waiter"); + DelegateSimpleThread thread(&runner, "event_waiter"); EXPECT_FALSE(event.IsSignaled()); thread.Start(); @@ -110,18 +112,18 @@ TEST(SimpleThreadTest, WaitForEvent) { } TEST(SimpleThreadTest, NamedWithOptions) { - base::WaitableEvent event(true, false); + WaitableEvent event(true, false); WaitEventRunner runner(&event); - base::SimpleThread::Options options; - base::DelegateSimpleThread thread(&runner, "event_waiter", options); + SimpleThread::Options options; + DelegateSimpleThread thread(&runner, "event_waiter", options); EXPECT_EQ(thread.name_prefix(), "event_waiter"); EXPECT_FALSE(event.IsSignaled()); thread.Start(); EXPECT_EQ(thread.name_prefix(), "event_waiter"); EXPECT_EQ(thread.name(), - std::string("event_waiter/") + base::IntToString(thread.tid())); + std::string("event_waiter/") + IntToString(thread.tid())); event.Wait(); EXPECT_TRUE(event.IsSignaled()); @@ -130,13 +132,13 @@ TEST(SimpleThreadTest, NamedWithOptions) { // We keep the name and tid, even after the thread is gone. EXPECT_EQ(thread.name_prefix(), "event_waiter"); EXPECT_EQ(thread.name(), - std::string("event_waiter/") + base::IntToString(thread.tid())); + std::string("event_waiter/") + IntToString(thread.tid())); } TEST(SimpleThreadTest, ThreadPool) { - base::AtomicSequenceNumber seq; + AtomicSequenceNumber seq; SeqRunner runner(&seq); - base::DelegateSimpleThreadPool pool("seq_runner", 10); + DelegateSimpleThreadPool pool("seq_runner", 10); // Add work before we're running. pool.AddWork(&runner, 300); @@ -153,8 +155,8 @@ TEST(SimpleThreadTest, ThreadPool) { // We can reuse our pool. Verify that all 10 threads can actually run in // parallel, so this test will only pass if there are actually 10 threads. - base::AtomicSequenceNumber seq2; - base::WaitableEvent event(true, false); + AtomicSequenceNumber seq2; + WaitableEvent event(true, false); // Changing 9 to 10, for example, would cause us JoinAll() to never return. VerifyPoolRunner verifier(&seq2, 9, &event); pool.Start(); @@ -164,3 +166,5 @@ TEST(SimpleThreadTest, ThreadPool) { pool.JoinAll(); EXPECT_EQ(seq2.GetNext(), 10); } + +} // namespace base diff --git a/base/thread.cc b/base/threading/thread.cc index bc715f0..09f8847 100644 --- a/base/thread.cc +++ b/base/threading/thread.cc @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/thread.h" +#include "base/threading/thread.h" #include "base/lazy_instance.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" -#include "base/thread_local.h" -#include "base/waitable_event.h" +#include "base/threading/thread_local.h" +#include "base/synchronization/waitable_event.h" namespace base { diff --git a/base/thread.h b/base/threading/thread.h index fc542f0..811dd80 100644 --- a/base/thread.h +++ b/base/threading/thread.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// 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. @@ -10,7 +10,7 @@ #include "base/message_loop.h" #include "base/message_loop_proxy.h" -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" namespace base { @@ -29,6 +29,10 @@ namespace base { class Thread : PlatformThread::Delegate { public: struct Options { + Options() : message_loop_type(MessageLoop::TYPE_DEFAULT), stack_size(0) {} + Options(MessageLoop::Type type, size_t size) + : message_loop_type(type), stack_size(size) {} + // Specifies the type of message loop that will be allocated on the thread. MessageLoop::Type message_loop_type; @@ -36,10 +40,6 @@ class Thread : PlatformThread::Delegate { // This does not necessarily correspond to the thread's initial stack size. // A value of 0 indicates that the default maximum should be used. size_t stack_size; - - Options() : message_loop_type(MessageLoop::TYPE_DEFAULT), stack_size(0) {} - Options(MessageLoop::Type type, size_t size) - : message_loop_type(type), stack_size(size) {} }; // Constructor. @@ -152,11 +152,11 @@ class Thread : PlatformThread::Delegate { } private: + bool thread_was_started() const { return started_; } + // PlatformThread::Delegate methods: virtual void ThreadMain(); - bool thread_was_started() const { return started_; } - // Whether we successfully started the thread. bool started_; diff --git a/base/thread_checker.cc b/base/threading/thread_checker.cc index 52f9847..28ba400 100644 --- a/base/thread_checker.cc +++ b/base/threading/thread_checker.cc @@ -2,11 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/thread_checker.h" +#include "base/threading/thread_checker.h" // This code is only done in debug builds. #ifndef NDEBUG +namespace base { + ThreadChecker::ThreadChecker() : valid_thread_id_(kInvalidThreadId) { EnsureThreadIdAssigned(); } @@ -31,4 +33,6 @@ void ThreadChecker::EnsureThreadIdAssigned() const { valid_thread_id_ = PlatformThread::CurrentId(); } +} // namespace base + #endif // NDEBUG diff --git a/base/thread_checker.h b/base/threading/thread_checker.h index c09bcbe..c0010fb 100644 --- a/base/thread_checker.h +++ b/base/threading/thread_checker.h @@ -2,15 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_THREAD_CHECKER_H_ -#define BASE_THREAD_CHECKER_H_ +#ifndef BASE_THREADING_THREAD_CHECKER_H_ +#define BASE_THREADING_THREAD_CHECKER_H_ #pragma once #ifndef NDEBUG #include "base/lock.h" -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" #endif // NDEBUG +namespace base { + // Before using this class, please consider using NonThreadSafe as it // makes it much easier to determine the nature of your class. // @@ -66,4 +68,6 @@ class ThreadChecker { }; #endif // NDEBUG -#endif // BASE_THREAD_CHECKER_H_ +} // namespace base + +#endif // BASE_THREADING_THREAD_CHECKER_H_ diff --git a/base/thread_checker_unittest.cc b/base/threading/thread_checker_unittest.cc index 6c55348..6ce5bf1 100644 --- a/base/thread_checker_unittest.cc +++ b/base/threading/thread_checker_unittest.cc @@ -4,13 +4,15 @@ #include "base/basictypes.h" #include "base/logging.h" -#include "base/thread_checker.h" #include "base/scoped_ptr.h" -#include "base/simple_thread.h" +#include "base/threading/thread_checker.h" +#include "base/threading/simple_thread.h" #include "testing/gtest/include/gtest/gtest.h" #ifndef NDEBUG +namespace base { + // Simple class to exersice the basics of ThreadChecker. // Both the destructor and DoStuff should verify that they were // called on the same thread as the constructor. @@ -139,4 +141,6 @@ TEST(ThreadCheckerDeathTest, DetachFromThread) { #endif // GTEST_HAS_DEATH_TEST +} // namespace base + #endif // NDEBUG diff --git a/base/thread_collision_warner.cc b/base/threading/thread_collision_warner.cc index 1a13643..547e11c 100644 --- a/base/thread_collision_warner.cc +++ b/base/threading/thread_collision_warner.cc @@ -1,11 +1,11 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/thread_collision_warner.h" +#include "base/threading/thread_collision_warner.h" #include "base/logging.h" -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" namespace base { diff --git a/base/thread_collision_warner.h b/base/threading/thread_collision_warner.h index 1e14d1a..17ed5a4 100644 --- a/base/thread_collision_warner.h +++ b/base/threading/thread_collision_warner.h @@ -1,9 +1,9 @@ -// Copyright (c) 2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2009 The Chromium 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_THREAD_COLLISION_WARNER_H_ -#define BASE_THREAD_COLLISION_WARNER_H_ +#ifndef BASE_THREADING_THREAD_COLLISION_WARNER_H_ +#define BASE_THREADING_THREAD_COLLISION_WARNER_H_ #pragma once #include <memory> @@ -240,4 +240,4 @@ class ThreadCollisionWarner { } // namespace base -#endif // BASE_THREAD_COLLISION_WARNER_H_ +#endif // BASE_THREADING_THREAD_COLLISION_WARNER_H_ diff --git a/base/thread_collision_warner_unittest.cc b/base/threading/thread_collision_warner_unittest.cc index b70cfbe..68987c3 100644 --- a/base/thread_collision_warner_unittest.cc +++ b/base/threading/thread_collision_warner_unittest.cc @@ -1,13 +1,13 @@ -// Copyright (c) 2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/compiler_specific.h" #include "base/lock.h" -#include "base/platform_thread.h" #include "base/scoped_ptr.h" -#include "base/simple_thread.h" -#include "base/thread_collision_warner.h" +#include "base/threading/platform_thread.h" +#include "base/threading/simple_thread.h" +#include "base/threading/thread_collision_warner.h" #include "testing/gtest/include/gtest/gtest.h" // '' : local class member function does not have a body @@ -190,7 +190,7 @@ TEST(ThreadCollisionTest, MTScopedBookCriticalSectionTest) { void push(int value) { DFAKE_SCOPED_LOCK(push_pop_); - PlatformThread::Sleep(5000); + base::PlatformThread::Sleep(5000); } int pop() { @@ -248,7 +248,7 @@ TEST(ThreadCollisionTest, MTSynchedScopedBookCriticalSectionTest) { void push(int value) { DFAKE_SCOPED_LOCK(push_pop_); - PlatformThread::Sleep(2000); + base::PlatformThread::Sleep(2000); } int pop() { @@ -318,7 +318,7 @@ TEST(ThreadCollisionTest, MTSynchedScopedRecursiveBookCriticalSectionTest) { void push(int) { DFAKE_SCOPED_RECURSIVE_LOCK(push_pop_); bar(); - PlatformThread::Sleep(2000); + base::PlatformThread::Sleep(2000); } int pop() { diff --git a/base/thread_local.h b/base/threading/thread_local.h index eba48d2..069543f 100644 --- a/base/thread_local.h +++ b/base/threading/thread_local.h @@ -45,8 +45,8 @@ // return Singleton<ThreadLocalPointer<MyClass> >::get()->Get(); // } -#ifndef BASE_THREAD_LOCAL_H_ -#define BASE_THREAD_LOCAL_H_ +#ifndef BASE_THREADING_THREAD_LOCAL_H_ +#define BASE_THREADING_THREAD_LOCAL_H_ #pragma once #include "base/basictypes.h" @@ -124,4 +124,4 @@ class ThreadLocalBoolean { } // namespace base -#endif // BASE_THREAD_LOCAL_H_ +#endif // BASE_THREADING_THREAD_LOCAL_H_ diff --git a/base/thread_local_posix.cc b/base/threading/thread_local_posix.cc index 4d03403..568fa4b 100644 --- a/base/thread_local_posix.cc +++ b/base/threading/thread_local_posix.cc @@ -1,8 +1,8 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/thread_local.h" +#include "base/threading/thread_local.h" #include <pthread.h> diff --git a/base/thread_local_storage.h b/base/threading/thread_local_storage.h index b37a53c..204b653 100644 --- a/base/thread_local_storage.h +++ b/base/threading/thread_local_storage.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_THREAD_LOCAL_STORAGE_H_ -#define BASE_THREAD_LOCAL_STORAGE_H_ +#ifndef BASE_THREADING_THREAD_LOCAL_STORAGE_H_ +#define BASE_THREADING_THREAD_LOCAL_STORAGE_H_ #pragma once #include "base/basictypes.h" @@ -12,6 +12,8 @@ #include <pthread.h> #endif +namespace base { + // Wrapper for thread local storage. This class doesn't do much except provide // an API for portability. class ThreadLocalStorage { @@ -88,8 +90,6 @@ class ThreadLocalStorage { DISALLOW_COPY_AND_ASSIGN(ThreadLocalStorage); }; -// Temporary backwards-compatible name. -// TODO(evanm): replace all usage of TLSSlot. -typedef ThreadLocalStorage::Slot TLSSlot; +} // namespace base -#endif // BASE_THREAD_LOCAL_STORAGE_H_ +#endif // BASE_THREADING_THREAD_LOCAL_STORAGE_H_ diff --git a/base/thread_local_storage_posix.cc b/base/threading/thread_local_storage_posix.cc index eac74fd..81b7332 100644 --- a/base/thread_local_storage_posix.cc +++ b/base/threading/thread_local_storage_posix.cc @@ -1,11 +1,13 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/thread_local_storage.h" +#include "base/threading/thread_local_storage.h" #include "base/logging.h" +namespace base { + ThreadLocalStorage::Slot::Slot(TLSDestructorFunc destructor) : initialized_(false) { Initialize(destructor); @@ -42,3 +44,5 @@ void ThreadLocalStorage::Slot::Set(void* value) { if (error) NOTREACHED(); } + +} // namespace base diff --git a/base/thread_local_storage_unittest.cc b/base/threading/thread_local_storage_unittest.cc index cb24c75..216e650 100644 --- a/base/thread_local_storage_unittest.cc +++ b/base/threading/thread_local_storage_unittest.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -7,8 +7,8 @@ #include <process.h> #endif -#include "base/simple_thread.h" -#include "base/thread_local_storage.h" +#include "base/threading/simple_thread.h" +#include "base/threading/thread_local_storage.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_WIN) @@ -17,11 +17,14 @@ #pragma warning(disable : 4311 4312) #endif -const int kInitialTlsValue = 0x5555; -static ThreadLocalStorage::Slot tls_slot(base::LINKER_INITIALIZED); +namespace base { + +namespace { +const int kInitialTlsValue = 0x5555; +static ThreadLocalStorage::Slot tls_slot(LINKER_INITIALIZED); -class ThreadLocalStorageRunner : public base::DelegateSimpleThread::Delegate { +class ThreadLocalStorageRunner : public DelegateSimpleThread::Delegate { public: explicit ThreadLocalStorageRunner(int* tls_value_ptr) : tls_value_ptr_(tls_value_ptr) {} @@ -54,6 +57,7 @@ void ThreadLocalStorageCleanup(void *value) { *ptr = kInitialTlsValue; } +} // namespace TEST(ThreadLocalStorageTest, Basics) { ThreadLocalStorage::Slot slot; @@ -69,7 +73,7 @@ TEST(ThreadLocalStorageTest, TLSDestructors) { const int kNumThreads = 5; int values[kNumThreads]; ThreadLocalStorageRunner* thread_delegates[kNumThreads]; - base::DelegateSimpleThread* threads[kNumThreads]; + DelegateSimpleThread* threads[kNumThreads]; tls_slot.Initialize(ThreadLocalStorageCleanup); @@ -77,8 +81,8 @@ TEST(ThreadLocalStorageTest, TLSDestructors) { for (int index = 0; index < kNumThreads; index++) { values[index] = kInitialTlsValue; thread_delegates[index] = new ThreadLocalStorageRunner(&values[index]); - threads[index] = new base::DelegateSimpleThread(thread_delegates[index], - "tls thread"); + threads[index] = new DelegateSimpleThread(thread_delegates[index], + "tls thread"); threads[index]->Start(); } @@ -92,3 +96,5 @@ TEST(ThreadLocalStorageTest, TLSDestructors) { EXPECT_EQ(values[index], kInitialTlsValue); } } + +} // namespace base diff --git a/base/thread_local_storage_win.cc b/base/threading/thread_local_storage_win.cc index 7f8ea27..2967a27 100644 --- a/base/thread_local_storage_win.cc +++ b/base/threading/thread_local_storage_win.cc @@ -1,13 +1,15 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/thread_local_storage.h" +#include "base/threading/thread_local_storage.h" #include <windows.h> #include "base/logging.h" +namespace base { + // In order to make TLS destructors work, we need to keep function // pointers to the destructor for each TLS that we allocate. // We make this work by allocating a single OS-level TLS, which @@ -122,6 +124,8 @@ void ThreadLocalStorage::ThreadExit() { TlsSetValue(tls_key_, NULL); } +} // namespace base + // Thread Termination Callbacks. // Windows doesn't support a per-thread destructor with its // TLS primitives. So, we build it manually by inserting a @@ -150,7 +154,7 @@ void NTAPI OnThreadExit(PVOID module, DWORD reason, PVOID reserved) { // On XP SP0 & SP1, the DLL_PROCESS_ATTACH is never seen. It is sent on SP2+ // and on W2K and W2K3. So don't assume it is sent. if (DLL_THREAD_DETACH == reason || DLL_PROCESS_DETACH == reason) - ThreadLocalStorage::ThreadExit(); + base::ThreadLocalStorage::ThreadExit(); } // .CRT$XLA to .CRT$XLZ is an array of PIMAGE_TLS_CALLBACK pointers that are diff --git a/base/thread_local_unittest.cc b/base/threading/thread_local_unittest.cc index 7632c56..ba12898 100644 --- a/base/thread_local_unittest.cc +++ b/base/threading/thread_local_unittest.cc @@ -1,13 +1,15 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" -#include "base/simple_thread.h" -#include "base/thread_local.h" -#include "base/waitable_event.h" +#include "base/threading/simple_thread.h" +#include "base/threading/thread_local.h" +#include "base/synchronization/waitable_event.h" #include "testing/gtest/include/gtest/gtest.h" +namespace base { + namespace { class ThreadLocalTesterBase : public base::DelegateSimpleThreadPool::Delegate { @@ -157,3 +159,5 @@ TEST(ThreadLocalTest, Boolean) { EXPECT_FALSE(tlb.Get()); } } + +} // namespace base diff --git a/base/thread_local_win.cc b/base/threading/thread_local_win.cc index ea14a67..56d3a3a 100644 --- a/base/thread_local_win.cc +++ b/base/threading/thread_local_win.cc @@ -1,8 +1,8 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/thread_local.h" +#include "base/threading/thread_local.h" #include <windows.h> diff --git a/base/thread_restrictions.cc b/base/threading/thread_restrictions.cc index 6767d80..a0c24b0 100644 --- a/base/thread_restrictions.cc +++ b/base/threading/thread_restrictions.cc @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" // This entire file is compiled out in Release mode. #ifndef NDEBUG #include "base/lazy_instance.h" #include "base/logging.h" -#include "base/thread_local.h" +#include "base/threading/thread_local.h" namespace base { diff --git a/base/thread_restrictions.h b/base/threading/thread_restrictions.h index 51e5a15..de8174f 100644 --- a/base/thread_restrictions.h +++ b/base/threading/thread_restrictions.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_THREAD_RESTRICTIONS_H_ -#define BASE_THREAD_RESTRICTIONS_H_ +#ifndef BASE_THREADING_THREAD_RESTRICTIONS_H_ +#define BASE_THREADING_THREAD_RESTRICTIONS_H_ #include "base/basictypes.h" @@ -97,4 +97,4 @@ class ThreadRestrictions { } // namespace base -#endif // BASE_THREAD_RESTRICTIONS_H_ +#endif // BASE_THREADING_THREAD_RESTRICTIONS_H_ diff --git a/base/thread_unittest.cc b/base/threading/thread_unittest.cc index 6b72b83..3748fc3 100644 --- a/base/thread_unittest.cc +++ b/base/threading/thread_unittest.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/thread.h" +#include "base/threading/thread.h" #include <vector> @@ -35,7 +35,7 @@ class SleepSome : public Task { explicit SleepSome(int msec) : msec_(msec) { } virtual void Run() { - PlatformThread::Sleep(msec_); + base::PlatformThread::Sleep(msec_); } private: int msec_; @@ -47,7 +47,7 @@ class SleepInsideInitThread : public Thread { virtual ~SleepInsideInitThread() { } virtual void Init() { - PlatformThread::Sleep(500); + base::PlatformThread::Sleep(500); init_called_ = true; } bool InitCalled() { return init_called_; } @@ -178,7 +178,7 @@ TEST_F(ThreadTest, StartWithOptions_StackSize) { // instead to avoid busy waiting, but this is sufficient for // testing purposes). for (int i = 100; i >= 0 && !was_invoked; --i) { - PlatformThread::Sleep(10); + base::PlatformThread::Sleep(10); } EXPECT_TRUE(was_invoked); } diff --git a/base/watchdog.cc b/base/threading/watchdog.cc index f9326e1..cd21578 100644 --- a/base/watchdog.cc +++ b/base/threading/watchdog.cc @@ -2,17 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/watchdog.h" +#include "base/threading/watchdog.h" #include "base/compiler_specific.h" #include "base/logging.h" -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" -using base::TimeDelta; -using base::TimeTicks; - -//------------------------------------------------------------------------------ -// Public API methods. +namespace base { // Start thread running in a Disarmed state. Watchdog::Watchdog(const TimeDelta& duration, @@ -144,3 +140,5 @@ Lock Watchdog::static_lock_; // Lock for access of static data... TimeTicks Watchdog::last_debugged_alarm_time_ = TimeTicks(); // static TimeDelta Watchdog::last_debugged_alarm_delay_; + +} // namespace base diff --git a/base/watchdog.h b/base/threading/watchdog.h index b4262d4..4af45dc 100644 --- a/base/watchdog.h +++ b/base/threading/watchdog.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. @@ -15,29 +15,31 @@ // a second thread, and their methods call (Arm() and Disarm()) return very // quickly. -#ifndef BASE_WATCHDOG_H__ -#define BASE_WATCHDOG_H__ +#ifndef BASE_THREADING_WATCHDOG_H_ +#define BASE_THREADING_WATCHDOG_H_ #pragma once #include <string> -#include "base/condition_variable.h" -#include "base/lock.h" -#include "base/platform_thread.h" +#include "base/synchronization/condition_variable.h" +#include "base/synchronization/lock.h" +#include "base/threading/platform_thread.h" #include "base/time.h" +namespace base { + class Watchdog { public: // Constructor specifies how long the Watchdog will wait before alarming. - Watchdog(const base::TimeDelta& duration, + Watchdog(const TimeDelta& duration, const std::string& thread_watched_name, bool enabled); virtual ~Watchdog(); // Start timing, and alarm when time expires (unless we're disarm()ed.) void Arm(); // Arm starting now. - void ArmSomeTimeDeltaAgo(const base::TimeDelta& time_delta); - void ArmAtStartTime(const base::TimeTicks start_time); + void ArmSomeTimeDeltaAgo(const TimeDelta& time_delta); + void ArmAtStartTime(const TimeTicks start_time); // Reset time, and do not set off the alarm. void Disarm(); @@ -57,9 +59,9 @@ class Watchdog { } virtual void ThreadMain(); private: - Watchdog* watchdog_; - void SetThreadName() const; + + Watchdog* watchdog_; }; enum State {ARMED, DISARMED, SHUTDOWN }; @@ -69,12 +71,12 @@ class Watchdog { Lock lock_; // Mutex for state_. ConditionVariable condition_variable_; State state_; - const base::TimeDelta duration_; // How long after start_time_ do we alarm? + const TimeDelta duration_; // How long after start_time_ do we alarm? const std::string thread_watched_name_; PlatformThreadHandle handle_; ThreadDelegate delegate_; // Store it, because it must outlive the thread. - base::TimeTicks start_time_; // Start of epoch, and alarm after duration_. + TimeTicks start_time_; // Start of epoch, and alarm after duration_. // When the debugger breaks (when we alarm), all the other alarms that are // armed will expire (also alarm). To diminish this effect, we track any @@ -84,11 +86,13 @@ class Watchdog { // on alarms from callers that specify old times. static Lock static_lock_; // Lock for access of static data... // When did we last alarm and get stuck (for a while) in a debugger? - static base::TimeTicks last_debugged_alarm_time_; + static TimeTicks last_debugged_alarm_time_; // How long did we sit on a break in the debugger? - static base::TimeDelta last_debugged_alarm_delay_; + static TimeDelta last_debugged_alarm_delay_; DISALLOW_COPY_AND_ASSIGN(Watchdog); }; -#endif // BASE_WATCHDOG_H__ +} // namespace base + +#endif // BASE_THREADING_WATCHDOG_H_ diff --git a/base/watchdog_unittest.cc b/base/threading/watchdog_unittest.cc index 658a31a..f96487b 100644 --- a/base/watchdog_unittest.cc +++ b/base/threading/watchdog_unittest.cc @@ -2,18 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// Tests for Watchdog class. - -#include "base/watchdog.h" +#include "base/threading/watchdog.h" #include "base/logging.h" -#include "base/platform_thread.h" #include "base/spin_wait.h" +#include "base/threading/platform_thread.h" #include "base/time.h" #include "testing/gtest/include/gtest/gtest.h" -using base::TimeDelta; -using base::TimeTicks; +namespace base { namespace { @@ -50,6 +47,7 @@ class WatchdogTest : public testing::Test { } }; +} // namespace //------------------------------------------------------------------------------ // Actual tests @@ -139,4 +137,4 @@ TEST_F(WatchdogTest, DisarmTest) { EXPECT_EQ(1, watchdog.alarm_counter()); } -} // namespace +} // namespace base diff --git a/base/worker_pool.h b/base/threading/worker_pool.h index e0b75a9..9a02acc 100644 --- a/base/worker_pool.h +++ b/base/threading/worker_pool.h @@ -1,15 +1,17 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_WORKER_POOL_H_ -#define BASE_WORKER_POOL_H_ +#ifndef BASE_THREADING_WORKER_POOL_H_ +#define BASE_THREADING_WORKER_POOL_H_ #pragma once #include "base/tracked.h" class Task; +namespace base { + // This is a facility that runs tasks that don't require a specific thread or // a message loop. // @@ -28,4 +30,6 @@ class WorkerPool { Task* task, bool task_is_slow); }; -#endif // BASE_WORKER_POOL_H_ +} // namespace base + +#endif // BASE_THREADING_WORKER_POOL_H_ diff --git a/base/worker_pool_posix.cc b/base/threading/worker_pool_posix.cc index 85e1d8e..8466403 100644 --- a/base/worker_pool_posix.cc +++ b/base/threading/worker_pool_posix.cc @@ -2,15 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/worker_pool.h" -#include "base/worker_pool_posix.h" +#include "base/threading/worker_pool_posix.h" #include "base/lazy_instance.h" #include "base/logging.h" -#include "base/platform_thread.h" #include "base/ref_counted.h" #include "base/stringprintf.h" #include "base/task.h" +#include "base/threading/platform_thread.h" +#include "base/threading/worker_pool.h" + +namespace base { namespace { @@ -32,8 +34,9 @@ class WorkerPoolImpl { }; WorkerPoolImpl::WorkerPoolImpl() - : pool_(new base::PosixDynamicThreadPool( - "WorkerPool", kIdleSecondsBeforeExit)) {} + : pool_(new base::PosixDynamicThreadPool("WorkerPool", + kIdleSecondsBeforeExit)) { +} WorkerPoolImpl::~WorkerPoolImpl() { pool_->Terminate(); @@ -90,8 +93,6 @@ bool WorkerPool::PostTask(const tracked_objects::Location& from_here, return true; } -namespace base { - PosixDynamicThreadPool::PosixDynamicThreadPool( const std::string& name_prefix, int idle_seconds_before_exit) diff --git a/base/worker_pool_posix.h b/base/threading/worker_pool_posix.h index 73d8287..1b68aef 100644 --- a/base/worker_pool_posix.h +++ b/base/threading/worker_pool_posix.h @@ -1,4 +1,4 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // @@ -21,19 +21,19 @@ // implementation of WorkerPool. No one else should be using these classes. // These symbols are exported in a header purely for testing purposes. -#ifndef BASE_WORKER_POOL_POSIX_H_ -#define BASE_WORKER_POOL_POSIX_H_ +#ifndef BASE_THREADING_WORKER_POOL_POSIX_H_ +#define BASE_THREADING_WORKER_POOL_POSIX_H_ #pragma once #include <queue> #include <string> #include "base/basictypes.h" -#include "base/condition_variable.h" -#include "base/lock.h" -#include "base/platform_thread.h" #include "base/ref_counted.h" #include "base/scoped_ptr.h" +#include "base/synchronization/condition_variable.h" +#include "base/synchronization/lock.h" +#include "base/threading/platform_thread.h" class Task; @@ -86,4 +86,4 @@ class PosixDynamicThreadPool } // namespace base -#endif // BASE_WORKER_POOL_POSIX_H_ +#endif // BASE_THREADING_WORKER_POOL_POSIX_H_ diff --git a/base/worker_pool_posix_unittest.cc b/base/threading/worker_pool_posix_unittest.cc index 55453c8..332c55e 100644 --- a/base/worker_pool_posix_unittest.cc +++ b/base/threading/worker_pool_posix_unittest.cc @@ -1,16 +1,16 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/worker_pool_posix.h" +#include "base/threading/worker_pool_posix.h" #include <set> -#include "base/condition_variable.h" #include "base/lock.h" -#include "base/platform_thread.h" +#include "base/synchronization/condition_variable.h" #include "base/task.h" -#include "base/waitable_event.h" +#include "base/threading/platform_thread.h" +#include "base/synchronization/waitable_event.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { @@ -40,8 +40,6 @@ class PosixDynamicThreadPool::PosixDynamicThreadPoolPeer { DISALLOW_COPY_AND_ASSIGN(PosixDynamicThreadPoolPeer); }; -} // namespace base - namespace { // IncrementingTask's main purpose is to increment a counter. It also updates a @@ -177,6 +175,8 @@ class PosixDynamicThreadPoolTest : public testing::Test { base::WaitableEvent start_; }; +} // namespace + TEST_F(PosixDynamicThreadPoolTest, Basic) { EXPECT_EQ(0, peer_.num_idle_threads()); EXPECT_EQ(0U, unique_threads_.size()); @@ -265,4 +265,4 @@ TEST_F(PosixDynamicThreadPoolTest, Complex) { EXPECT_EQ(4, counter_); } -} // namespace +} // namespace base diff --git a/base/worker_pool_unittest.cc b/base/threading/worker_pool_unittest.cc index f6bee96..f044e10 100644 --- a/base/worker_pool_unittest.cc +++ b/base/threading/worker_pool_unittest.cc @@ -3,15 +3,15 @@ // found in the LICENSE file. #include "base/task.h" -#include "base/waitable_event.h" -#include "base/worker_pool.h" +#include "base/synchronization/waitable_event.h" +#include "base/threading/worker_pool.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" -using base::WaitableEvent; - typedef PlatformTest WorkerPoolTest; +namespace base { + namespace { class PostTaskTestTask : public Task { @@ -27,6 +27,8 @@ class PostTaskTestTask : public Task { WaitableEvent* event_; }; +} // namespace + TEST_F(WorkerPoolTest, PostTask) { WaitableEvent test_event(false, false); WaitableEvent long_test_event(false, false); @@ -41,4 +43,4 @@ TEST_F(WorkerPoolTest, PostTask) { EXPECT_TRUE(signaled); } -} // namespace +} // namespace base diff --git a/base/worker_pool_win.cc b/base/threading/worker_pool_win.cc index 3f383b9..2072e52 100644 --- a/base/worker_pool_win.cc +++ b/base/threading/worker_pool_win.cc @@ -1,12 +1,14 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/worker_pool.h" +#include "base/threading/worker_pool.h" #include "base/logging.h" #include "base/task.h" +namespace base { + namespace { DWORD CALLBACK WorkItemCallback(void* param) { @@ -34,3 +36,5 @@ bool WorkerPool::PostTask(const tracked_objects::Location& from_here, return true; } + +} // namespace base diff --git a/base/time.h b/base/time.h index 79e30b4..e1fbf96 100644 --- a/base/time.h +++ b/base/time.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -385,6 +385,9 @@ class Time { private: friend class TimeDelta; + explicit Time(int64 us) : us_(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; @@ -393,9 +396,6 @@ class Time { // |is_local = true| or UTC |is_local = false|. static Time FromExploded(bool is_local, const Exploded& exploded); - explicit Time(int64 us) : us_(us) { - } - // The representation of Jan 1, 1970 UTC in microseconds since the // platform-dependent epoch. static const int64 kTimeTToMicrosecondsOffset; diff --git a/base/time_unittest.cc b/base/time_unittest.cc index 6ddf4d3..6c64b48 100644 --- a/base/time_unittest.cc +++ b/base/time_unittest.cc @@ -1,10 +1,10 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <time.h> -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" #include "base/time.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" @@ -106,7 +106,7 @@ TEST(Time, LocalMidnight) { TEST(TimeTicks, Deltas) { for (int index = 0; index < 50; index++) { TimeTicks ticks_start = TimeTicks::Now(); - PlatformThread::Sleep(10); + base::PlatformThread::Sleep(10); TimeTicks ticks_stop = TimeTicks::Now(); TimeDelta delta = ticks_stop - ticks_start; // Note: Although we asked for a 10ms sleep, if the diff --git a/base/time_win_unittest.cc b/base/time_win_unittest.cc index 4389e7a..3a96b91 100644 --- a/base/time_win_unittest.cc +++ b/base/time_win_unittest.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -6,7 +6,7 @@ #include <mmsystem.h> #include <process.h> -#include "base/platform_thread.h" +#include "base/threading/platform_thread.h" #include "base/time.h" #include "testing/gtest/include/gtest/gtest.h" @@ -220,7 +220,7 @@ TEST(TimeTicks, Drift) { // Sleep for a few milliseconds (note that it means 1000 microseconds). // If we check the drift too frequently, it's going to increase // monotonically, making our measurement less realistic. - PlatformThread::Sleep((i % 2 == 0) ? 1 : 2); + base::PlatformThread::Sleep((i % 2 == 0) ? 1 : 2); total_drift += drift_microseconds; } diff --git a/base/timer_unittest.cc b/base/timer_unittest.cc index 6453672..c2289c8 100644 --- a/base/timer_unittest.cc +++ b/base/timer_unittest.cc @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -267,7 +267,7 @@ void RunTest_DelayTimer_Deleted(MessageLoop::Type message_loop_type) { // When the timer is deleted, the DelayTimerFatalTarget should never be // called. - PlatformThread::Sleep(100); + base::PlatformThread::Sleep(100); } } // namespace diff --git a/base/tools_sanity_unittest.cc b/base/tools_sanity_unittest.cc index 2824836..779c236 100644 --- a/base/tools_sanity_unittest.cc +++ b/base/tools_sanity_unittest.cc @@ -1,12 +1,14 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" -#include "base/thread.h" +#include "base/threading/thread.h" #include "testing/gtest/include/gtest/gtest.h" +namespace base { + namespace { // We use caps here just to ensure that the method name doesn't interfere with @@ -136,3 +138,5 @@ TEST(ToolsSanityTest, DataRace) { delete thread1; delete thread2; } + +} // namespace base diff --git a/base/tracked_objects.cc b/base/tracked_objects.cc index 9db25ff..3646000 100644 --- a/base/tracked_objects.cc +++ b/base/tracked_objects.cc @@ -10,7 +10,7 @@ #include "base/message_loop.h" #include "base/string_util.h" #include "base/stringprintf.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" using base::TimeDelta; @@ -18,7 +18,7 @@ namespace tracked_objects { // A TLS slot to the TrackRegistry for the current thread. // static -TLSSlot ThreadData::tls_index_(base::LINKER_INITIALIZED); +base::ThreadLocalStorage::Slot ThreadData::tls_index_(base::LINKER_INITIALIZED); // A global state variable to prevent repeated initialization during tests. // static diff --git a/base/tracked_objects.h b/base/tracked_objects.h index 8590a8c..07731ff 100644 --- a/base/tracked_objects.h +++ b/base/tracked_objects.h @@ -1,4 +1,4 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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. @@ -11,8 +11,8 @@ #include <vector> #include "base/lock.h" -#include "base/thread_local_storage.h" #include "base/tracked.h" +#include "base/threading/thread_local_storage.h" // TrackedObjects provides a database of stats about objects (generally Tasks) // that are tracked. Tracking means their birth, death, duration, birth thread, @@ -307,6 +307,8 @@ class DataCollector { void AddListOfLivingObjects(); private: + typedef std::map<const BirthOnThread*, int> BirthCount; + // This instance may be provided to several threads to contribute data. The // following counter tracks how many more threads will contribute. When it is // zero, then all asynchronous contributions are complete, and locked access @@ -318,7 +320,6 @@ class DataCollector { // The total number of births recorded at each location for which we have not // seen a death count. - typedef std::map<const BirthOnThread*, int> BirthCount; BirthCount global_birth_count_; Lock accumulation_lock_; // Protects access during accumulation phase. @@ -571,7 +572,7 @@ class ThreadData { static void ShutdownDisablingFurtherTracking(); // We use thread local store to identify which ThreadData to interact with. - static TLSSlot tls_index_; + static base::ThreadLocalStorage::Slot tls_index_; // Link to the most recently created instance (starts a null terminated list). static ThreadData* first_; diff --git a/base/values.cc b/base/values.cc index 4553e68..3522569 100644 --- a/base/values.cc +++ b/base/values.cc @@ -263,6 +263,12 @@ bool StringValue::Equals(const Value* other) const { ///////////////////// BinaryValue //////////////////// +BinaryValue::~BinaryValue() { + DCHECK(buffer_); + if (buffer_) + delete[] buffer_; +} + // static BinaryValue* BinaryValue::Create(char* buffer, size_t size) { if (!buffer) @@ -282,20 +288,6 @@ BinaryValue* BinaryValue::CreateWithCopiedBuffer(const char* buffer, return new BinaryValue(buffer_copy, size); } - -BinaryValue::BinaryValue(char* buffer, size_t size) - : Value(TYPE_BINARY), - buffer_(buffer), - size_(size) { - DCHECK(buffer_); -} - -BinaryValue::~BinaryValue() { - DCHECK(buffer_); - if (buffer_) - delete[] buffer_; -} - Value* BinaryValue::DeepCopy() const { return CreateWithCopiedBuffer(buffer_, size_); } @@ -309,6 +301,13 @@ bool BinaryValue::Equals(const Value* other) const { return !memcmp(buffer_, other_binary->buffer_, size_); } +BinaryValue::BinaryValue(char* buffer, size_t size) + : Value(TYPE_BINARY), + buffer_(buffer), + size_(size) { + DCHECK(buffer_); +} + ///////////////////// DictionaryValue //////////////////// DictionaryValue::DictionaryValue() @@ -319,44 +318,6 @@ DictionaryValue::~DictionaryValue() { Clear(); } -Value* DictionaryValue::DeepCopy() const { - DictionaryValue* result = new DictionaryValue; - - for (ValueMap::const_iterator current_entry(dictionary_.begin()); - current_entry != dictionary_.end(); ++current_entry) { - result->SetWithoutPathExpansion(current_entry->first, - current_entry->second->DeepCopy()); - } - - return result; -} - -bool DictionaryValue::Equals(const Value* other) const { - if (other->GetType() != GetType()) - return false; - - const DictionaryValue* other_dict = - static_cast<const DictionaryValue*>(other); - key_iterator lhs_it(begin_keys()); - key_iterator rhs_it(other_dict->begin_keys()); - while (lhs_it != end_keys() && rhs_it != other_dict->end_keys()) { - Value* lhs; - Value* rhs; - if (*lhs_it != *rhs_it || - !GetWithoutPathExpansion(*lhs_it, &lhs) || - !other_dict->GetWithoutPathExpansion(*rhs_it, &rhs) || - !lhs->Equals(rhs)) { - return false; - } - ++lhs_it; - ++rhs_it; - } - if (lhs_it != end_keys() || rhs_it != other_dict->end_keys()) - return false; - - return true; -} - bool DictionaryValue::HasKey(const std::string& key) const { DCHECK(IsStringUTF8(key)); ValueMap::const_iterator current_entry = dictionary_.find(key); @@ -685,6 +646,44 @@ void DictionaryValue::MergeDictionary(const DictionaryValue* dictionary) { } } +Value* DictionaryValue::DeepCopy() const { + DictionaryValue* result = new DictionaryValue; + + for (ValueMap::const_iterator current_entry(dictionary_.begin()); + current_entry != dictionary_.end(); ++current_entry) { + result->SetWithoutPathExpansion(current_entry->first, + current_entry->second->DeepCopy()); + } + + return result; +} + +bool DictionaryValue::Equals(const Value* other) const { + if (other->GetType() != GetType()) + return false; + + const DictionaryValue* other_dict = + static_cast<const DictionaryValue*>(other); + key_iterator lhs_it(begin_keys()); + key_iterator rhs_it(other_dict->begin_keys()); + while (lhs_it != end_keys() && rhs_it != other_dict->end_keys()) { + Value* lhs; + Value* rhs; + if (*lhs_it != *rhs_it || + !GetWithoutPathExpansion(*lhs_it, &lhs) || + !other_dict->GetWithoutPathExpansion(*rhs_it, &rhs) || + !lhs->Equals(rhs)) { + return false; + } + ++lhs_it; + ++rhs_it; + } + if (lhs_it != end_keys() || rhs_it != other_dict->end_keys()) + return false; + + return true; +} + ///////////////////// ListValue //////////////////// ListValue::ListValue() : Value(TYPE_LIST) { diff --git a/base/values.h b/base/values.h index 2719d27..d69a685 100644 --- a/base/values.h +++ b/base/values.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. @@ -46,6 +46,17 @@ typedef std::map<std::string, Value*> ValueMap; // creating instances of the subclasses. class Value { public: + enum ValueType { + TYPE_NULL = 0, + TYPE_BOOLEAN, + TYPE_INTEGER, + TYPE_REAL, + TYPE_STRING, + TYPE_BINARY, + TYPE_DICTIONARY, + TYPE_LIST + }; + virtual ~Value(); // Convenience methods for creating Value objects for various @@ -62,17 +73,6 @@ class Value { // is non-null, the new object has taken ownership of the buffer pointer. static BinaryValue* CreateBinaryValue(char* buffer, size_t size); - typedef enum { - TYPE_NULL = 0, - TYPE_BOOLEAN, - TYPE_INTEGER, - TYPE_REAL, - TYPE_STRING, - TYPE_BINARY, - TYPE_DICTIONARY, - TYPE_LIST - } ValueType; - // Returns the type of the value stored by the current Value object. // Each type will be implemented by only one subclass of Value, so it's // safe to use the ValueType to determine whether you can cast from @@ -167,6 +167,8 @@ class StringValue : public Value { class BinaryValue: public Value { public: + virtual ~BinaryValue(); + // Creates a Value to represent a binary buffer. The new object takes // ownership of the pointer passed in, if successful. // Returns NULL if buffer is NULL. @@ -178,16 +180,14 @@ class BinaryValue: public Value { // Returns NULL if buffer is NULL. static BinaryValue* CreateWithCopiedBuffer(const char* buffer, size_t size); - virtual ~BinaryValue(); - - // Subclassed methods - virtual Value* DeepCopy() const; - virtual bool Equals(const Value* other) const; - size_t GetSize() const { return size_; } char* GetBuffer() { return buffer_; } const char* GetBuffer() const { return buffer_; } + // Overridden from Value: + virtual Value* DeepCopy() const; + virtual bool Equals(const Value* other) const; + private: // Constructor is private so that only objects with valid buffer pointers // and size values can be created. @@ -207,10 +207,6 @@ class DictionaryValue : public Value { DictionaryValue(); virtual ~DictionaryValue(); - // Subclassed methods - virtual Value* DeepCopy() const; - virtual bool Equals(const Value* other) const; - // Returns true if the current dictionary has a value for the given key. bool HasKey(const std::string& key) const; @@ -333,6 +329,10 @@ class DictionaryValue : public Value { key_iterator begin_keys() const { return key_iterator(dictionary_.begin()); } key_iterator end_keys() const { return key_iterator(dictionary_.end()); } + // Overridden from Value: + virtual Value* DeepCopy() const; + virtual bool Equals(const Value* other) const; + private: ValueMap dictionary_; @@ -342,14 +342,12 @@ class DictionaryValue : public Value { // This type of Value represents a list of other Value values. class ListValue : public Value { public: + typedef ValueVector::iterator iterator; + typedef ValueVector::const_iterator const_iterator; + ListValue(); ~ListValue(); - // Subclassed methods - virtual bool GetAsList(ListValue** out_value); - virtual Value* DeepCopy() const; - virtual bool Equals(const Value* other) const; - // Clears the contents of this ListValue void Clear(); @@ -411,15 +409,17 @@ class ListValue : public Value { } // Iteration - typedef ValueVector::iterator iterator; - typedef ValueVector::const_iterator const_iterator; - ListValue::iterator begin() { return list_.begin(); } ListValue::iterator end() { return list_.end(); } ListValue::const_iterator begin() const { return list_.begin(); } ListValue::const_iterator end() const { return list_.end(); } + // Overridden from Value: + virtual bool GetAsList(ListValue** out_value); + virtual Value* DeepCopy() const; + virtual bool Equals(const Value* other) const; + private: ValueVector list_; diff --git a/base/version.cc b/base/version.cc index 384be0a..571672c 100644 --- a/base/version.cc +++ b/base/version.cc @@ -12,6 +12,10 @@ #include "base/string_util.h" #include "base/utf_string_conversions.h" +Version::Version() : is_valid_(false) {} + +Version::~Version() {} + // static Version* Version::GetVersionFromString(const std::string& version_str) { Version* vers = new Version(); @@ -23,10 +27,6 @@ Version* Version::GetVersionFromString(const std::string& version_str) { return NULL; } -Version::Version() : is_valid_(false) {} - -Version::~Version() {} - Version* Version::Clone() const { DCHECK(is_valid_); Version* copy = new Version(); diff --git a/base/version.h b/base/version.h index 2fda4ad..28ee227 100644 --- a/base/version.h +++ b/base/version.h @@ -1,4 +1,4 @@ -// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// 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. @@ -17,11 +17,6 @@ // Each component is limited to a uint16. class Version { public: - // The version string must be made up of 1 or more uint16's separated - // by '.'. Returns NULL if string is not in this format. - // Caller is responsible for freeing the Version object once done. - static Version* GetVersionFromString(const std::string& version_str); - // Exposed only so that a Version can be stored in STL containers; // any call to the methods below on a default-constructed Version // will DCHECK. @@ -29,6 +24,11 @@ class Version { ~Version(); + // The version string must be made up of 1 or more uint16's separated + // by '.'. Returns NULL if string is not in this format. + // Caller is responsible for freeing the Version object once done. + static Version* GetVersionFromString(const std::string& version_str); + // Creates a copy of this version. Caller takes ownership. Version* Clone() const; diff --git a/base/weak_ptr.h b/base/weak_ptr.h index ed9ef66..6168367 100644 --- a/base/weak_ptr.h +++ b/base/weak_ptr.h @@ -53,8 +53,8 @@ #pragma once #include "base/logging.h" -#include "base/non_thread_safe.h" #include "base/ref_counted.h" +#include "base/threading/non_thread_safe.h" namespace base { @@ -64,7 +64,7 @@ namespace internal { class WeakReference { public: - class Flag : public RefCounted<Flag>, public NonThreadSafe { + class Flag : public RefCounted<Flag>, public base::NonThreadSafe { public: Flag(Flag** handle); ~Flag(); @@ -74,7 +74,7 @@ class WeakReference { void Invalidate() { handle_ = NULL; } bool is_valid() const { return handle_ != NULL; } - void DetachFromThread() { NonThreadSafe::DetachFromThread(); } + void DetachFromThread() { base::NonThreadSafe::DetachFromThread(); } private: Flag** handle_; diff --git a/base/weak_ptr_unittest.cc b/base/weak_ptr_unittest.cc index b808401..bcaca9e 100644 --- a/base/weak_ptr_unittest.cc +++ b/base/weak_ptr_unittest.cc @@ -4,7 +4,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "base/message_loop.h" -#include "base/thread.h" +#include "base/threading/thread.h" #include "base/scoped_ptr.h" #include "base/weak_ptr.h" diff --git a/base/win/event_trace_consumer_unittest.cc b/base/win/event_trace_consumer_unittest.cc index f11f459..efbfdf9 100644 --- a/base/win/event_trace_consumer_unittest.cc +++ b/base/win/event_trace_consumer_unittest.cc @@ -4,14 +4,16 @@ // // Unit tests for event trace consumer_ base class. #include "base/win/event_trace_consumer.h" + #include <list> + #include "base/basictypes.h" -#include "base/win/event_trace_controller.h" -#include "base/win/event_trace_provider.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" -#include "base/scoped_handle.h" +#include "base/win/event_trace_controller.h" +#include "base/win/event_trace_provider.h" +#include "base/win/scoped_handle.h" #include "testing/gtest/include/gtest/gtest.h" #include <initguid.h> // NOLINT - has to be last @@ -63,14 +65,14 @@ class TestConsumer: public EtwTraceConsumerBase<TestConsumer> { ::SetEvent(sank_event_.Get()); } - static ScopedHandle sank_event_; + static base::win::ScopedHandle sank_event_; static EventQueue events_; private: DISALLOW_COPY_AND_ASSIGN(TestConsumer); }; -ScopedHandle TestConsumer::sank_event_; +base::win::ScopedHandle TestConsumer::sank_event_; EventQueue TestConsumer::events_; const wchar_t* const kTestSessionName = L"TestLogSession"; @@ -175,8 +177,8 @@ class EtwTraceConsumerRealtimeTest: public testing::Test { } TestConsumer consumer_; - ScopedHandle consumer_ready_; - ScopedHandle consumer_thread_; + base::win::ScopedHandle consumer_ready_; + base::win::ScopedHandle consumer_thread_; }; } // namespace diff --git a/base/win/event_trace_controller_unittest.cc b/base/win/event_trace_controller_unittest.cc index 2b3cd66..8eab40a 100644 --- a/base/win/event_trace_controller_unittest.cc +++ b/base/win/event_trace_controller_unittest.cc @@ -1,17 +1,19 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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. // // Unit tests for event trace controller. -#include "base/win/event_trace_controller.h" -#include "base/win/event_trace_provider.h" + +#include <initguid.h> // NOLINT. + #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" -#include "base/scoped_handle.h" #include "base/sys_info.h" +#include "base/win/event_trace_controller.h" +#include "base/win/event_trace_provider.h" +#include "base/win/scoped_handle.h" #include "testing/gtest/include/gtest/gtest.h" -#include <initguid.h> // NOLINT - must be last. namespace { @@ -50,7 +52,7 @@ class TestingProvider: public EtwTraceProvider { ::SetEvent(callback_event_.Get()); } - ScopedHandle callback_event_; + base::win::ScopedHandle callback_event_; DISALLOW_COPY_AND_ASSIGN(TestingProvider); }; diff --git a/base/object_watcher.cc b/base/win/object_watcher.cc index a15234b..4f5e7ab 100644 --- a/base/object_watcher.cc +++ b/base/win/object_watcher.cc @@ -1,12 +1,13 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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/object_watcher.h" +#include "base/win/object_watcher.h" #include "base/logging.h" namespace base { +namespace win { //----------------------------------------------------------------------------- @@ -135,4 +136,5 @@ void ObjectWatcher::WillDestroyCurrentMessageLoop() { StopWatching(); } +} // namespace win } // namespace base diff --git a/base/object_watcher.h b/base/win/object_watcher.h index e05ceac..16534c2 100644 --- a/base/object_watcher.h +++ b/base/win/object_watcher.h @@ -1,9 +1,9 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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_OBJECT_WATCHER_H_ -#define BASE_OBJECT_WATCHER_H_ +#ifndef BASE_WIN_OBJECT_WATCHER_H_ +#define BASE_WIN_OBJECT_WATCHER_H_ #pragma once #include <windows.h> @@ -11,6 +11,7 @@ #include "base/message_loop.h" namespace base { +namespace win { // A class that provides a means to asynchronously wait for a Windows object to // become signaled. It is an abstraction around RegisterWaitForSingleObject @@ -87,6 +88,7 @@ class ObjectWatcher : public MessageLoop::DestructionObserver { DISALLOW_COPY_AND_ASSIGN(ObjectWatcher); }; +} // namespace win } // namespace base #endif // BASE_OBJECT_WATCHER_H_ diff --git a/base/object_watcher_unittest.cc b/base/win/object_watcher_unittest.cc index 3605dbb..fe151d9 100644 --- a/base/object_watcher_unittest.cc +++ b/base/win/object_watcher_unittest.cc @@ -1,23 +1,26 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// 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 <process.h> #include "base/message_loop.h" -#include "base/object_watcher.h" +#include "base/win/object_watcher.h" #include "testing/gtest/include/gtest/gtest.h" +namespace base { +namespace win { + namespace { -class QuitDelegate : public base::ObjectWatcher::Delegate { +class QuitDelegate : public ObjectWatcher::Delegate { public: virtual void OnObjectSignaled(HANDLE object) { MessageLoop::current()->Quit(); } }; -class DecrementCountDelegate : public base::ObjectWatcher::Delegate { +class DecrementCountDelegate : public ObjectWatcher::Delegate { public: explicit DecrementCountDelegate(int* counter) : counter_(counter) { } @@ -28,12 +31,10 @@ class DecrementCountDelegate : public base::ObjectWatcher::Delegate { int* counter_; }; -} // namespace - void RunTest_BasicSignal(MessageLoop::Type message_loop_type) { MessageLoop message_loop(message_loop_type); - base::ObjectWatcher watcher; + ObjectWatcher watcher; EXPECT_EQ(NULL, watcher.GetWatchedObject()); // A manual-reset event that is not yet signaled. @@ -55,7 +56,7 @@ void RunTest_BasicSignal(MessageLoop::Type message_loop_type) { void RunTest_BasicCancel(MessageLoop::Type message_loop_type) { MessageLoop message_loop(message_loop_type); - base::ObjectWatcher watcher; + ObjectWatcher watcher; // A manual-reset event that is not yet signaled. HANDLE event = CreateEvent(NULL, TRUE, FALSE, NULL); @@ -73,7 +74,7 @@ void RunTest_BasicCancel(MessageLoop::Type message_loop_type) { void RunTest_CancelAfterSet(MessageLoop::Type message_loop_type) { MessageLoop message_loop(message_loop_type); - base::ObjectWatcher watcher; + ObjectWatcher watcher; int counter = 1; DecrementCountDelegate delegate(&counter); @@ -105,7 +106,7 @@ void RunTest_OutlivesMessageLoop(MessageLoop::Type message_loop_type) { // people use the Singleton pattern or atexit. HANDLE event = CreateEvent(NULL, TRUE, FALSE, NULL); // not signaled { - base::ObjectWatcher watcher; + ObjectWatcher watcher; { MessageLoop message_loop(message_loop_type); @@ -116,6 +117,8 @@ void RunTest_OutlivesMessageLoop(MessageLoop::Type message_loop_type) { CloseHandle(event); } +} // namespace + //----------------------------------------------------------------------------- TEST(ObjectWatcherTest, BasicSignal) { @@ -141,3 +144,6 @@ TEST(ObjectWatcherTest, OutlivesMessageLoop) { RunTest_OutlivesMessageLoop(MessageLoop::TYPE_IO); RunTest_OutlivesMessageLoop(MessageLoop::TYPE_UI); } + +} // namespace win +} // namespace base diff --git a/base/win/registry.cc b/base/win/registry.cc index f8e05a7..dbb8d7a 100644 --- a/base/win/registry.cc +++ b/base/win/registry.cc @@ -7,7 +7,7 @@ #include <shlwapi.h> #include "base/logging.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" #pragma comment(lib, "shlwapi.lib") // for SHDeleteKey diff --git a/base/win/rgs_helper.h b/base/win/rgs_helper.h deleted file mode 100644 index 16e33bf..0000000 --- a/base/win/rgs_helper.h +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// Defines a map for adding variables to rgs files. This allows COM object -// classes to declare the values of these variables so that we don't need to -// copy/paste them and manually keep them in sync. -// To use this, declare the registry ID of your RGS file using -// the DECLARE_REGISTRY_RESOURCEID_EX macro, instead of the -// DECLARE_REGISTRY_RESOURCEID, then add a registry map to your class -// using the registry map macros: -// BEGIN_REGISTRY_MAP(MyClassName) -// REGMAP_ENTRY("NAME", "MyClassName Class") -// REGMAP_ENTRY_UUID("CLSID", CLSID_MyClassName) -// END_REGISTRY_MAP() -// -// You can then refer to the names above in your RGS file as -// variables %NAME% and %CLSID%, respectively. -#ifndef BASE_WIN_RGS_HELPER_H_ -#define BASE_WIN_RGS_HELPER_H_ - -#include "base/string_util.h" - -struct ATLRegmapEntryHelper : public _ATL_REGMAP_ENTRY { - ATLRegmapEntryHelper() { - szKey = NULL; - szData = NULL; - } - ATLRegmapEntryHelper(LPCOLESTR key, LPCOLESTR data) { - szKey = key; - size_t size = lstrlen(data) + 1; - szData = new wchar_t[size]; - base::wcslcpy(const_cast<wchar_t*>(szData), data, size); - } - - ATLRegmapEntryHelper(LPCOLESTR key, UINT resid) { - wchar_t data[256] = {0}; - szKey = key; - if (::LoadString(_pModule->m_hInstResource, resid, data, - arraysize(data) - 1) == 0) { - *data = L'\0'; - } - - size_t size = lstrlen(data) + 1; - - szData = new wchar_t[size]; - base::wcslcpy(const_cast<wchar_t*>(szData), data, size); - } - - ATLRegmapEntryHelper(LPCOLESTR key, REFGUID guid) { - szKey = key; - static const size_t kGuidStringSize = 40; - szData = new wchar_t[kGuidStringSize]; - if (szData) { - if (::StringFromGUID2(guid, const_cast<LPOLESTR>(szData), - kGuidStringSize) == 0) { - *const_cast<LPOLESTR>(szData) = L'\0'; - } - } - } - ~ATLRegmapEntryHelper() { - delete [] szData; - } -}; - -#define BEGIN_REGISTRY_MAP(x)\ - static struct _ATL_REGMAP_ENTRY *_GetRegistryMap() {\ - static const ATLRegmapEntryHelper map[] = { -#define REGMAP_ENTRY(x, y) ATLRegmapEntryHelper(OLESTR(##x), OLESTR(##y)), - -#define REGMAP_UUID(x, clsid) ATLRegmapEntryHelper(OLESTR(##x), clsid), - -// This allows usage of a Resource string. -#define REGMAP_RESOURCE(x, resid) ATLRegmapEntryHelper(OLESTR(##x), resid), - -// This allows usage of a static function to be called to provide the string. -#define REGMAP_FUNCTION(x, f) ATLRegmapEntryHelper(OLESTR(##x), ##f()), - -#define END_REGISTRY_MAP() ATLRegmapEntryHelper() };\ - return (_ATL_REGMAP_ENTRY*)map;\ - } - -#define DECLARE_REGISTRY_RESOURCEID_EX(x)\ - static HRESULT WINAPI UpdateRegistry(BOOL bRegister) {\ - return ATL::_pAtlModule->UpdateRegistryFromResource((UINT)x, bRegister, \ - _GetRegistryMap());\ - } - -#endif // BASE_WIN_RGS_HELPER_H_ diff --git a/base/win_util.cc b/base/win/win_util.cc index 3fcfb92..87905ea 100644 --- a/base/win_util.cc +++ b/base/win/win_util.cc @@ -1,8 +1,8 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// 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/win_util.h" +#include "base/win/win_util.h" #include <aclapi.h> #include <shobjidl.h> // Must be before propkey. @@ -13,14 +13,15 @@ #include "base/logging.h" #include "base/win/registry.h" -#include "base/scoped_handle.h" #include "base/scoped_ptr.h" #include "base/string_util.h" #include "base/stringprintf.h" -#include "base/thread_restrictions.h" +#include "base/threading/thread_restrictions.h" +#include "base/win/scoped_handle.h" #include "base/win/windows_version.h" -namespace win_util { +namespace base { +namespace win { #define SIZEOF_STRUCT_WITH_SPECIFIED_LAST_MEMBER(struct_name, member) \ offsetof(struct_name, member) + \ @@ -46,7 +47,7 @@ bool GetUserSidString(std::wstring* user_sid) { HANDLE token = NULL; if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token)) return false; - ScopedHandle token_scoped(token); + base::win::ScopedHandle token_scoped(token); DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE; scoped_array<BYTE> user_bytes(new BYTE[size]); @@ -70,30 +71,6 @@ bool GetUserSidString(std::wstring* user_sid) { return true; } -#pragma warning(push) -#pragma warning(disable:4312 4244) -WNDPROC SetWindowProc(HWND hwnd, WNDPROC proc) { - // The reason we don't return the SetwindowLongPtr() value is that it returns - // the orignal window procedure and not the current one. I don't know if it is - // a bug or an intended feature. - WNDPROC oldwindow_proc = - reinterpret_cast<WNDPROC>(GetWindowLongPtr(hwnd, GWLP_WNDPROC)); - SetWindowLongPtr(hwnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(proc)); - return oldwindow_proc; -} - -void* SetWindowUserData(HWND hwnd, void* user_data) { - return - reinterpret_cast<void*>(SetWindowLongPtr(hwnd, GWLP_USERDATA, - reinterpret_cast<LONG_PTR>(user_data))); -} - -void* GetWindowUserData(HWND hwnd) { - return reinterpret_cast<void*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)); -} - -#pragma warning(pop) - bool IsShiftPressed() { return (::GetKeyState(VK_SHIFT) & 0x8000) == 0x8000; } @@ -106,27 +83,6 @@ bool IsAltPressed() { return (::GetKeyState(VK_MENU) & 0x8000) == 0x8000; } -std::wstring GetClassName(HWND window) { - // GetClassNameW will return a truncated result (properly null terminated) if - // the given buffer is not large enough. So, it is not possible to determine - // that we got the entire class name if the result is exactly equal to the - // size of the buffer minus one. - DWORD buffer_size = MAX_PATH; - while (true) { - std::wstring output; - DWORD size_ret = - GetClassNameW(window, WriteInto(&output, buffer_size), buffer_size); - if (size_ret == 0) - break; - if (size_ret < (buffer_size - 1)) { - output.resize(size_ret); - return output; - } - buffer_size *= 2; - } - return std::wstring(); // error -} - bool UserAccountControlIsEnabled() { // This can be slow if Windows ends up going to disk. Should watch this key // for changes and only read it once, preferably on the file thread. @@ -144,28 +100,6 @@ bool UserAccountControlIsEnabled() { return (uac_enabled != 0); } -std::wstring FormatMessage(unsigned messageid) { - wchar_t* string_buffer = NULL; - unsigned string_length = ::FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, NULL, messageid, 0, - reinterpret_cast<wchar_t *>(&string_buffer), 0, NULL); - - std::wstring formatted_string; - if (string_buffer) { - formatted_string = string_buffer; - LocalFree(reinterpret_cast<HLOCAL>(string_buffer)); - } else { - // The formating failed. simply convert the message value into a string. - base::SStringPrintf(&formatted_string, L"message number %d", messageid); - } - return formatted_string; -} - -std::wstring FormatLastWin32Error() { - return FormatMessage(GetLastError()); -} - bool SetAppIdForPropertyStore(IPropertyStore* property_store, const wchar_t* app_id) { DCHECK(property_store); @@ -202,7 +136,8 @@ bool RemoveCommandFromAutoRun(HKEY root_key, const string16& name) { return autorun_key.DeleteValue(name.c_str()); } -} // namespace win_util +} // namespace win +} // namespace base #ifdef _MSC_VER // diff --git a/base/win_util.h b/base/win/win_util.h index 4ba7eeb..187e42d 100644 --- a/base/win_util.h +++ b/base/win/win_util.h @@ -2,8 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef BASE_WIN_UTIL_H_ -#define BASE_WIN_UTIL_H_ +// ============================================================================= +// PLEASE READ +// +// In general, you should not be adding stuff to this file. +// +// - If your thing is only used in one place, just put it in a reasonable +// location in or near that one place. It's nice you want people to be able +// to re-use your function, but realistically, if it hasn't been necessary +// before after so many years of development, it's probably not going to be +// used in other places in the future unless you know of them now. +// +// - If your thing is used by multiple callers and is UI-related, it should +// probably be in app/win/ instead. Try to put it in the most specific file +// possible (avoiding the *_util files when practical). +// +// ============================================================================= + +#ifndef BASE_WIN_WIN_UTIL_H_ +#define BASE_WIN_WIN_UTIL_H_ #pragma once #include <windows.h> @@ -16,21 +33,14 @@ struct IPropertyStore; struct _tagpropertykey; typedef _tagpropertykey PROPERTYKEY; -namespace win_util { +namespace base { +namespace win { void GetNonClientMetrics(NONCLIENTMETRICS* metrics); // Returns the string representing the current user sid. bool GetUserSidString(std::wstring* user_sid); -// Useful for subclassing a HWND. Returns the previous window procedure. -WNDPROC SetWindowProc(HWND hwnd, WNDPROC wndproc); - -// Pointer-friendly wrappers around Get/SetWindowLong(..., GWLP_USERDATA, ...) -// Returns the previously set value. -void* SetWindowUserData(HWND hwnd, void* user_data); -void* GetWindowUserData(HWND hwnd); - // Returns true if the shift key is currently pressed. bool IsShiftPressed(); @@ -40,10 +50,6 @@ bool IsCtrlPressed(); // Returns true if the alt key is currently pressed. bool IsAltPressed(); -// A version of the GetClassNameW API that returns the class name in an -// std::wstring. An empty result indicates a failure to get the class name. -std::wstring GetClassName(HWND window); - // Returns false if user account control (UAC) has been disabled with the // EnableLUA registry flag. Returns true if user account control is enabled. // NOTE: The EnableLUA registry flag, which is ignored on Windows XP @@ -52,13 +58,6 @@ std::wstring GetClassName(HWND window); // if the OS is Vista. bool UserAccountControlIsEnabled(); -// Use the Win32 API FormatMessage() function to generate a string, using -// Windows's default Message Compiled resources; ignoring the inserts. -std::wstring FormatMessage(unsigned messageid); - -// Uses the last Win32 error to generate a human readable message string. -std::wstring FormatLastWin32Error(); - // Sets the application id in given IPropertyStore. The function is intended // for tagging application/chromium shortcut, browser window and jump list for // Win7. @@ -73,6 +72,7 @@ bool AddCommandToAutoRun(HKEY root_key, const string16& name, // could be HKCU or HKLM or the root of any user hive. bool RemoveCommandFromAutoRun(HKEY root_key, const string16& name); -} // namespace win_util +} // namespace win +} // namespace base -#endif // BASE_WIN_UTIL_H_ +#endif // BASE_WIN_WIN_UTIL_H_ diff --git a/base/win/win_util_unittest.cc b/base/win/win_util_unittest.cc new file mode 100644 index 0000000..b79ed56 --- /dev/null +++ b/base/win/win_util_unittest.cc @@ -0,0 +1,58 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <windows.h> + +#include "base/basictypes.h" +#include "base/string_util.h" +#include "base/win/win_util.h" +#include "base/win/windows_version.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace base { +namespace win { + +namespace { + +// Saves the current thread's locale ID when initialized, and restores it when +// the instance is going out of scope. +class ThreadLocaleSaver { + public: + ThreadLocaleSaver() : original_locale_id_(GetThreadLocale()) {} + ~ThreadLocaleSaver() { SetThreadLocale(original_locale_id_); } + + private: + LCID original_locale_id_; + + DISALLOW_COPY_AND_ASSIGN(ThreadLocaleSaver); +}; + +} // namespace + +// The test is somewhat silly, because the Vista bots some have UAC enabled +// and some have it disabled. At least we check that it does not crash. +TEST(BaseWinUtilTest, TestIsUACEnabled) { + if (GetVersion() >= base::win::VERSION_VISTA) { + UserAccountControlIsEnabled(); + } else { + EXPECT_TRUE(UserAccountControlIsEnabled()); + } +} + +TEST(BaseWinUtilTest, TestGetUserSidString) { + std::wstring user_sid; + EXPECT_TRUE(GetUserSidString(&user_sid)); + EXPECT_TRUE(!user_sid.empty()); +} + +TEST(BaseWinUtilTest, TestGetNonClientMetrics) { + NONCLIENTMETRICS metrics = {0}; + GetNonClientMetrics(&metrics); + EXPECT_TRUE(metrics.cbSize > 0); + EXPECT_TRUE(metrics.iScrollWidth > 0); + EXPECT_TRUE(metrics.iScrollHeight > 0); +} + +} // namespace win +} // namespace base diff --git a/base/win_util_unittest.cc b/base/win_util_unittest.cc deleted file mode 100644 index 673bc84..0000000 --- a/base/win_util_unittest.cc +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <windows.h> - -#include "base/basictypes.h" -#include "base/string_util.h" -#include "base/win_util.h" -#include "base/win/windows_version.h" -#include "testing/gtest/include/gtest/gtest.h" - -// The test is somewhat silly, because the Vista bots some have UAC enabled -// and some have it disabled. At least we check that it does not crash. -TEST(BaseWinUtilTest, TestIsUACEnabled) { - if (base::win::GetVersion() >= base::win::VERSION_VISTA) { - win_util::UserAccountControlIsEnabled(); - } else { - EXPECT_TRUE(win_util::UserAccountControlIsEnabled()); - } -} - -TEST(BaseWinUtilTest, TestGetUserSidString) { - std::wstring user_sid; - EXPECT_TRUE(win_util::GetUserSidString(&user_sid)); - EXPECT_TRUE(!user_sid.empty()); -} - -TEST(BaseWinUtilTest, TestGetNonClientMetrics) { - NONCLIENTMETRICS metrics = {0}; - win_util::GetNonClientMetrics(&metrics); - EXPECT_TRUE(metrics.cbSize > 0); - EXPECT_TRUE(metrics.iScrollWidth > 0); - EXPECT_TRUE(metrics.iScrollHeight > 0); -} - -namespace { - -// Saves the current thread's locale ID when initialized, and restores it when -// the instance is going out of scope. -class ThreadLocaleSaver { - public: - ThreadLocaleSaver() : original_locale_id_(GetThreadLocale()) {} - ~ThreadLocaleSaver() { SetThreadLocale(original_locale_id_); } - - private: - LCID original_locale_id_; - - DISALLOW_COPY_AND_ASSIGN(ThreadLocaleSaver); -}; - -} // namespace - -TEST(BaseWinUtilTest, FormatMessage) { - // Because we cannot write tests of every language, we only test the message - // of en-US locale. Here, we change the current locale temporarily. - ThreadLocaleSaver thread_locale_saver; - WORD language_id = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US); - LCID locale_id = MAKELCID(language_id, SORT_DEFAULT); - ASSERT_TRUE(SetThreadLocale(locale_id)); - - const int kAccessDeniedErrorCode = 5; - SetLastError(kAccessDeniedErrorCode); - ASSERT_EQ(GetLastError(), kAccessDeniedErrorCode); - std::wstring value; - TrimWhitespace(win_util::FormatLastWin32Error(), TRIM_ALL, &value); - EXPECT_EQ(std::wstring(L"Access is denied."), value); - - // Manually call the OS function - wchar_t * string_buffer = NULL; - unsigned string_length = - ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, NULL, - kAccessDeniedErrorCode, 0, - reinterpret_cast<wchar_t *>(&string_buffer), 0, NULL); - - // Verify the call succeeded - ASSERT_TRUE(string_length); - ASSERT_TRUE(string_buffer); - - // Verify the string is the same by different calls - EXPECT_EQ(win_util::FormatLastWin32Error(), std::wstring(string_buffer)); - EXPECT_EQ(win_util::FormatMessage(kAccessDeniedErrorCode), - std::wstring(string_buffer)); - - // Done with the buffer allocated by ::FormatMessage() - LocalFree(string_buffer); -} |