Delete lots of unused base/win Change-Id: Ia0b915bd0a39915569022c7a9ae29d2eb29fb228 Reviewed-on: https://gn-review.googlesource.com/1681 Reviewed-by: Brett Wilson <brettw@chromium.org> Commit-Queue: Scott Graham <scottmg@chromium.org>
diff --git a/base/files/file_util_win.cc b/base/files/file_util_win.cc index 545dbc0..9133d7e 100644 --- a/base/files/file_util_win.cc +++ b/base/files/file_util_win.cc
@@ -30,7 +30,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "base/win/scoped_handle.h" -#include "base/win/windows_version.h" // #define needed to link in RtlGenRandom(), a.k.a. SystemFunction036. See the // "Community Additions" comment on MSDN here:
diff --git a/base/win/async_operation.h b/base/win/async_operation.h deleted file mode 100644 index 2c41ddf..0000000 --- a/base/win/async_operation.h +++ /dev/null
@@ -1,244 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_WIN_ASYNC_OPERATION_H_ -#define BASE_WIN_ASYNC_OPERATION_H_ - -#include <unknwn.h> -#include <windows.foundation.h> -#include <wrl/async.h> -#include <wrl/client.h> - -#include <type_traits> -#include <utility> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/optional.h" -#include "base/threading/thread_checker.h" - -namespace base { -namespace win { - -// This file provides an implementation of Windows::Foundation::IAsyncOperation. -// Specializations exist for "regular" types and interface types that inherit -// from IUnknown. Both specializations expose a callback() method, which can be -// used to provide the result that will be forwarded to the registered -// completion handler. For regular types it expects an instance of that type, -// and for interface types it expects a corresponding ComPtr. This class is -// thread-affine and all member methods should be called on the same thread that -// constructed the object. In order to offload heavy result computation, -// base's PostTaskAndReplyWithResult() should be used with the ResultCallback -// passed as a reply. -// -// Example usages: -// -// // Regular types -// auto regular_op = WRL::Make<base::win::AsyncOperation<int>>(); -// auto cb = regular_op->callback(); -// regular_op->put_Completed(...event handler...); -// ... -// // This will invoke the event handler. -// std::move(cb).Run(123); -// ... -// // Results can be queried: -// int results = 0; -// regular_op->GetResults(&results); -// EXPECT_EQ(123, results); -// -// // Interface types -// auto interface_op = WRL::Make<base::win::AsyncOperation<FooBar*>>(); -// auto cb = interface_op->callback(); -// interface_op->put_Completed(...event handler...); -// ... -// // This will invoke the event handler. -// std::move(cb).Run(WRL::Make<IFooBarImpl>()); -// ... -// // Results can be queried: -// WRL::ComPtr<IFooBar> results; -// interface_op->GetResults(&results); -// // |results| points to the provided IFooBarImpl instance. -// -// // Offloading a heavy computation: -// auto my_op = WRL::Make<base::win::AsyncOperation<FooBar*>>(); -// base::PostTaskAndReplyWithResult( -// base::BindOnce(MakeFooBar), my_op->callback()); - -namespace internal { - -// Template tricks needed to dispatch to the correct implementation below. -// -// For all types which are neither InterfaceGroups nor RuntimeClasses, the -// following three typedefs are synonyms for a single C++ type. But for -// InterfaceGroups and RuntimeClasses, they are different types: -// LogicalT: The C++ Type for the InterfaceGroup or RuntimeClass, when -// used as a template parameter. Eg "RCFoo*" -// AbiT: The C++ type for the default interface used to represent the -// InterfaceGroup or RuntimeClass when passed as a method parameter. -// Eg "IFoo*" -// ComplexT: An instantiation of the Internal "AggregateType" template that -// combines LogicalT with AbiT. Eg "AggregateType<RCFoo*,IFoo*>" -// -// windows.foundation.collections.h defines the following template and -// semantics in Windows::Foundation::Internal: -// -// template <class LogicalType, class AbiType> -// struct AggregateType; -// -// LogicalType - the Windows Runtime type (eg, runtime class, inteface group, -// etc) being provided as an argument to an _impl template, when -// that type cannot be represented at the ABI. -// AbiType - the type used for marshalling, ie "at the ABI", for the -// logical type. -template <typename T> -using ComplexT = - typename ABI::Windows::Foundation::IAsyncOperation<T>::TResult_complex; - -template <typename T> -using AbiT = - typename ABI::Windows::Foundation::Internal::GetAbiType<ComplexT<T>>::type; - -template <typename T> -using LogicalT = typename ABI::Windows::Foundation::Internal::GetLogicalType< - ComplexT<T>>::type; - -template <typename T> -using InterfaceT = std::remove_pointer_t<AbiT<T>>; - -// Implementation of shared functionality. -template <class T> -class AsyncOperationBase - : public Microsoft::WRL::RuntimeClass< - Microsoft::WRL::RuntimeClassFlags< - Microsoft::WRL::WinRt | Microsoft::WRL::InhibitRoOriginateError>, - ABI::Windows::Foundation::IAsyncOperation<T>> { - public: - using Handler = ABI::Windows::Foundation::IAsyncOperationCompletedHandler<T>; - - AsyncOperationBase() = default; - ~AsyncOperationBase() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); } - - // ABI::Windows::Foundation::IAsyncOperation: - IFACEMETHODIMP put_Completed(Handler* handler) override { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - handler_ = handler; - return S_OK; - } - - IFACEMETHODIMP get_Completed(Handler** handler) override { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - return handler_.CopyTo(handler); - } - - protected: - void InvokeCompletedHandler() { - handler_->Invoke(this, ABI::Windows::Foundation::AsyncStatus::Completed); - } - - THREAD_CHECKER(thread_checker_); - - private: - Microsoft::WRL::ComPtr<Handler> handler_; - - DISALLOW_COPY_AND_ASSIGN(AsyncOperationBase); -}; - -} // namespace internal - -template <typename T, typename Enable = void> -class AsyncOperation; - -template <typename T> -class AsyncOperation< - T, - std::enable_if_t<std::is_base_of<IUnknown, internal::InterfaceT<T>>::value>> - : public internal::AsyncOperationBase<T> { - public: - using InterfacePointer = Microsoft::WRL::ComPtr<internal::InterfaceT<T>>; - using ResultCallback = base::OnceCallback<void(InterfacePointer)>; - - AsyncOperation() : weak_factory_(this) { - // Note: This can't be done in the constructor initializer list. This is - // because it relies on weak_factory_ to be initialized, which needs to be - // the last class member. Also applies below. - callback_ = - base::BindOnce(&AsyncOperation::OnResult, weak_factory_.GetWeakPtr()); - } - - ResultCallback callback() { - // Note: `this->` here and below is necessary due to the - // -Wmicrosoft-template compiler warning. - DCHECK_CALLED_ON_VALID_THREAD(this->thread_checker_); - DCHECK(!callback_.is_null()); - return std::move(callback_); - } - - // ABI::Windows::Foundation::IAsyncOperation: - IFACEMETHODIMP GetResults(internal::AbiT<T>* results) override { - DCHECK_CALLED_ON_VALID_THREAD(this->thread_checker_); - return ptr_ ? ptr_.CopyTo(results) : E_PENDING; - } - - private: - void OnResult(InterfacePointer ptr) { - DCHECK_CALLED_ON_VALID_THREAD(this->thread_checker_); - DCHECK(!ptr_); - ptr_ = std::move(ptr); - this->InvokeCompletedHandler(); - } - - ResultCallback callback_; - InterfacePointer ptr_; - base::WeakPtrFactory<AsyncOperation> weak_factory_; -}; - -template <typename T> -class AsyncOperation< - T, - std::enable_if_t< - !std::is_base_of<IUnknown, internal::InterfaceT<T>>::value>> - : public internal::AsyncOperationBase<T> { - public: - using ResultCallback = base::OnceCallback<void(T)>; - - AsyncOperation() : weak_factory_(this) { - callback_ = - base::BindOnce(&AsyncOperation::OnResult, weak_factory_.GetWeakPtr()); - } - - ResultCallback callback() { - DCHECK_CALLED_ON_VALID_THREAD(this->thread_checker_); - DCHECK(!callback_.is_null()); - return std::move(callback_); - } - - // ABI::Windows::Foundation::IAsyncOperation: - IFACEMETHODIMP GetResults(internal::AbiT<T>* results) override { - DCHECK_CALLED_ON_VALID_THREAD(this->thread_checker_); - if (!value_) - return E_PENDING; - - *results = *value_; - return S_OK; - } - - private: - void OnResult(T result) { - DCHECK_CALLED_ON_VALID_THREAD(this->thread_checker_); - DCHECK(!value_); - value_.emplace(std::move(result)); - this->InvokeCompletedHandler(); - } - - ResultCallback callback_; - base::Optional<T> value_; - base::WeakPtrFactory<AsyncOperation> weak_factory_; -}; - -} // namespace win -} // namespace base - -#endif // BASE_WIN_ASYNC_OPERATION_H_
diff --git a/base/win/com_init_check_hook.cc b/base/win/com_init_check_hook.cc deleted file mode 100644 index 7055bb0..0000000 --- a/base/win/com_init_check_hook.cc +++ /dev/null
@@ -1,299 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/win/com_init_check_hook.h" - -#include <objbase.h> -#include <stdint.h> -#include <string.h> -#include <windows.h> - -#include "base/strings/stringprintf.h" -#include "base/synchronization/lock.h" -#include "base/win/com_init_util.h" -#include "base/win/patch_util.h" - -namespace base { -namespace win { - -#if defined(COM_INIT_CHECK_HOOK_ENABLED) - -namespace { - -// Hotpatchable Microsoft x86 32-bit functions take one of two forms: -// Newer format: -// RelAddr Binary Instruction Remarks -// -5 cc int 3 -// -4 cc int 3 -// -3 cc int 3 -// -2 cc int 3 -// -1 cc int 3 -// 0 8bff mov edi,edi Actual entry point and no-op. -// 2 ... Actual body. -// -// Older format: -// RelAddr Binary Instruction Remarks -// -5 90 nop -// -4 90 nop -// -3 90 nop -// -2 90 nop -// -1 90 nop -// 0 8bff mov edi,edi Actual entry point and no-op. -// 2 ... Actual body. -// -// The "int 3" or nop sled as well as entry point no-op are critical, as they -// are just enough to patch in a short backwards jump to -5 (2 bytes) then that -// can do a relative 32-bit jump about 2GB before or after the current address. -// -// To perform a hotpatch, we need to figure out where we want to go and where -// we are now as the final jump is relative. Let's say we want to jump to -// 0x12345678. Relative jumps are calculated from eip, which for our jump is the -// next instruction address. For the example above, that means we start at a 0 -// base address. -// -// Our patch will then look as follows: -// RelAddr Binary Instruction Remarks -// -5 e978563412 jmp 0x12345678-(-0x5+0x5) Note little-endian format. -// 0 ebf9 jmp -0x5-(0x0+0x2) Goes to RelAddr -0x5. -// 2 ... Actual body. -// Note: The jmp instructions above are structured as -// Address(Destination)-(Address(jmp Instruction)+sizeof(jmp Instruction)) - -// The struct below is provided for convenience and must be packed together byte -// by byte with no word alignment padding. This comes at a very small -// performance cost because now there are shifts handling the fields, but -// it improves readability. -#pragma pack(push, 1) -struct StructuredHotpatch { - unsigned char jmp_32_relative = 0xe9; // jmp relative 32-bit. - int32_t relative_address = 0; // 32-bit signed operand. - unsigned char jmp_8_relative = 0xeb; // jmp relative 8-bit. - unsigned char back_address = 0xf9; // Operand of -7. -}; -#pragma pack(pop) - -static_assert(sizeof(StructuredHotpatch) == 7, - "Needs to be exactly 7 bytes for the hotpatch to work."); - -// nop Function Padding with "mov edi,edi" -const unsigned char g_hotpatch_placeholder_nop[] = {0x90, 0x90, 0x90, 0x90, - 0x90, 0x8b, 0xff}; - -// int 3 Function Padding with "mov edi,edi" -const unsigned char g_hotpatch_placeholder_int3[] = {0xcc, 0xcc, 0xcc, 0xcc, - 0xcc, 0x8b, 0xff}; - -class HookManager { - public: - static HookManager* GetInstance() { - static auto* hook_manager = new HookManager(); - return hook_manager; - } - - void RegisterHook() { - AutoLock auto_lock(lock_); - if (init_count_ == 0) - WriteHook(); - - ++init_count_; - } - - void UnregisterHook() { - AutoLock auto_lock(lock_); - DCHECK_NE(0U, init_count_); - if (init_count_ == 1) - RevertHook(); - - --init_count_; - } - - private: - enum class HotpatchPlaceholderFormat { - // The hotpatch placeholder is currently unknown - UNKNOWN, - // The hotpatch placeholder used int 3's in the sled. - INT3, - // The hotpatch placeholder used nop's in the sled. - NOP, - // This function has already been patched by a different component. - EXTERNALLY_PATCHED, - }; - - HookManager() = default; - ~HookManager() = default; - - void WriteHook() { - lock_.AssertAcquired(); - DCHECK(!ole32_library_); - ole32_library_ = ::LoadLibrary(L"ole32.dll"); - - if (!ole32_library_) - return; - - // See banner comment above why this subtracts 5 bytes. - co_create_instance_padded_address_ = - reinterpret_cast<uint32_t>( - GetProcAddress(ole32_library_, "CoCreateInstance")) - - 5; - - // See banner comment above why this adds 7 bytes. - original_co_create_instance_body_function_ = - reinterpret_cast<decltype(original_co_create_instance_body_function_)>( - co_create_instance_padded_address_ + 7); - - HotpatchPlaceholderFormat format = GetHotpatchPlaceholderFormat( - reinterpret_cast<const void*>(co_create_instance_padded_address_)); - if (format == HotpatchPlaceholderFormat::UNKNOWN) { - NOTREACHED() << "Unrecognized hotpatch function format: " - << FirstSevenBytesToString( - co_create_instance_padded_address_); - return; - } else if (format == HotpatchPlaceholderFormat::EXTERNALLY_PATCHED) { - hotpatch_placeholder_format_ = format; - NOTREACHED() << "CoCreateInstance appears to be previously patched. (" - << FirstSevenBytesToString( - co_create_instance_padded_address_) - << ")"; - return; - } - - uint32_t dchecked_co_create_instance_address = - reinterpret_cast<uint32_t>(&HookManager::DCheckedCoCreateInstance); - uint32_t jmp_offset_base_address = co_create_instance_padded_address_ + 5; - StructuredHotpatch structured_hotpatch; - structured_hotpatch.relative_address = - dchecked_co_create_instance_address - jmp_offset_base_address; - - DCHECK_EQ(hotpatch_placeholder_format_, HotpatchPlaceholderFormat::UNKNOWN); - DWORD patch_result = internal::ModifyCode( - reinterpret_cast<void*>(co_create_instance_padded_address_), - reinterpret_cast<void*>(&structured_hotpatch), - sizeof(structured_hotpatch)); - if (patch_result == NO_ERROR) - hotpatch_placeholder_format_ = format; - } - - void RevertHook() { - lock_.AssertAcquired(); - switch (hotpatch_placeholder_format_) { - case HotpatchPlaceholderFormat::INT3: - internal::ModifyCode( - reinterpret_cast<void*>(co_create_instance_padded_address_), - reinterpret_cast<const void*>(&g_hotpatch_placeholder_int3), - sizeof(g_hotpatch_placeholder_int3)); - break; - case HotpatchPlaceholderFormat::NOP: - internal::ModifyCode( - reinterpret_cast<void*>(co_create_instance_padded_address_), - reinterpret_cast<const void*>(&g_hotpatch_placeholder_nop), - sizeof(g_hotpatch_placeholder_nop)); - break; - case HotpatchPlaceholderFormat::EXTERNALLY_PATCHED: - case HotpatchPlaceholderFormat::UNKNOWN: - break; - } - - hotpatch_placeholder_format_ = HotpatchPlaceholderFormat::UNKNOWN; - - if (ole32_library_) { - ::FreeLibrary(ole32_library_); - ole32_library_ = nullptr; - } - - co_create_instance_padded_address_ = 0; - original_co_create_instance_body_function_ = nullptr; - } - - HotpatchPlaceholderFormat GetHotpatchPlaceholderFormat(const void* address) { - if (::memcmp(reinterpret_cast<void*>(co_create_instance_padded_address_), - reinterpret_cast<const void*>(&g_hotpatch_placeholder_int3), - sizeof(g_hotpatch_placeholder_int3)) == 0) { - return HotpatchPlaceholderFormat::INT3; - } - - if (::memcmp(reinterpret_cast<void*>(co_create_instance_padded_address_), - reinterpret_cast<const void*>(&g_hotpatch_placeholder_nop), - sizeof(g_hotpatch_placeholder_nop)) == 0) { - return HotpatchPlaceholderFormat::NOP; - } - - const unsigned char* instruction_bytes = - reinterpret_cast<const unsigned char*>( - co_create_instance_padded_address_); - const unsigned char entry_point_byte = instruction_bytes[5]; - // Check for all of the common jmp opcodes. - if (entry_point_byte == 0xeb || entry_point_byte == 0xe9 || - entry_point_byte == 0xff || entry_point_byte == 0xea) { - return HotpatchPlaceholderFormat::EXTERNALLY_PATCHED; - } - - return HotpatchPlaceholderFormat::UNKNOWN; - } - - static HRESULT __stdcall DCheckedCoCreateInstance(const CLSID& rclsid, - IUnknown* pUnkOuter, - DWORD dwClsContext, - REFIID riid, - void** ppv) { - // Chromium COM callers need to make sure that their thread is configured to - // process COM objects to avoid creating an implicit MTA or silently failing - // STA object creation call due to the SUCCEEDED() pattern for COM calls. - // - // If you hit this assert as part of migrating to the Task Scheduler, - // evaluate your threading guarantees and dispatch your work with - // base::CreateCOMSTATaskRunnerWithTraits(). - // - // If you need MTA support, ping //base/task_scheduler/OWNERS. - AssertComInitialized( - "CoCreateInstance calls in Chromium require explicit COM " - "initialization via base::CreateCOMSTATaskRunnerWithTraits() or " - "ScopedCOMInitializer. See the comment in DCheckedCoCreateInstance for " - "more details."); - return original_co_create_instance_body_function_(rclsid, pUnkOuter, - dwClsContext, riid, ppv); - } - - // Returns the first 7 bytes in hex as a string at |address|. - static std::string FirstSevenBytesToString(uint32_t address) { - const unsigned char* bytes = - reinterpret_cast<const unsigned char*>(address); - return base::StringPrintf("%02x %02x %02x %02x %02x %02x %02x", bytes[0], - bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], - bytes[6]); - } - - // Synchronizes everything in this class. - base::Lock lock_; - size_t init_count_ = 0; - HMODULE ole32_library_ = nullptr; - uint32_t co_create_instance_padded_address_ = 0; - HotpatchPlaceholderFormat hotpatch_placeholder_format_ = - HotpatchPlaceholderFormat::UNKNOWN; - static decltype( - ::CoCreateInstance)* original_co_create_instance_body_function_; - - DISALLOW_COPY_AND_ASSIGN(HookManager); -}; - -decltype(::CoCreateInstance)* - HookManager::original_co_create_instance_body_function_ = nullptr; - -} // namespace - -#endif // defined(COM_INIT_CHECK_HOOK_ENABLED) - -ComInitCheckHook::ComInitCheckHook() { -#if defined(COM_INIT_CHECK_HOOK_ENABLED) - HookManager::GetInstance()->RegisterHook(); -#endif // defined(COM_INIT_CHECK_HOOK_ENABLED) -} - -ComInitCheckHook::~ComInitCheckHook() { -#if defined(COM_INIT_CHECK_HOOK_ENABLED) - HookManager::GetInstance()->UnregisterHook(); -#endif // defined(COM_INIT_CHECK_HOOK_ENABLED) -} - -} // namespace win -} // namespace base
diff --git a/base/win/com_init_check_hook.h b/base/win/com_init_check_hook.h deleted file mode 100644 index 6681da1..0000000 --- a/base/win/com_init_check_hook.h +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_WIN_COM_INIT_CHECK_HOOK_H_ -#define BASE_WIN_COM_INIT_CHECK_HOOK_H_ - -#include "base/logging.h" -#include "base/macros.h" -#include "build_config.h" - -namespace base { -namespace win { - -// Hotpatching is only supported in Intel 32-bit x86 processors because Windows -// binaries contain a convenient 2 byte hotpatch noop. This doesn't exist in -// 64-bit binaries. - -#if DCHECK_IS_ON() && defined(ARCH_CPU_X86_FAMILY) && \ - defined(ARCH_CPU_32_BITS) && !defined(GOOGLE_CHROME_BUILD) && \ - !defined(OFFICIAL_BUILD) && \ - !defined(COM_INIT_CHECK_HOOK_DISABLED) // See crbug/737090 for details. -#define COM_INIT_CHECK_HOOK_ENABLED -#endif - -// Manages the installation of consistency DCHECK hooks of COM APIs that require -// COM to be initialized and only works if COM_INIT_CHECK_HOOK_ENABLED is -// defined. Care should be taken if this is instantiated with multiple threads -// running as the hotpatch does not apply atomically. -class ComInitCheckHook { - public: - ComInitCheckHook(); - ~ComInitCheckHook(); - - private: - DISALLOW_COPY_AND_ASSIGN(ComInitCheckHook); -}; - -} // namespace win -} // namespace base - -#endif // BASE_WIN_COM_INIT_CHECK_HOOK_H_
diff --git a/base/win/com_init_util.cc b/base/win/com_init_util.cc deleted file mode 100644 index d81f420..0000000 --- a/base/win/com_init_util.cc +++ /dev/null
@@ -1,81 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/win/com_init_util.h" - -#include <windows.h> -#include <winternl.h> - -namespace base { -namespace win { - -#if DCHECK_IS_ON() - -namespace { - -const char kComNotInitialized[] = "COM is not initialized on this thread."; - -// Derived from combase.dll. -struct OleTlsData { - enum ApartmentFlags { - LOGICAL_THREAD_REGISTERED = 0x2, - STA = 0x80, - MTA = 0x140, - }; - - void* thread_base; - void* sm_allocator; - DWORD apartment_id; - DWORD apartment_flags; - // There are many more fields than this, but for our purposes, we only care - // about |apartment_flags|. Correctly declaring the previous types allows this - // to work between x86 and x64 builds. -}; - -OleTlsData* GetOleTlsData() { - TEB* teb = NtCurrentTeb(); - return reinterpret_cast<OleTlsData*>(teb->ReservedForOle); -} - -ComApartmentType GetComApartmentTypeForThread() { - OleTlsData* ole_tls_data = GetOleTlsData(); - if (!ole_tls_data) - return ComApartmentType::NONE; - - if (ole_tls_data->apartment_flags & OleTlsData::ApartmentFlags::STA) - return ComApartmentType::STA; - - if ((ole_tls_data->apartment_flags & OleTlsData::ApartmentFlags::MTA) == - OleTlsData::ApartmentFlags::MTA) { - return ComApartmentType::MTA; - } - - return ComApartmentType::NONE; -} - -} // namespace - -void AssertComInitialized(const char* message) { - if (GetComApartmentTypeForThread() != ComApartmentType::NONE) - return; - - // COM worker threads don't always set up the apartment, but they do perform - // some thread registration, so we allow those. - OleTlsData* ole_tls_data = GetOleTlsData(); - if (ole_tls_data && (ole_tls_data->apartment_flags & - OleTlsData::ApartmentFlags::LOGICAL_THREAD_REGISTERED)) { - return; - } - - NOTREACHED() << (message ? message : kComNotInitialized); -} - -void AssertComApartmentType(ComApartmentType apartment_type) { - DCHECK_EQ(apartment_type, GetComApartmentTypeForThread()); -} - -#endif // DCHECK_IS_ON() - -} // namespace win -} // namespace base
diff --git a/base/win/com_init_util.h b/base/win/com_init_util.h deleted file mode 100644 index 9d47099..0000000 --- a/base/win/com_init_util.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_WIN_COM_INIT_UTIL_H_ -#define BASE_WIN_COM_INIT_UTIL_H_ - -#include "base/logging.h" - -namespace base { -namespace win { - -enum class ComApartmentType { - // Uninitialized or has an unrecognized apartment type. - NONE, - // Single-threaded Apartment. - STA, - // Multi-threaded Apartment. - MTA, -}; - -#if DCHECK_IS_ON() - -// DCHECKs if COM is not initialized on this thread as an STA or MTA. -// |message| is optional and is used for the DCHECK if specified. -void AssertComInitialized(const char* message = nullptr); - -// DCHECKs if |apartment_type| is not the same as the current thread's apartment -// type. -void AssertComApartmentType(ComApartmentType apartment_type); - -#else // DCHECK_IS_ON() -inline void AssertComInitialized() {} -inline void AssertComApartmentType(ComApartmentType apartment_type) {} -#endif // DCHECK_IS_ON() - -} // namespace win -} // namespace base - -#endif // BASE_WIN_COM_INIT_UTIL_H_
diff --git a/base/win/core_winrt_util.cc b/base/win/core_winrt_util.cc deleted file mode 100644 index 7a30490..0000000 --- a/base/win/core_winrt_util.cc +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/win/core_winrt_util.h" - -namespace { - -FARPROC LoadComBaseFunction(const char* function_name) { - static HMODULE const handle = ::LoadLibrary(L"combase.dll"); - return handle ? ::GetProcAddress(handle, function_name) : nullptr; -} - -decltype(&::RoInitialize) GetRoInitializeFunction() { - static decltype(&::RoInitialize) const function = - reinterpret_cast<decltype(&::RoInitialize)>( - LoadComBaseFunction("RoInitialize")); - return function; -} - -decltype(&::RoUninitialize) GetRoUninitializeFunction() { - static decltype(&::RoUninitialize) const function = - reinterpret_cast<decltype(&::RoUninitialize)>( - LoadComBaseFunction("RoUninitialize")); - return function; -} - -decltype(&::RoActivateInstance) GetRoActivateInstanceFunction() { - static decltype(&::RoActivateInstance) const function = - reinterpret_cast<decltype(&::RoActivateInstance)>( - LoadComBaseFunction("RoActivateInstance")); - return function; -} - -decltype(&::RoGetActivationFactory) GetRoGetActivationFactoryFunction() { - static decltype(&::RoGetActivationFactory) const function = - reinterpret_cast<decltype(&::RoGetActivationFactory)>( - LoadComBaseFunction("RoGetActivationFactory")); - return function; -} - -} // namespace - -namespace base { -namespace win { - -bool ResolveCoreWinRTDelayload() { - // TODO(finnur): Add AssertIOAllowed once crbug.com/770193 is fixed. - return GetRoInitializeFunction() && GetRoUninitializeFunction() && - GetRoActivateInstanceFunction() && GetRoGetActivationFactoryFunction(); -} - -HRESULT RoInitialize(RO_INIT_TYPE init_type) { - auto ro_initialize_func = GetRoInitializeFunction(); - if (!ro_initialize_func) - return E_FAIL; - return ro_initialize_func(init_type); -} - -void RoUninitialize() { - auto ro_uninitialize_func = GetRoUninitializeFunction(); - if (ro_uninitialize_func) - ro_uninitialize_func(); -} - -HRESULT RoGetActivationFactory(HSTRING class_id, - const IID& iid, - void** out_factory) { - auto get_factory_func = GetRoGetActivationFactoryFunction(); - if (!get_factory_func) - return E_FAIL; - return get_factory_func(class_id, iid, out_factory); -} - -HRESULT RoActivateInstance(HSTRING class_id, IInspectable** instance) { - auto activate_instance_func = GetRoActivateInstanceFunction(); - if (!activate_instance_func) - return E_FAIL; - return activate_instance_func(class_id, instance); -} - -} // namespace win -} // namespace base
diff --git a/base/win/core_winrt_util.h b/base/win/core_winrt_util.h deleted file mode 100644 index d760c79..0000000 --- a/base/win/core_winrt_util.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_WIN_CORE_WINRT_UTIL_H_ -#define BASE_WIN_CORE_WINRT_UTIL_H_ - -#include <hstring.h> -#include <inspectable.h> -#include <roapi.h> -#include <windef.h> - -#include "base/strings/string16.h" -#include "base/win/scoped_hstring.h" - -namespace base { -namespace win { - -// Provides access to Core WinRT functions which may not be available on -// Windows 7. Loads functions dynamically at runtime to prevent library -// dependencies. - -bool ResolveCoreWinRTDelayload(); - -// The following stubs are provided for when component build is enabled, in -// order to avoid the propagation of delay-loading CoreWinRT to other modules. - -HRESULT RoInitialize(RO_INIT_TYPE init_type); - -void RoUninitialize(); - -HRESULT RoGetActivationFactory(HSTRING class_id, - const IID& iid, - void** out_factory); - -HRESULT RoActivateInstance(HSTRING class_id, IInspectable** instance); - -// Retrieves an activation factory for the type specified. -template <typename InterfaceType, char16 const* runtime_class_id> -HRESULT GetActivationFactory(InterfaceType** factory) { - ScopedHString class_id_hstring = ScopedHString::Create(runtime_class_id); - if (!class_id_hstring.is_valid()) - return E_FAIL; - - return base::win::RoGetActivationFactory(class_id_hstring.get(), - IID_PPV_ARGS(factory)); -} - -} // namespace win -} // namespace base - -#endif // BASE_WIN_CORE_WINRT_UTIL_H_
diff --git a/base/win/dllmain.cc b/base/win/dllmain.cc deleted file mode 100644 index 907c7f4..0000000 --- a/base/win/dllmain.cc +++ /dev/null
@@ -1,123 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Windows doesn't support pthread_key_create's destr_function, and in fact -// it's a bit tricky to get code to run when a thread exits. This is -// cargo-cult magic from http://www.codeproject.com/threads/tls.asp. -// We are trying to be compatible with both a LoadLibrary style invocation, as -// well as static linking. This code only needs to be included if we use -// LoadLibrary, but it hooks into the "standard" set of TLS callbacks that are -// provided for static linking. - -// This code is deliberately written to match the style of calls seen in -// base/threading/thread_local_storage_win.cc. Please keep the two in sync if -// coding conventions are changed. - -// WARNING: Do *NOT* try to include this in the construction of the base -// library, even though it potentially drives code in -// base/threading/thread_local_storage_win.cc. If you do, some users will end -// up getting duplicate definition of DllMain() in some of their later links. - -// Force a reference to _tls_used to make the linker create the TLS directory -// if it's not already there (that is, even if __declspec(thread) is not used). -// Force a reference to p_thread_callback_dllmain_typical_entry to prevent whole -// program optimization from discarding the variables. - -#include <windows.h> - -#include "base/compiler_specific.h" -#include "base/win/win_util.h" - -// Indicate if another service is scanning the callbacks. When this becomes -// set to true, then DllMain() will stop supporting the callback service. This -// value is set to true the first time any of our callbacks are called, as that -// shows that some other service is handling callbacks. -static bool linker_notifications_are_active = false; - -// This will be our mostly no-op callback that we'll list. We won't -// deliberately call it, and if it is called, that means we don't need to do any -// of the callbacks anymore. We expect such a call to arrive via a -// THREAD_ATTACH message, long before we'd have to perform our THREAD_DETACH -// callbacks. -static void NTAPI on_callback(PVOID h, DWORD reason, PVOID reserved); - -#ifdef _WIN64 - -#pragma comment(linker, "/INCLUDE:_tls_used") -#pragma comment(linker, "/INCLUDE:p_thread_callback_dllmain_typical_entry") - -#else // _WIN64 - -#pragma comment(linker, "/INCLUDE:__tls_used") -#pragma comment(linker, "/INCLUDE:_p_thread_callback_dllmain_typical_entry") - -#endif // _WIN64 - -// Explicitly depend on VC\crt\src\tlssup.c variables -// to bracket the list of TLS callbacks. -extern "C" PIMAGE_TLS_CALLBACK __xl_a, __xl_z; - -// extern "C" suppresses C++ name mangling so we know the symbol names for the -// linker /INCLUDE:symbol pragmas above. -extern "C" { -#ifdef _WIN64 - -// .CRT section is merged with .rdata on x64 so it must be constant data. -#pragma data_seg(push, old_seg) -// Use a typical possible name in the .CRT$XL? list of segments. -#pragma const_seg(".CRT$XLB") -// When defining a const variable, it must have external linkage to be sure the -// linker doesn't discard it. -extern const PIMAGE_TLS_CALLBACK p_thread_callback_dllmain_typical_entry; -const PIMAGE_TLS_CALLBACK p_thread_callback_dllmain_typical_entry = on_callback; -#pragma data_seg(pop, old_seg) - -#else // _WIN64 - -#pragma data_seg(push, old_seg) -// Use a typical possible name in the .CRT$XL? list of segments. -#pragma data_seg(".CRT$XLB") -PIMAGE_TLS_CALLBACK p_thread_callback_dllmain_typical_entry = on_callback; -#pragma data_seg(pop, old_seg) - -#endif // _WIN64 -} // extern "C" - -// Custom crash code to get a unique entry in crash reports. -NOINLINE static void CrashOnProcessDetach() { - *static_cast<volatile int*>(0) = 0x356; -} - -// Make DllMain call the listed callbacks. This way any third parties that are -// linked in will also be called. -BOOL WINAPI DllMain(PVOID h, DWORD reason, PVOID reserved) { - if (DLL_PROCESS_DETACH == reason && base::win::ShouldCrashOnProcessDetach()) - CrashOnProcessDetach(); - - if (DLL_THREAD_DETACH != reason && DLL_PROCESS_DETACH != reason) - return true; // We won't service THREAD_ATTACH calls. - - if (linker_notifications_are_active) - return true; // Some other service is doing this work. - - for (PIMAGE_TLS_CALLBACK* it = &__xl_a; it < &__xl_z; ++it) { - if (*it == NULL || *it == on_callback) - continue; // Don't bother to call our own callback. - (*it)(h, reason, reserved); - } - return true; -} - -static void NTAPI on_callback(PVOID h, DWORD reason, PVOID reserved) { - // Do nothing. We were just a place holder in the list used to test that we - // call all items. - // If we are called, it means that some other system is scanning the callbacks - // and we don't need to do so in DllMain(). - linker_notifications_are_active = true; - // Note: If some other routine some how plays this same game... we could both - // decide not to do the scanning <sigh>, but this trick should suppress - // duplicate calls on Vista, where the runtime takes care of the callbacks, - // and allow us to do the callbacks on XP, where we are currently devoid of - // callbacks (due to an explicit LoadLibrary call). -}
diff --git a/base/win/enum_variant.cc b/base/win/enum_variant.cc deleted file mode 100644 index fd81775..0000000 --- a/base/win/enum_variant.cc +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/win/enum_variant.h" - -#include <algorithm> - -#include "base/logging.h" - -namespace base { -namespace win { - -EnumVariant::EnumVariant(unsigned long count) - : items_(new VARIANT[count]), count_(count), current_index_(0) {} - -EnumVariant::~EnumVariant() {} - -VARIANT* EnumVariant::ItemAt(unsigned long index) { - DCHECK(index < count_); - return &items_[index]; -} - -ULONG STDMETHODCALLTYPE EnumVariant::AddRef() { - return IUnknownImpl::AddRef(); -} - -ULONG STDMETHODCALLTYPE EnumVariant::Release() { - return IUnknownImpl::Release(); -} - -STDMETHODIMP EnumVariant::QueryInterface(REFIID riid, void** ppv) { - if (riid == IID_IEnumVARIANT) { - *ppv = static_cast<IEnumVARIANT*>(this); - AddRef(); - return S_OK; - } - - return IUnknownImpl::QueryInterface(riid, ppv); -} - -STDMETHODIMP EnumVariant::Next(ULONG requested_count, - VARIANT* out_elements, - ULONG* out_elements_received) { - unsigned long count = std::min(requested_count, count_ - current_index_); - for (unsigned long i = 0; i < count; ++i) - out_elements[i] = items_[current_index_ + i]; - current_index_ += count; - *out_elements_received = count; - - return (count == requested_count ? S_OK : S_FALSE); -} - -STDMETHODIMP EnumVariant::Skip(ULONG skip_count) { - unsigned long count = skip_count; - if (current_index_ + count > count_) - count = count_ - current_index_; - - current_index_ += count; - return (count == skip_count ? S_OK : S_FALSE); -} - -STDMETHODIMP EnumVariant::Reset() { - current_index_ = 0; - return S_OK; -} - -STDMETHODIMP EnumVariant::Clone(IEnumVARIANT** out_cloned_object) { - EnumVariant* other = new EnumVariant(count_); - if (count_ > 0) - memcpy(other->ItemAt(0), &items_[0], count_ * sizeof(VARIANT)); - other->Skip(current_index_); - other->AddRef(); - *out_cloned_object = other; - return S_OK; -} - -} // namespace win -} // namespace base
diff --git a/base/win/enum_variant.h b/base/win/enum_variant.h deleted file mode 100644 index d12f350..0000000 --- a/base/win/enum_variant.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_WIN_ENUM_VARIANT_H_ -#define BASE_WIN_ENUM_VARIANT_H_ - -#include <unknwn.h> - -#include <memory> - -#include "base/win/iunknown_impl.h" - -namespace base { -namespace win { - -// A simple implementation of IEnumVARIANT. -class EnumVariant : public IEnumVARIANT, public IUnknownImpl { - public: - // The constructor allocates an array of size |count|. Then use - // ItemAt to set the value of each item in the array to initialize it. - explicit EnumVariant(unsigned long count); - - // Returns a mutable pointer to the item at position |index|. - VARIANT* ItemAt(unsigned long index); - - // IUnknown. - ULONG STDMETHODCALLTYPE AddRef() override; - ULONG STDMETHODCALLTYPE Release() override; - STDMETHODIMP QueryInterface(REFIID riid, void** ppv) override; - - // IEnumVARIANT. - STDMETHODIMP Next(ULONG requested_count, - VARIANT* out_elements, - ULONG* out_elements_received) override; - STDMETHODIMP Skip(ULONG skip_count) override; - STDMETHODIMP Reset() override; - STDMETHODIMP Clone(IEnumVARIANT** out_cloned_object) override; - - private: - ~EnumVariant() override; - - std::unique_ptr<VARIANT[]> items_; - unsigned long count_; - unsigned long current_index_; -}; - -} // namespace win -} // namespace base - -#endif // BASE_WIN_ENUM_VARIANT_H_
diff --git a/base/win/iat_patch_function.cc b/base/win/iat_patch_function.cc deleted file mode 100644 index 5f151f9..0000000 --- a/base/win/iat_patch_function.cc +++ /dev/null
@@ -1,255 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/win/iat_patch_function.h" - -#include "base/logging.h" -#include "base/win/patch_util.h" -#include "base/win/pe_image.h" - -namespace base { -namespace win { - -namespace { - -struct InterceptFunctionInformation { - bool finished_operation; - const char* imported_from_module; - const char* function_name; - void* new_function; - void** old_function; - IMAGE_THUNK_DATA** iat_thunk; - DWORD return_code; -}; - -void* GetIATFunction(IMAGE_THUNK_DATA* iat_thunk) { - if (NULL == iat_thunk) { - NOTREACHED(); - return NULL; - } - - // Works around the 64 bit portability warning: - // The Function member inside IMAGE_THUNK_DATA is really a pointer - // to the IAT function. IMAGE_THUNK_DATA correctly maps to IMAGE_THUNK_DATA32 - // or IMAGE_THUNK_DATA64 for correct pointer size. - union FunctionThunk { - IMAGE_THUNK_DATA thunk; - void* pointer; - } iat_function; - - iat_function.thunk = *iat_thunk; - return iat_function.pointer; -} - -bool InterceptEnumCallback(const base::win::PEImage& image, - const char* module, - DWORD ordinal, - const char* name, - DWORD hint, - IMAGE_THUNK_DATA* iat, - void* cookie) { - InterceptFunctionInformation* intercept_information = - reinterpret_cast<InterceptFunctionInformation*>(cookie); - - if (NULL == intercept_information) { - NOTREACHED(); - return false; - } - - DCHECK(module); - - if ((0 == lstrcmpiA(module, intercept_information->imported_from_module)) && - (NULL != name) && - (0 == lstrcmpiA(name, intercept_information->function_name))) { - // Save the old pointer. - if (NULL != intercept_information->old_function) { - *(intercept_information->old_function) = GetIATFunction(iat); - } - - if (NULL != intercept_information->iat_thunk) { - *(intercept_information->iat_thunk) = iat; - } - - // portability check - static_assert( - sizeof(iat->u1.Function) == sizeof(intercept_information->new_function), - "unknown IAT thunk format"); - - // Patch the function. - intercept_information->return_code = internal::ModifyCode( - &(iat->u1.Function), &(intercept_information->new_function), - sizeof(intercept_information->new_function)); - - // Terminate further enumeration. - intercept_information->finished_operation = true; - return false; - } - - return true; -} - -// Helper to intercept a function in an import table of a specific -// module. -// -// Arguments: -// module_handle Module to be intercepted -// imported_from_module Module that exports the symbol -// function_name Name of the API to be intercepted -// new_function Interceptor function -// old_function Receives the original function pointer -// iat_thunk Receives pointer to IAT_THUNK_DATA -// for the API from the import table. -// -// Returns: Returns NO_ERROR on success or Windows error code -// as defined in winerror.h -DWORD InterceptImportedFunction(HMODULE module_handle, - const char* imported_from_module, - const char* function_name, - void* new_function, - void** old_function, - IMAGE_THUNK_DATA** iat_thunk) { - if ((NULL == module_handle) || (NULL == imported_from_module) || - (NULL == function_name) || (NULL == new_function)) { - NOTREACHED(); - return ERROR_INVALID_PARAMETER; - } - - base::win::PEImage target_image(module_handle); - if (!target_image.VerifyMagic()) { - NOTREACHED(); - return ERROR_INVALID_PARAMETER; - } - - InterceptFunctionInformation intercept_information = {false, - imported_from_module, - function_name, - new_function, - old_function, - iat_thunk, - ERROR_GEN_FAILURE}; - - // First go through the IAT. If we don't find the import we are looking - // for in IAT, search delay import table. - target_image.EnumAllImports(InterceptEnumCallback, &intercept_information); - if (!intercept_information.finished_operation) { - target_image.EnumAllDelayImports(InterceptEnumCallback, - &intercept_information); - } - - return intercept_information.return_code; -} - -// Restore intercepted IAT entry with the original function. -// -// Arguments: -// intercept_function Interceptor function -// original_function Receives the original function pointer -// -// Returns: Returns NO_ERROR on success or Windows error code -// as defined in winerror.h -DWORD RestoreImportedFunction(void* intercept_function, - void* original_function, - IMAGE_THUNK_DATA* iat_thunk) { - if ((NULL == intercept_function) || (NULL == original_function) || - (NULL == iat_thunk)) { - NOTREACHED(); - return ERROR_INVALID_PARAMETER; - } - - if (GetIATFunction(iat_thunk) != intercept_function) { - // Check if someone else has intercepted on top of us. - // We cannot unpatch in this case, just raise a red flag. - NOTREACHED(); - return ERROR_INVALID_FUNCTION; - } - - return internal::ModifyCode(&(iat_thunk->u1.Function), &original_function, - sizeof(original_function)); -} - -} // namespace - -IATPatchFunction::IATPatchFunction() - : module_handle_(NULL), - intercept_function_(NULL), - original_function_(NULL), - iat_thunk_(NULL) {} - -IATPatchFunction::~IATPatchFunction() { - if (NULL != intercept_function_) { - DWORD error = Unpatch(); - DCHECK_EQ(static_cast<DWORD>(NO_ERROR), error); - } -} - -DWORD IATPatchFunction::Patch(const wchar_t* module, - const char* imported_from_module, - const char* function_name, - void* new_function) { - HMODULE module_handle = LoadLibraryW(module); - if (module_handle == NULL) { - NOTREACHED(); - return GetLastError(); - } - - DWORD error = PatchFromModule(module_handle, imported_from_module, - function_name, new_function); - if (NO_ERROR == error) { - module_handle_ = module_handle; - } else { - FreeLibrary(module_handle); - } - - return error; -} - -DWORD IATPatchFunction::PatchFromModule(HMODULE module, - const char* imported_from_module, - const char* function_name, - void* new_function) { - DCHECK_EQ(static_cast<void*>(NULL), original_function_); - DCHECK_EQ(static_cast<IMAGE_THUNK_DATA*>(NULL), iat_thunk_); - DCHECK_EQ(static_cast<void*>(NULL), intercept_function_); - DCHECK(module); - - DWORD error = - InterceptImportedFunction(module, imported_from_module, function_name, - new_function, &original_function_, &iat_thunk_); - - if (NO_ERROR == error) { - DCHECK_NE(original_function_, intercept_function_); - intercept_function_ = new_function; - } - - return error; -} - -DWORD IATPatchFunction::Unpatch() { - DWORD error = RestoreImportedFunction(intercept_function_, original_function_, - iat_thunk_); - DCHECK_EQ(static_cast<DWORD>(NO_ERROR), error); - - // Hands off the intercept if we fail to unpatch. - // If IATPatchFunction::Unpatch fails during RestoreImportedFunction - // it means that we cannot safely unpatch the import address table - // patch. In this case its better to be hands off the intercept as - // trying to unpatch again in the destructor of IATPatchFunction is - // not going to be any safer - if (module_handle_) - FreeLibrary(module_handle_); - module_handle_ = NULL; - intercept_function_ = NULL; - original_function_ = NULL; - iat_thunk_ = NULL; - - return error; -} - -void* IATPatchFunction::original_function() const { - DCHECK(is_patched()); - return original_function_; -} - -} // namespace win -} // namespace base
diff --git a/base/win/iat_patch_function.h b/base/win/iat_patch_function.h deleted file mode 100644 index c9f2d6c..0000000 --- a/base/win/iat_patch_function.h +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_WIN_IAT_PATCH_FUNCTION_H_ -#define BASE_WIN_IAT_PATCH_FUNCTION_H_ - -#include <windows.h> - -#include "base/macros.h" - -namespace base { -namespace win { - -// A class that encapsulates Import Address Table patching helpers and restores -// the original function in the destructor. -// -// It will intercept functions for a specific DLL imported from another DLL. -// This is the case when, for example, we want to intercept -// CertDuplicateCertificateContext function (exported from crypt32.dll) called -// by wininet.dll. -class IATPatchFunction { - public: - IATPatchFunction(); - ~IATPatchFunction(); - - // Intercept a function in an import table of a specific - // module. Save the original function and the import - // table address. These values will be used later - // during Unpatch - // - // Arguments: - // module Module to be intercepted - // imported_from_module Module that exports the 'function_name' - // function_name Name of the API to be intercepted - // - // Returns: Windows error code (winerror.h). NO_ERROR if successful - // - // Note: Patching a function will make the IAT patch take some "ownership" on - // |module|. It will LoadLibrary(module) to keep the DLL alive until a call - // to Unpatch(), which will call FreeLibrary() and allow the module to be - // unloaded. The idea is to help prevent the DLL from going away while a - // patch is still active. - DWORD Patch(const wchar_t* module, - const char* imported_from_module, - const char* function_name, - void* new_function); - - // Same as Patch(), but uses a handle to a |module| instead of the DLL name. - DWORD PatchFromModule(HMODULE module, - const char* imported_from_module, - const char* function_name, - void* new_function); - - // Unpatch the IAT entry using internally saved original - // function. - // - // Returns: Windows error code (winerror.h). NO_ERROR if successful - DWORD Unpatch(); - - bool is_patched() const { return (NULL != intercept_function_); } - - void* original_function() const; - - private: - HMODULE module_handle_; - void* intercept_function_; - void* original_function_; - IMAGE_THUNK_DATA* iat_thunk_; - - DISALLOW_COPY_AND_ASSIGN(IATPatchFunction); -}; - -} // namespace win -} // namespace base - -#endif // BASE_WIN_IAT_PATCH_FUNCTION_H_
diff --git a/base/win/iunknown_impl.cc b/base/win/iunknown_impl.cc deleted file mode 100644 index 2d83523..0000000 --- a/base/win/iunknown_impl.cc +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/win/iunknown_impl.h" - -namespace base { -namespace win { - -IUnknownImpl::IUnknownImpl() : ref_count_(0) {} - -IUnknownImpl::~IUnknownImpl() {} - -ULONG STDMETHODCALLTYPE IUnknownImpl::AddRef() { - ref_count_.Increment(); - return 1; -} - -ULONG STDMETHODCALLTYPE IUnknownImpl::Release() { - if (!ref_count_.Decrement()) { - delete this; - return 0; - } - return 1; -} - -STDMETHODIMP IUnknownImpl::QueryInterface(REFIID riid, void** ppv) { - if (riid == IID_IUnknown) { - *ppv = static_cast<IUnknown*>(this); - AddRef(); - return S_OK; - } - - *ppv = NULL; - return E_NOINTERFACE; -} - -} // namespace win -} // namespace base
diff --git a/base/win/iunknown_impl.h b/base/win/iunknown_impl.h deleted file mode 100644 index 60f2403..0000000 --- a/base/win/iunknown_impl.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_WIN_IUNKNOWN_IMPL_H_ -#define BASE_WIN_IUNKNOWN_IMPL_H_ - -#include <unknwn.h> - -#include "base/atomic_ref_count.h" -#include "base/compiler_specific.h" - -namespace base { -namespace win { - -// IUnknown implementation for other classes to derive from. -class IUnknownImpl : public IUnknown { - public: - IUnknownImpl(); - - ULONG STDMETHODCALLTYPE AddRef() override; - ULONG STDMETHODCALLTYPE Release() override; - - // Subclasses should extend this to return any interfaces they provide. - STDMETHODIMP QueryInterface(REFIID riid, void** ppv) override; - - protected: - virtual ~IUnknownImpl(); - - private: - AtomicRefCount ref_count_; -}; - -} // namespace win -} // namespace base - -#endif // BASE_WIN_IUNKNOWN_IMPL_H_
diff --git a/base/win/pe_image.cc b/base/win/pe_image.cc deleted file mode 100644 index ea58504..0000000 --- a/base/win/pe_image.cc +++ /dev/null
@@ -1,582 +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. - -// This file implements PEImage, a generic class to manipulate PE files. -// This file was adapted from GreenBorder's Code. - -#include <stddef.h> - -#include "base/win/pe_image.h" - -namespace base { -namespace win { - -// Structure to perform imports enumerations. -struct EnumAllImportsStorage { - PEImage::EnumImportsFunction callback; - PVOID cookie; -}; - -namespace { - -// PdbInfo Signature -const DWORD kPdbInfoSignature = 'SDSR'; - -// Compare two strings byte by byte on an unsigned basis. -// if s1 == s2, return 0 -// if s1 < s2, return negative -// if s1 > s2, return positive -// Exception if inputs are invalid. -int StrCmpByByte(LPCSTR s1, LPCSTR s2) { - while (*s1 != '\0' && *s1 == *s2) { - ++s1; - ++s2; - } - - return (*reinterpret_cast<const unsigned char*>(s1) - - *reinterpret_cast<const unsigned char*>(s2)); -} - -struct PdbInfo { - DWORD Signature; - GUID Guid; - DWORD Age; - char PdbFileName[1]; -}; - -} // namespace - -// Callback used to enumerate imports. See EnumImportChunksFunction. -bool ProcessImportChunk(const PEImage& image, - LPCSTR module, - PIMAGE_THUNK_DATA name_table, - PIMAGE_THUNK_DATA iat, - PVOID cookie) { - EnumAllImportsStorage& storage = - *reinterpret_cast<EnumAllImportsStorage*>(cookie); - - return image.EnumOneImportChunk(storage.callback, module, name_table, iat, - storage.cookie); -} - -// Callback used to enumerate delay imports. See EnumDelayImportChunksFunction. -bool ProcessDelayImportChunk(const PEImage& image, - PImgDelayDescr delay_descriptor, - LPCSTR module, - PIMAGE_THUNK_DATA name_table, - PIMAGE_THUNK_DATA iat, - PVOID cookie) { - EnumAllImportsStorage& storage = - *reinterpret_cast<EnumAllImportsStorage*>(cookie); - - return image.EnumOneDelayImportChunk(storage.callback, delay_descriptor, - module, name_table, iat, storage.cookie); -} - -void PEImage::set_module(HMODULE module) { - module_ = module; -} - -PIMAGE_DOS_HEADER PEImage::GetDosHeader() const { - return reinterpret_cast<PIMAGE_DOS_HEADER>(module_); -} - -PIMAGE_NT_HEADERS PEImage::GetNTHeaders() const { - PIMAGE_DOS_HEADER dos_header = GetDosHeader(); - - return reinterpret_cast<PIMAGE_NT_HEADERS>( - reinterpret_cast<char*>(dos_header) + dos_header->e_lfanew); -} - -PIMAGE_SECTION_HEADER PEImage::GetSectionHeader(UINT section) const { - PIMAGE_NT_HEADERS nt_headers = GetNTHeaders(); - PIMAGE_SECTION_HEADER first_section = IMAGE_FIRST_SECTION(nt_headers); - - if (section < nt_headers->FileHeader.NumberOfSections) - return first_section + section; - else - return NULL; -} - -WORD PEImage::GetNumSections() const { - return GetNTHeaders()->FileHeader.NumberOfSections; -} - -DWORD PEImage::GetImageDirectoryEntrySize(UINT directory) const { - PIMAGE_NT_HEADERS nt_headers = GetNTHeaders(); - - return nt_headers->OptionalHeader.DataDirectory[directory].Size; -} - -PVOID PEImage::GetImageDirectoryEntryAddr(UINT directory) const { - PIMAGE_NT_HEADERS nt_headers = GetNTHeaders(); - - return RVAToAddr( - nt_headers->OptionalHeader.DataDirectory[directory].VirtualAddress); -} - -PIMAGE_SECTION_HEADER PEImage::GetImageSectionFromAddr(PVOID address) const { - PBYTE target = reinterpret_cast<PBYTE>(address); - PIMAGE_SECTION_HEADER section; - - for (UINT i = 0; NULL != (section = GetSectionHeader(i)); i++) { - // Don't use the virtual RVAToAddr. - PBYTE start = - reinterpret_cast<PBYTE>(PEImage::RVAToAddr(section->VirtualAddress)); - - DWORD size = section->Misc.VirtualSize; - - if ((start <= target) && (start + size > target)) - return section; - } - - return NULL; -} - -PIMAGE_SECTION_HEADER PEImage::GetImageSectionHeaderByName( - LPCSTR section_name) const { - if (NULL == section_name) - return NULL; - - PIMAGE_SECTION_HEADER ret = NULL; - int num_sections = GetNumSections(); - - for (int i = 0; i < num_sections; i++) { - PIMAGE_SECTION_HEADER section = GetSectionHeader(i); - if (0 == _strnicmp(reinterpret_cast<LPCSTR>(section->Name), section_name, - sizeof(section->Name))) { - ret = section; - break; - } - } - - return ret; -} - -bool PEImage::GetDebugId(LPGUID guid, LPDWORD age, LPCSTR* pdb_filename) const { - DWORD debug_directory_size = - GetImageDirectoryEntrySize(IMAGE_DIRECTORY_ENTRY_DEBUG); - PIMAGE_DEBUG_DIRECTORY debug_directory = - reinterpret_cast<PIMAGE_DEBUG_DIRECTORY>( - GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_DEBUG)); - - size_t directory_count = debug_directory_size / sizeof(IMAGE_DEBUG_DIRECTORY); - - for (size_t index = 0; index < directory_count; ++index) { - if (debug_directory[index].Type == IMAGE_DEBUG_TYPE_CODEVIEW) { - PdbInfo* pdb_info = reinterpret_cast<PdbInfo*>( - RVAToAddr(debug_directory[index].AddressOfRawData)); - if (pdb_info->Signature != kPdbInfoSignature) { - // Unsupported PdbInfo signature - return false; - } - - if (guid) - *guid = pdb_info->Guid; - if (age) - *age = pdb_info->Age; - if (pdb_filename) - *pdb_filename = pdb_info->PdbFileName; - return true; - } - } - return false; -} - -PDWORD PEImage::GetExportEntry(LPCSTR name) const { - PIMAGE_EXPORT_DIRECTORY exports = GetExportDirectory(); - - if (NULL == exports) - return NULL; - - WORD ordinal = 0; - if (!GetProcOrdinal(name, &ordinal)) - return NULL; - - PDWORD functions = - reinterpret_cast<PDWORD>(RVAToAddr(exports->AddressOfFunctions)); - - return functions + ordinal - exports->Base; -} - -FARPROC PEImage::GetProcAddress(LPCSTR function_name) const { - PDWORD export_entry = GetExportEntry(function_name); - if (NULL == export_entry) - return NULL; - - PBYTE function = reinterpret_cast<PBYTE>(RVAToAddr(*export_entry)); - - PBYTE exports = reinterpret_cast<PBYTE>( - GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_EXPORT)); - DWORD size = GetImageDirectoryEntrySize(IMAGE_DIRECTORY_ENTRY_EXPORT); - - // Check for forwarded exports as a special case. - if (exports <= function && exports + size > function) - return reinterpret_cast<FARPROC>(-1); - - return reinterpret_cast<FARPROC>(function); -} - -bool PEImage::GetProcOrdinal(LPCSTR function_name, WORD* ordinal) const { - if (NULL == ordinal) - return false; - - PIMAGE_EXPORT_DIRECTORY exports = GetExportDirectory(); - - if (NULL == exports) - return false; - - if (IsOrdinal(function_name)) { - *ordinal = ToOrdinal(function_name); - } else { - PDWORD names = reinterpret_cast<PDWORD>(RVAToAddr(exports->AddressOfNames)); - PDWORD lower = names; - PDWORD upper = names + exports->NumberOfNames; - int cmp = -1; - - // Binary Search for the name. - while (lower != upper) { - PDWORD middle = lower + (upper - lower) / 2; - LPCSTR name = reinterpret_cast<LPCSTR>(RVAToAddr(*middle)); - - // This may be called by sandbox before MSVCRT dll loads, so can't use - // CRT function here. - cmp = StrCmpByByte(function_name, name); - - if (cmp == 0) { - lower = middle; - break; - } - - if (cmp > 0) - lower = middle + 1; - else - upper = middle; - } - - if (cmp != 0) - return false; - - PWORD ordinals = - reinterpret_cast<PWORD>(RVAToAddr(exports->AddressOfNameOrdinals)); - - *ordinal = ordinals[lower - names] + static_cast<WORD>(exports->Base); - } - - return true; -} - -bool PEImage::EnumSections(EnumSectionsFunction callback, PVOID cookie) const { - PIMAGE_NT_HEADERS nt_headers = GetNTHeaders(); - UINT num_sections = nt_headers->FileHeader.NumberOfSections; - PIMAGE_SECTION_HEADER section = GetSectionHeader(0); - - for (UINT i = 0; i < num_sections; i++, section++) { - PVOID section_start = RVAToAddr(section->VirtualAddress); - DWORD size = section->Misc.VirtualSize; - - if (!callback(*this, section, section_start, size, cookie)) - return false; - } - - return true; -} - -bool PEImage::EnumExports(EnumExportsFunction callback, PVOID cookie) const { - PVOID directory = GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_EXPORT); - DWORD size = GetImageDirectoryEntrySize(IMAGE_DIRECTORY_ENTRY_EXPORT); - - // Check if there are any exports at all. - if (NULL == directory || 0 == size) - return true; - - PIMAGE_EXPORT_DIRECTORY exports = - reinterpret_cast<PIMAGE_EXPORT_DIRECTORY>(directory); - UINT ordinal_base = exports->Base; - UINT num_funcs = exports->NumberOfFunctions; - UINT num_names = exports->NumberOfNames; - PDWORD functions = - reinterpret_cast<PDWORD>(RVAToAddr(exports->AddressOfFunctions)); - PDWORD names = reinterpret_cast<PDWORD>(RVAToAddr(exports->AddressOfNames)); - PWORD ordinals = - reinterpret_cast<PWORD>(RVAToAddr(exports->AddressOfNameOrdinals)); - - for (UINT count = 0; count < num_funcs; count++) { - PVOID func = RVAToAddr(functions[count]); - if (NULL == func) - continue; - - // Check for a name. - LPCSTR name = NULL; - UINT hint; - for (hint = 0; hint < num_names; hint++) { - if (ordinals[hint] == count) { - name = reinterpret_cast<LPCSTR>(RVAToAddr(names[hint])); - break; - } - } - - if (name == NULL) - hint = 0; - - // Check for forwarded exports. - LPCSTR forward = NULL; - if (reinterpret_cast<char*>(func) >= reinterpret_cast<char*>(directory) && - reinterpret_cast<char*>(func) <= - reinterpret_cast<char*>(directory) + size) { - forward = reinterpret_cast<LPCSTR>(func); - func = 0; - } - - if (!callback(*this, ordinal_base + count, hint, name, func, forward, - cookie)) - return false; - } - - return true; -} - -bool PEImage::EnumRelocs(EnumRelocsFunction callback, PVOID cookie) const { - PVOID directory = GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_BASERELOC); - DWORD size = GetImageDirectoryEntrySize(IMAGE_DIRECTORY_ENTRY_BASERELOC); - PIMAGE_BASE_RELOCATION base = - reinterpret_cast<PIMAGE_BASE_RELOCATION>(directory); - - if (!directory) - return true; - - while (size >= sizeof(IMAGE_BASE_RELOCATION) && base->SizeOfBlock && - size >= base->SizeOfBlock) { - PWORD reloc = reinterpret_cast<PWORD>(base + 1); - UINT num_relocs = - (base->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD); - - for (UINT i = 0; i < num_relocs; i++, reloc++) { - WORD type = *reloc >> 12; - PVOID address = RVAToAddr(base->VirtualAddress + (*reloc & 0x0FFF)); - - if (!callback(*this, type, address, cookie)) - return false; - } - - size -= base->SizeOfBlock; - base = reinterpret_cast<PIMAGE_BASE_RELOCATION>( - reinterpret_cast<char*>(base) + base->SizeOfBlock); - } - - return true; -} - -bool PEImage::EnumImportChunks(EnumImportChunksFunction callback, - PVOID cookie) const { - DWORD size = GetImageDirectoryEntrySize(IMAGE_DIRECTORY_ENTRY_IMPORT); - PIMAGE_IMPORT_DESCRIPTOR import = GetFirstImportChunk(); - - if (import == NULL || size < sizeof(IMAGE_IMPORT_DESCRIPTOR)) - return true; - - for (; import->FirstThunk; import++) { - LPCSTR module_name = reinterpret_cast<LPCSTR>(RVAToAddr(import->Name)); - PIMAGE_THUNK_DATA name_table = reinterpret_cast<PIMAGE_THUNK_DATA>( - RVAToAddr(import->OriginalFirstThunk)); - PIMAGE_THUNK_DATA iat = - reinterpret_cast<PIMAGE_THUNK_DATA>(RVAToAddr(import->FirstThunk)); - - if (!callback(*this, module_name, name_table, iat, cookie)) - return false; - } - - return true; -} - -bool PEImage::EnumOneImportChunk(EnumImportsFunction callback, - LPCSTR module_name, - PIMAGE_THUNK_DATA name_table, - PIMAGE_THUNK_DATA iat, - PVOID cookie) const { - if (NULL == name_table) - return false; - - for (; name_table && name_table->u1.Ordinal; name_table++, iat++) { - LPCSTR name = NULL; - WORD ordinal = 0; - WORD hint = 0; - - if (IMAGE_SNAP_BY_ORDINAL(name_table->u1.Ordinal)) { - ordinal = static_cast<WORD>(IMAGE_ORDINAL32(name_table->u1.Ordinal)); - } else { - PIMAGE_IMPORT_BY_NAME import = reinterpret_cast<PIMAGE_IMPORT_BY_NAME>( - RVAToAddr(name_table->u1.ForwarderString)); - - hint = import->Hint; - name = reinterpret_cast<LPCSTR>(&import->Name); - } - - if (!callback(*this, module_name, ordinal, name, hint, iat, cookie)) - return false; - } - - return true; -} - -bool PEImage::EnumAllImports(EnumImportsFunction callback, PVOID cookie) const { - EnumAllImportsStorage temp = {callback, cookie}; - return EnumImportChunks(ProcessImportChunk, &temp); -} - -bool PEImage::EnumDelayImportChunks(EnumDelayImportChunksFunction callback, - PVOID cookie) const { - PVOID directory = - GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT); - DWORD size = GetImageDirectoryEntrySize(IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT); - PImgDelayDescr delay_descriptor = reinterpret_cast<PImgDelayDescr>(directory); - - if (directory == NULL || size == 0) - return true; - - for (; delay_descriptor->rvaHmod; delay_descriptor++) { - PIMAGE_THUNK_DATA name_table; - PIMAGE_THUNK_DATA iat; - LPCSTR module_name; - - // check if VC7-style imports, using RVAs instead of - // VC6-style addresses. - bool rvas = (delay_descriptor->grAttrs & dlattrRva) != 0; - - if (rvas) { - module_name = - reinterpret_cast<LPCSTR>(RVAToAddr(delay_descriptor->rvaDLLName)); - name_table = reinterpret_cast<PIMAGE_THUNK_DATA>( - RVAToAddr(delay_descriptor->rvaINT)); - iat = reinterpret_cast<PIMAGE_THUNK_DATA>( - RVAToAddr(delay_descriptor->rvaIAT)); - } else { - // Values in IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT are 32-bit, even on 64-bit - // platforms. See section 4.8 of PECOFF image spec rev 8.3. - module_name = reinterpret_cast<LPCSTR>( - static_cast<uintptr_t>(delay_descriptor->rvaDLLName)); - name_table = reinterpret_cast<PIMAGE_THUNK_DATA>( - static_cast<uintptr_t>(delay_descriptor->rvaINT)); - iat = reinterpret_cast<PIMAGE_THUNK_DATA>( - static_cast<uintptr_t>(delay_descriptor->rvaIAT)); - } - - if (!callback(*this, delay_descriptor, module_name, name_table, iat, - cookie)) - return false; - } - - return true; -} - -bool PEImage::EnumOneDelayImportChunk(EnumImportsFunction callback, - PImgDelayDescr delay_descriptor, - LPCSTR module_name, - PIMAGE_THUNK_DATA name_table, - PIMAGE_THUNK_DATA iat, - PVOID cookie) const { - for (; name_table->u1.Ordinal; name_table++, iat++) { - LPCSTR name = NULL; - WORD ordinal = 0; - WORD hint = 0; - - if (IMAGE_SNAP_BY_ORDINAL(name_table->u1.Ordinal)) { - ordinal = static_cast<WORD>(IMAGE_ORDINAL32(name_table->u1.Ordinal)); - } else { - PIMAGE_IMPORT_BY_NAME import; - bool rvas = (delay_descriptor->grAttrs & dlattrRva) != 0; - - if (rvas) { - import = reinterpret_cast<PIMAGE_IMPORT_BY_NAME>( - RVAToAddr(name_table->u1.ForwarderString)); - } else { - import = reinterpret_cast<PIMAGE_IMPORT_BY_NAME>( - name_table->u1.ForwarderString); - } - - hint = import->Hint; - name = reinterpret_cast<LPCSTR>(&import->Name); - } - - if (!callback(*this, module_name, ordinal, name, hint, iat, cookie)) - return false; - } - - return true; -} - -bool PEImage::EnumAllDelayImports(EnumImportsFunction callback, - PVOID cookie) const { - EnumAllImportsStorage temp = {callback, cookie}; - return EnumDelayImportChunks(ProcessDelayImportChunk, &temp); -} - -bool PEImage::VerifyMagic() const { - PIMAGE_DOS_HEADER dos_header = GetDosHeader(); - - if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) - return false; - - PIMAGE_NT_HEADERS nt_headers = GetNTHeaders(); - - if (nt_headers->Signature != IMAGE_NT_SIGNATURE) - return false; - - if (nt_headers->FileHeader.SizeOfOptionalHeader != - sizeof(IMAGE_OPTIONAL_HEADER)) - return false; - - if (nt_headers->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC) - return false; - - return true; -} - -bool PEImage::ImageRVAToOnDiskOffset(DWORD rva, DWORD* on_disk_offset) const { - LPVOID address = RVAToAddr(rva); - return ImageAddrToOnDiskOffset(address, on_disk_offset); -} - -bool PEImage::ImageAddrToOnDiskOffset(LPVOID address, - DWORD* on_disk_offset) const { - if (NULL == address) - return false; - - // Get the section that this address belongs to. - PIMAGE_SECTION_HEADER section_header = GetImageSectionFromAddr(address); - if (NULL == section_header) - return false; - - // Don't follow the virtual RVAToAddr, use the one on the base. - DWORD offset_within_section = - static_cast<DWORD>(reinterpret_cast<uintptr_t>(address)) - - static_cast<DWORD>(reinterpret_cast<uintptr_t>( - PEImage::RVAToAddr(section_header->VirtualAddress))); - - *on_disk_offset = section_header->PointerToRawData + offset_within_section; - return true; -} - -PVOID PEImage::RVAToAddr(DWORD rva) const { - if (rva == 0) - return NULL; - - return reinterpret_cast<char*>(module_) + rva; -} - -PVOID PEImageAsData::RVAToAddr(DWORD rva) const { - if (rva == 0) - return NULL; - - PVOID in_memory = PEImage::RVAToAddr(rva); - DWORD disk_offset; - - if (!ImageAddrToOnDiskOffset(in_memory, &disk_offset)) - return NULL; - - return PEImage::RVAToAddr(disk_offset); -} - -} // namespace win -} // namespace base
diff --git a/base/win/pe_image.h b/base/win/pe_image.h deleted file mode 100644 index 7766b49..0000000 --- a/base/win/pe_image.h +++ /dev/null
@@ -1,281 +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. - -// This file was adapted from GreenBorder's Code. -// To understand what this class is about (for other than well known functions -// as GetProcAddress), a good starting point is "An In-Depth Look into the -// Win32 Portable Executable File Format" by Matt Pietrek: -// http://msdn.microsoft.com/msdnmag/issues/02/02/PE/default.aspx - -#ifndef BASE_WIN_PE_IMAGE_H_ -#define BASE_WIN_PE_IMAGE_H_ - -#include <windows.h> - -#if defined(_WIN32_WINNT_WIN8) -// The Windows 8 SDK defines FACILITY_VISUALCPP in winerror.h. -#undef FACILITY_VISUALCPP -#endif -#include <DelayIMP.h> - -namespace base { -namespace win { - -// This class is a wrapper for the Portable Executable File Format (PE). -// Its main purpose is to provide an easy way to work with imports and exports -// from a file, mapped in memory as image. -class PEImage { - public: - // Callback to enumerate sections. - // cookie is the value passed to the enumerate method. - // Returns true to continue the enumeration. - typedef bool (*EnumSectionsFunction)(const PEImage& image, - PIMAGE_SECTION_HEADER header, - PVOID section_start, - DWORD section_size, - PVOID cookie); - - // Callback to enumerate exports. - // function is the actual address of the symbol. If forward is not null, it - // contains the dll and symbol to forward this export to. cookie is the value - // passed to the enumerate method. - // Returns true to continue the enumeration. - typedef bool (*EnumExportsFunction)(const PEImage& image, - DWORD ordinal, - DWORD hint, - LPCSTR name, - PVOID function, - LPCSTR forward, - PVOID cookie); - - // Callback to enumerate import blocks. - // name_table and iat point to the imports name table and address table for - // this block. cookie is the value passed to the enumerate method. - // Returns true to continue the enumeration. - typedef bool (*EnumImportChunksFunction)(const PEImage& image, - LPCSTR module, - PIMAGE_THUNK_DATA name_table, - PIMAGE_THUNK_DATA iat, - PVOID cookie); - - // Callback to enumerate imports. - // module is the dll that exports this symbol. cookie is the value passed to - // the enumerate method. - // Returns true to continue the enumeration. - typedef bool (*EnumImportsFunction)(const PEImage& image, - LPCSTR module, - DWORD ordinal, - LPCSTR name, - DWORD hint, - PIMAGE_THUNK_DATA iat, - PVOID cookie); - - // Callback to enumerate delayed import blocks. - // module is the dll that exports this block of symbols. cookie is the value - // passed to the enumerate method. - // Returns true to continue the enumeration. - typedef bool (*EnumDelayImportChunksFunction)(const PEImage& image, - PImgDelayDescr delay_descriptor, - LPCSTR module, - PIMAGE_THUNK_DATA name_table, - PIMAGE_THUNK_DATA iat, - PVOID cookie); - - // Callback to enumerate relocations. - // cookie is the value passed to the enumerate method. - // Returns true to continue the enumeration. - typedef bool (*EnumRelocsFunction)(const PEImage& image, - WORD type, - PVOID address, - PVOID cookie); - - explicit PEImage(HMODULE module) : module_(module) {} - explicit PEImage(const void* module) { - module_ = reinterpret_cast<HMODULE>(const_cast<void*>(module)); - } - - virtual ~PEImage() {} - - // Gets the HMODULE for this object. - HMODULE module() const; - - // Sets this object's HMODULE. - void set_module(HMODULE module); - - // Checks if this symbol is actually an ordinal. - static bool IsOrdinal(LPCSTR name); - - // Converts a named symbol to the corresponding ordinal. - static WORD ToOrdinal(LPCSTR name); - - // Returns the DOS_HEADER for this PE. - PIMAGE_DOS_HEADER GetDosHeader() const; - - // Returns the NT_HEADER for this PE. - PIMAGE_NT_HEADERS GetNTHeaders() const; - - // Returns number of sections of this PE. - WORD GetNumSections() const; - - // Returns the header for a given section. - // returns NULL if there is no such section. - PIMAGE_SECTION_HEADER GetSectionHeader(UINT section) const; - - // Returns the size of a given directory entry. - DWORD GetImageDirectoryEntrySize(UINT directory) const; - - // Returns the address of a given directory entry. - PVOID GetImageDirectoryEntryAddr(UINT directory) const; - - // Returns the section header for a given address. - // Use: s = image.GetImageSectionFromAddr(a); - // Post: 's' is the section header of the section that contains 'a' - // or NULL if there is no such section. - PIMAGE_SECTION_HEADER GetImageSectionFromAddr(PVOID address) const; - - // Returns the section header for a given section. - PIMAGE_SECTION_HEADER GetImageSectionHeaderByName(LPCSTR section_name) const; - - // Returns the first block of imports. - PIMAGE_IMPORT_DESCRIPTOR GetFirstImportChunk() const; - - // Returns the exports directory. - PIMAGE_EXPORT_DIRECTORY GetExportDirectory() const; - - // Returns the debug id (guid+age) and |pdb_filename|. Parameters are optional - // and can be null. |pdb_filename| is a direct reference to PEImage and - // doesn't not need to be freed. - bool GetDebugId(LPGUID guid, LPDWORD age, LPCSTR* pdb_filename) const; - - // Returns a given export entry. - // Use: e = image.GetExportEntry(f); - // Pre: 'f' is either a zero terminated string or ordinal - // Post: 'e' is a pointer to the export directory entry - // that contains 'f's export RVA, or NULL if 'f' - // is not exported from this image - PDWORD GetExportEntry(LPCSTR name) const; - - // Returns the address for a given exported symbol. - // Use: p = image.GetProcAddress(f); - // Pre: 'f' is either a zero terminated string or ordinal. - // Post: if 'f' is a non-forwarded export from image, 'p' is - // the exported function. If 'f' is a forwarded export - // then p is the special value -1. In this case - // RVAToAddr(*GetExportEntry) can be used to resolve - // the string that describes the forward. - FARPROC GetProcAddress(LPCSTR function_name) const; - - // Retrieves the ordinal for a given exported symbol. - // Returns true if the symbol was found. - bool GetProcOrdinal(LPCSTR function_name, WORD* ordinal) const; - - // Enumerates PE sections. - // cookie is a generic cookie to pass to the callback. - // Returns true on success. - bool EnumSections(EnumSectionsFunction callback, PVOID cookie) const; - - // Enumerates PE exports. - // cookie is a generic cookie to pass to the callback. - // Returns true on success. - bool EnumExports(EnumExportsFunction callback, PVOID cookie) const; - - // Enumerates PE imports. - // cookie is a generic cookie to pass to the callback. - // Returns true on success. - bool EnumAllImports(EnumImportsFunction callback, PVOID cookie) const; - - // Enumerates PE import blocks. - // cookie is a generic cookie to pass to the callback. - // Returns true on success. - bool EnumImportChunks(EnumImportChunksFunction callback, PVOID cookie) const; - - // Enumerates the imports from a single PE import block. - // cookie is a generic cookie to pass to the callback. - // Returns true on success. - bool EnumOneImportChunk(EnumImportsFunction callback, - LPCSTR module_name, - PIMAGE_THUNK_DATA name_table, - PIMAGE_THUNK_DATA iat, - PVOID cookie) const; - - // Enumerates PE delay imports. - // cookie is a generic cookie to pass to the callback. - // Returns true on success. - bool EnumAllDelayImports(EnumImportsFunction callback, PVOID cookie) const; - - // Enumerates PE delay import blocks. - // cookie is a generic cookie to pass to the callback. - // Returns true on success. - bool EnumDelayImportChunks(EnumDelayImportChunksFunction callback, - PVOID cookie) const; - - // Enumerates imports from a single PE delay import block. - // cookie is a generic cookie to pass to the callback. - // Returns true on success. - bool EnumOneDelayImportChunk(EnumImportsFunction callback, - PImgDelayDescr delay_descriptor, - LPCSTR module_name, - PIMAGE_THUNK_DATA name_table, - PIMAGE_THUNK_DATA iat, - PVOID cookie) const; - - // Enumerates PE relocation entries. - // cookie is a generic cookie to pass to the callback. - // Returns true on success. - bool EnumRelocs(EnumRelocsFunction callback, PVOID cookie) const; - - // Verifies the magic values on the PE file. - // Returns true if all values are correct. - bool VerifyMagic() const; - - // Converts an rva value to the appropriate address. - virtual PVOID RVAToAddr(DWORD rva) const; - - // Converts an rva value to an offset on disk. - // Returns true on success. - bool ImageRVAToOnDiskOffset(DWORD rva, DWORD* on_disk_offset) const; - - // Converts an address to an offset on disk. - // Returns true on success. - bool ImageAddrToOnDiskOffset(LPVOID address, DWORD* on_disk_offset) const; - - private: - HMODULE module_; -}; - -// This class is an extension to the PEImage class that allows working with PE -// files mapped as data instead of as image file. -class PEImageAsData : public PEImage { - public: - explicit PEImageAsData(HMODULE hModule) : PEImage(hModule) {} - - PVOID RVAToAddr(DWORD rva) const override; -}; - -inline bool PEImage::IsOrdinal(LPCSTR name) { - return reinterpret_cast<uintptr_t>(name) <= 0xFFFF; -} - -inline WORD PEImage::ToOrdinal(LPCSTR name) { - return static_cast<WORD>(reinterpret_cast<intptr_t>(name)); -} - -inline HMODULE PEImage::module() const { - return module_; -} - -inline PIMAGE_IMPORT_DESCRIPTOR PEImage::GetFirstImportChunk() const { - return reinterpret_cast<PIMAGE_IMPORT_DESCRIPTOR>( - GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_IMPORT)); -} - -inline PIMAGE_EXPORT_DIRECTORY PEImage::GetExportDirectory() const { - return reinterpret_cast<PIMAGE_EXPORT_DIRECTORY>( - GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_EXPORT)); -} - -} // namespace win -} // namespace base - -#endif // BASE_WIN_PE_IMAGE_H_
diff --git a/base/win/pe_image_test.cc b/base/win/pe_image_test.cc deleted file mode 100644 index 8591495..0000000 --- a/base/win/pe_image_test.cc +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <windows.h> - -#include <cfgmgr32.h> -#include <shellapi.h> - -#pragma comment(linker, "/export:FwdExport=KERNEL32.CreateFileA") - -extern "C" { - -__declspec(dllexport) void ExportFunc1() { - // Call into user32.dll. - HWND dummy = GetDesktopWindow(); - SetWindowTextA(dummy, "dummy"); -} - -__declspec(dllexport) void ExportFunc2() { - // Call into cfgmgr32.dll. - CM_MapCrToWin32Err(CR_SUCCESS, ERROR_SUCCESS); - - // Call into shell32.dll. - SHFILEOPSTRUCT file_operation = {0}; - SHFileOperation(&file_operation); - - // Call into kernel32.dll. - HANDLE h = CreateEvent(NULL, FALSE, FALSE, NULL); - CloseHandle(h); -} - -} // extern "C"
diff --git a/base/win/process_startup_helper.cc b/base/win/process_startup_helper.cc deleted file mode 100644 index 347db71..0000000 --- a/base/win/process_startup_helper.cc +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright (c) 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/win/process_startup_helper.h" - -#include <crtdbg.h> -#include <new.h> -#include <stdlib.h> - -namespace { - -#pragma optimize("", off) -// Handlers for invalid parameter and pure call. They generate a breakpoint to -// tell breakpad that it needs to dump the process. -void InvalidParameter(const wchar_t* expression, - const wchar_t* function, - const wchar_t* file, - unsigned int line, - uintptr_t reserved) { - __debugbreak(); - _exit(1); -} - -void PureCall() { - __debugbreak(); - _exit(1); -} -#pragma optimize("", on) - -} // namespace - -namespace base { -namespace win { - -// Register the invalid param handler and pure call handler to be able to -// notify breakpad when it happens. -void RegisterInvalidParamHandler() { - _set_invalid_parameter_handler(InvalidParameter); - _set_purecall_handler(PureCall); -} - -void SetupCRT(const CommandLine& command_line) { -#if defined(_CRTDBG_MAP_ALLOC) - _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); - _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); -#else - _CrtSetReportMode(_CRT_ASSERT, 0); -#endif -} - -} // namespace win -} // namespace base
diff --git a/base/win/process_startup_helper.h b/base/win/process_startup_helper.h deleted file mode 100644 index c579433..0000000 --- a/base/win/process_startup_helper.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright (c) 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_WIN_PROCESS_STARTUP_HELPER_H_ -#define BASE_WIN_PROCESS_STARTUP_HELPER_H_ - -namespace base { - -class CommandLine; - -namespace win { - -// Register the invalid param handler and pure call handler to be able to -// notify breakpad when it happens. -void RegisterInvalidParamHandler(); - -// Sets up the CRT's debugging macros to output to stdout. -void SetupCRT(const CommandLine& command_line); - -} // namespace win -} // namespace base - -#endif // BASE_WIN_PROCESS_STARTUP_HELPER_H_
diff --git a/base/win/registry.cc b/base/win/registry.cc index 1ca839d..e07820b 100644 --- a/base/win/registry.cc +++ b/base/win/registry.cc
@@ -11,7 +11,6 @@ #include "base/logging.h" #include "base/macros.h" #include "base/strings/string_util.h" -#include "base/win/windows_version.h" namespace base { namespace win {
diff --git a/base/win/resource_util.cc b/base/win/resource_util.cc deleted file mode 100644 index b964aee..0000000 --- a/base/win/resource_util.cc +++ /dev/null
@@ -1,51 +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/win/resource_util.h" -#include "base/logging.h" - -namespace base { -namespace win { - -bool GetResourceFromModule(HMODULE module, - int resource_id, - LPCTSTR resource_type, - void** data, - size_t* length) { - if (!module) - return false; - - if (!IS_INTRESOURCE(resource_id)) { - NOTREACHED(); - return false; - } - - HRSRC hres_info = - FindResource(module, MAKEINTRESOURCE(resource_id), resource_type); - if (NULL == hres_info) - return false; - - DWORD data_size = SizeofResource(module, hres_info); - HGLOBAL hres = LoadResource(module, hres_info); - if (!hres) - return false; - - void* resource = LockResource(hres); - if (!resource) - return false; - - *data = resource; - *length = static_cast<size_t>(data_size); - return true; -} - -bool GetDataResourceFromModule(HMODULE module, - int resource_id, - void** data, - size_t* length) { - return GetResourceFromModule(module, resource_id, L"BINDATA", data, length); -} - -} // namespace win -} // namespace base
diff --git a/base/win/resource_util.h b/base/win/resource_util.h deleted file mode 100644 index b4473fd..0000000 --- a/base/win/resource_util.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file contains utility functions for accessing resources in external -// files (DLLs) or embedded in the executable itself. - -#ifndef BASE_WIN_RESOURCE_UTIL_H_ -#define BASE_WIN_RESOURCE_UTIL_H_ - -#include <stddef.h> -#include <windows.h> - -namespace base { -namespace win { - -// Function for getting a data resource of the specified |resource_type| from -// a dll. Some resources are optional, especially in unit tests, so this -// returns false but doesn't raise an error if the resource can't be loaded. -bool GetResourceFromModule(HMODULE module, - int resource_id, - LPCTSTR resource_type, - void** data, - size_t* length); - -// Function for getting a data resource (BINDATA) from a dll. Some -// resources are optional, especially in unit tests, so this returns false -// but doesn't raise an error if the resource can't be loaded. -bool GetDataResourceFromModule(HMODULE module, - int resource_id, - void** data, - size_t* length); - -} // namespace win -} // namespace base - -#endif // BASE_WIN_RESOURCE_UTIL_H_
diff --git a/base/win/shortcut.cc b/base/win/shortcut.cc deleted file mode 100644 index fcd8a70..0000000 --- a/base/win/shortcut.cc +++ /dev/null
@@ -1,364 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/win/shortcut.h" - -#include <objbase.h> -#include <propkey.h> -#include <shellapi.h> -#include <shlobj.h> -#include <wrl/client.h> - -#include "base/files/file_util.h" -#include "base/win/scoped_propvariant.h" -#include "base/win/win_util.h" -#include "base/win/windows_version.h" - -namespace base { -namespace win { - -namespace { - -using Microsoft::WRL::ComPtr; - -// Initializes |i_shell_link| and |i_persist_file| (releasing them first if they -// are already initialized). -// If |shortcut| is not NULL, loads |shortcut| into |i_persist_file|. -// If any of the above steps fail, both |i_shell_link| and |i_persist_file| will -// be released. -void InitializeShortcutInterfaces(const wchar_t* shortcut, - ComPtr<IShellLink>* i_shell_link, - ComPtr<IPersistFile>* i_persist_file) { - i_shell_link->Reset(); - i_persist_file->Reset(); - if (FAILED(::CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, - IID_PPV_ARGS(i_shell_link->GetAddressOf()))) || - FAILED(i_shell_link->CopyTo(i_persist_file->GetAddressOf())) || - (shortcut && FAILED((*i_persist_file)->Load(shortcut, STGM_READWRITE)))) { - i_shell_link->Reset(); - i_persist_file->Reset(); - } -} - -} // namespace - -ShortcutProperties::ShortcutProperties() - : icon_index(-1), dual_mode(false), options(0U) {} - -ShortcutProperties::ShortcutProperties(const ShortcutProperties& other) = - default; - -ShortcutProperties::~ShortcutProperties() {} - -bool CreateOrUpdateShortcutLink(const FilePath& shortcut_path, - const ShortcutProperties& properties, - ShortcutOperation operation) { - // A target is required unless |operation| is SHORTCUT_UPDATE_EXISTING. - if (operation != SHORTCUT_UPDATE_EXISTING && - !(properties.options & ShortcutProperties::PROPERTIES_TARGET)) { - NOTREACHED(); - return false; - } - - bool shortcut_existed = PathExists(shortcut_path); - - // Interfaces to the old shortcut when replacing an existing shortcut. - ComPtr<IShellLink> old_i_shell_link; - ComPtr<IPersistFile> old_i_persist_file; - - // Interfaces to the shortcut being created/updated. - ComPtr<IShellLink> i_shell_link; - ComPtr<IPersistFile> i_persist_file; - switch (operation) { - case SHORTCUT_CREATE_ALWAYS: - InitializeShortcutInterfaces(NULL, &i_shell_link, &i_persist_file); - break; - case SHORTCUT_UPDATE_EXISTING: - InitializeShortcutInterfaces(shortcut_path.value().c_str(), &i_shell_link, - &i_persist_file); - break; - case SHORTCUT_REPLACE_EXISTING: - InitializeShortcutInterfaces(shortcut_path.value().c_str(), - &old_i_shell_link, &old_i_persist_file); - // Confirm |shortcut_path| exists and is a shortcut by verifying - // |old_i_persist_file| was successfully initialized in the call above. If - // so, initialize the interfaces to begin writing a new shortcut (to - // overwrite the current one if successful). - if (old_i_persist_file.Get()) - InitializeShortcutInterfaces(NULL, &i_shell_link, &i_persist_file); - break; - default: - NOTREACHED(); - } - - // Return false immediately upon failure to initialize shortcut interfaces. - if (!i_persist_file.Get()) - return false; - - if ((properties.options & ShortcutProperties::PROPERTIES_TARGET) && - FAILED(i_shell_link->SetPath(properties.target.value().c_str()))) { - return false; - } - - if ((properties.options & ShortcutProperties::PROPERTIES_WORKING_DIR) && - FAILED(i_shell_link->SetWorkingDirectory( - properties.working_dir.value().c_str()))) { - return false; - } - - if (properties.options & ShortcutProperties::PROPERTIES_ARGUMENTS) { - if (FAILED(i_shell_link->SetArguments(properties.arguments.c_str()))) - return false; - } else if (old_i_persist_file.Get()) { - wchar_t current_arguments[MAX_PATH] = {0}; - if (SUCCEEDED( - old_i_shell_link->GetArguments(current_arguments, MAX_PATH))) { - i_shell_link->SetArguments(current_arguments); - } - } - - if ((properties.options & ShortcutProperties::PROPERTIES_DESCRIPTION) && - FAILED(i_shell_link->SetDescription(properties.description.c_str()))) { - return false; - } - - if ((properties.options & ShortcutProperties::PROPERTIES_ICON) && - FAILED(i_shell_link->SetIconLocation(properties.icon.value().c_str(), - properties.icon_index))) { - return false; - } - - bool has_app_id = - (properties.options & ShortcutProperties::PROPERTIES_APP_ID) != 0; - bool has_dual_mode = - (properties.options & ShortcutProperties::PROPERTIES_DUAL_MODE) != 0; - bool has_toast_activator_clsid = - (properties.options & - ShortcutProperties::PROPERTIES_TOAST_ACTIVATOR_CLSID) != 0; - if (has_app_id || has_dual_mode || has_toast_activator_clsid) { - ComPtr<IPropertyStore> property_store; - if (FAILED(i_shell_link.CopyTo(property_store.GetAddressOf())) || - !property_store.Get()) - return false; - - if (has_app_id && !SetAppIdForPropertyStore(property_store.Get(), - properties.app_id.c_str())) { - return false; - } - if (has_dual_mode && !SetBooleanValueForPropertyStore( - property_store.Get(), PKEY_AppUserModel_IsDualMode, - properties.dual_mode)) { - return false; - } - if (has_toast_activator_clsid && - !SetClsidForPropertyStore(property_store.Get(), - PKEY_AppUserModel_ToastActivatorCLSID, - properties.toast_activator_clsid)) { - return false; - } - } - - // Release the interfaces to the old shortcut to make sure it doesn't prevent - // overwriting it if needed. - old_i_persist_file.Reset(); - old_i_shell_link.Reset(); - - HRESULT result = i_persist_file->Save(shortcut_path.value().c_str(), TRUE); - - // Release the interfaces in case the SHChangeNotify call below depends on - // the operations above being fully completed. - i_persist_file.Reset(); - i_shell_link.Reset(); - - // If we successfully created/updated the icon, notify the shell that we have - // done so. - const bool succeeded = SUCCEEDED(result); - if (succeeded) { - if (shortcut_existed) { - // TODO(gab): SHCNE_UPDATEITEM might be sufficient here; further testing - // required. - SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); - } else { - SHChangeNotify(SHCNE_CREATE, SHCNF_PATH, shortcut_path.value().c_str(), - NULL); - } - } - - return succeeded; -} - -bool ResolveShortcutProperties(const FilePath& shortcut_path, - uint32_t options, - ShortcutProperties* properties) { - DCHECK(options && properties); - - if (options & ~ShortcutProperties::PROPERTIES_ALL) - NOTREACHED() << "Unhandled property is used."; - - ComPtr<IShellLink> i_shell_link; - - // Get pointer to the IShellLink interface. - if (FAILED(::CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, - IID_PPV_ARGS(&i_shell_link)))) { - return false; - } - - ComPtr<IPersistFile> persist; - // Query IShellLink for the IPersistFile interface. - if (FAILED(i_shell_link.CopyTo(persist.GetAddressOf()))) - return false; - - // Load the shell link. - if (FAILED(persist->Load(shortcut_path.value().c_str(), STGM_READ))) - return false; - - // Reset |properties|. - properties->options = 0; - - wchar_t temp[MAX_PATH]; - if (options & ShortcutProperties::PROPERTIES_TARGET) { - if (FAILED(i_shell_link->GetPath(temp, MAX_PATH, NULL, SLGP_UNCPRIORITY))) - return false; - properties->set_target(FilePath(temp)); - } - - if (options & ShortcutProperties::PROPERTIES_WORKING_DIR) { - if (FAILED(i_shell_link->GetWorkingDirectory(temp, MAX_PATH))) - return false; - properties->set_working_dir(FilePath(temp)); - } - - if (options & ShortcutProperties::PROPERTIES_ARGUMENTS) { - if (FAILED(i_shell_link->GetArguments(temp, MAX_PATH))) - return false; - properties->set_arguments(temp); - } - - if (options & ShortcutProperties::PROPERTIES_DESCRIPTION) { - // Note: description length constrained by MAX_PATH. - if (FAILED(i_shell_link->GetDescription(temp, MAX_PATH))) - return false; - properties->set_description(temp); - } - - if (options & ShortcutProperties::PROPERTIES_ICON) { - int temp_index; - if (FAILED(i_shell_link->GetIconLocation(temp, MAX_PATH, &temp_index))) - return false; - properties->set_icon(FilePath(temp), temp_index); - } - - if (options & (ShortcutProperties::PROPERTIES_APP_ID | - ShortcutProperties::PROPERTIES_DUAL_MODE | - ShortcutProperties::PROPERTIES_TOAST_ACTIVATOR_CLSID)) { - ComPtr<IPropertyStore> property_store; - if (FAILED(i_shell_link.CopyTo(property_store.GetAddressOf()))) - return false; - - if (options & ShortcutProperties::PROPERTIES_APP_ID) { - ScopedPropVariant pv_app_id; - if (property_store->GetValue(PKEY_AppUserModel_ID, pv_app_id.Receive()) != - S_OK) { - return false; - } - switch (pv_app_id.get().vt) { - case VT_EMPTY: - properties->set_app_id(L""); - break; - case VT_LPWSTR: - properties->set_app_id(pv_app_id.get().pwszVal); - break; - default: - NOTREACHED() << "Unexpected variant type: " << pv_app_id.get().vt; - return false; - } - } - - if (options & ShortcutProperties::PROPERTIES_DUAL_MODE) { - ScopedPropVariant pv_dual_mode; - if (property_store->GetValue(PKEY_AppUserModel_IsDualMode, - pv_dual_mode.Receive()) != S_OK) { - return false; - } - switch (pv_dual_mode.get().vt) { - case VT_EMPTY: - properties->set_dual_mode(false); - break; - case VT_BOOL: - properties->set_dual_mode(pv_dual_mode.get().boolVal == VARIANT_TRUE); - break; - default: - NOTREACHED() << "Unexpected variant type: " << pv_dual_mode.get().vt; - return false; - } - } - - if (options & ShortcutProperties::PROPERTIES_TOAST_ACTIVATOR_CLSID) { - ScopedPropVariant pv_toast_activator_clsid; - if (property_store->GetValue(PKEY_AppUserModel_ToastActivatorCLSID, - pv_toast_activator_clsid.Receive()) != - S_OK) { - return false; - } - switch (pv_toast_activator_clsid.get().vt) { - case VT_EMPTY: - properties->set_toast_activator_clsid(CLSID_NULL); - break; - case VT_CLSID: - properties->set_toast_activator_clsid( - *(pv_toast_activator_clsid.get().puuid)); - break; - default: - NOTREACHED() << "Unexpected variant type: " - << pv_toast_activator_clsid.get().vt; - return false; - } - } - } - - return true; -} - -bool ResolveShortcut(const FilePath& shortcut_path, - FilePath* target_path, - string16* args) { - uint32_t options = 0; - if (target_path) - options |= ShortcutProperties::PROPERTIES_TARGET; - if (args) - options |= ShortcutProperties::PROPERTIES_ARGUMENTS; - DCHECK(options); - - ShortcutProperties properties; - if (!ResolveShortcutProperties(shortcut_path, options, &properties)) - return false; - - if (target_path) - *target_path = properties.target; - if (args) - *args = properties.arguments; - return true; -} - -bool CanPinShortcutToTaskbar() { - // "Pin to taskbar" stopped being supported in Windows 10. - return GetVersion() < VERSION_WIN10; -} - -bool PinShortcutToTaskbar(const FilePath& shortcut) { - DCHECK(CanPinShortcutToTaskbar()); - - intptr_t result = reinterpret_cast<intptr_t>(ShellExecute( - NULL, L"taskbarpin", shortcut.value().c_str(), NULL, NULL, 0)); - return result > 32; -} - -bool UnpinShortcutFromTaskbar(const FilePath& shortcut) { - intptr_t result = reinterpret_cast<intptr_t>(ShellExecute( - NULL, L"taskbarunpin", shortcut.value().c_str(), NULL, NULL, 0)); - return result > 32; -} - -} // namespace win -} // namespace base
diff --git a/base/win/shortcut.h b/base/win/shortcut.h deleted file mode 100644 index d5bcff7..0000000 --- a/base/win/shortcut.h +++ /dev/null
@@ -1,179 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_WIN_SHORTCUT_H_ -#define BASE_WIN_SHORTCUT_H_ - -#include <stdint.h> -#include <windows.h> - -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/strings/string16.h" - -namespace base { -namespace win { - -enum ShortcutOperation { - // Create a new shortcut (overwriting if necessary). - SHORTCUT_CREATE_ALWAYS = 0, - // Overwrite an existing shortcut (fails if the shortcut doesn't exist). - // If the arguments are not specified on the new shortcut, keep the old - // shortcut's arguments. - SHORTCUT_REPLACE_EXISTING, - // Update specified properties only on an existing shortcut. - SHORTCUT_UPDATE_EXISTING, -}; - -// Properties for shortcuts. Properties set will be applied to the shortcut on -// creation/update, others will be ignored. -// Callers are encouraged to use the setters provided which take care of -// setting |options| as desired. -struct ShortcutProperties { - enum IndividualProperties { - PROPERTIES_TARGET = 1U << 0, - PROPERTIES_WORKING_DIR = 1U << 1, - PROPERTIES_ARGUMENTS = 1U << 2, - PROPERTIES_DESCRIPTION = 1U << 3, - PROPERTIES_ICON = 1U << 4, - PROPERTIES_APP_ID = 1U << 5, - PROPERTIES_DUAL_MODE = 1U << 6, - PROPERTIES_TOAST_ACTIVATOR_CLSID = 1U << 7, - // Be sure to update the values below when adding a new property. - PROPERTIES_ALL = PROPERTIES_TARGET | PROPERTIES_WORKING_DIR | - PROPERTIES_ARGUMENTS | PROPERTIES_DESCRIPTION | - PROPERTIES_ICON | PROPERTIES_APP_ID | - PROPERTIES_DUAL_MODE | PROPERTIES_TOAST_ACTIVATOR_CLSID - }; - - ShortcutProperties(); - ShortcutProperties(const ShortcutProperties& other); - ~ShortcutProperties(); - - void set_target(const FilePath& target_in) { - target = target_in; - options |= PROPERTIES_TARGET; - } - - void set_working_dir(const FilePath& working_dir_in) { - working_dir = working_dir_in; - options |= PROPERTIES_WORKING_DIR; - } - - void set_arguments(const string16& arguments_in) { - // Size restriction as per MSDN at http://goo.gl/TJ7q5. - DCHECK(arguments_in.size() < MAX_PATH); - arguments = arguments_in; - options |= PROPERTIES_ARGUMENTS; - } - - void set_description(const string16& description_in) { - // Size restriction as per MSDN at http://goo.gl/OdNQq. - DCHECK(description_in.size() < MAX_PATH); - description = description_in; - options |= PROPERTIES_DESCRIPTION; - } - - void set_icon(const FilePath& icon_in, int icon_index_in) { - icon = icon_in; - icon_index = icon_index_in; - options |= PROPERTIES_ICON; - } - - void set_app_id(const string16& app_id_in) { - app_id = app_id_in; - options |= PROPERTIES_APP_ID; - } - - void set_dual_mode(bool dual_mode_in) { - dual_mode = dual_mode_in; - options |= PROPERTIES_DUAL_MODE; - } - - void set_toast_activator_clsid(const CLSID& toast_activator_clsid_in) { - toast_activator_clsid = toast_activator_clsid_in; - options |= PROPERTIES_TOAST_ACTIVATOR_CLSID; - } - - // The target to launch from this shortcut. This is mandatory when creating - // a shortcut. - FilePath target; - // The name of the working directory when launching the shortcut. - FilePath working_dir; - // The arguments to be applied to |target| when launching from this shortcut. - // The length of this string must be less than MAX_PATH. - string16 arguments; - // The localized description of the shortcut. - // The length of this string must be less than MAX_PATH. - string16 description; - // The path to the icon (can be a dll or exe, in which case |icon_index| is - // the resource id). - FilePath icon; - int icon_index; - // The app model id for the shortcut. - string16 app_id; - // Whether this is a dual mode shortcut (Win8+). - bool dual_mode; - // The CLSID of the COM object registered with the OS via the shortcut. This - // is for app activation via user interaction with a toast notification in the - // Action Center. (Win10 version 1607, build 14393, and beyond). - CLSID toast_activator_clsid; - // Bitfield made of IndividualProperties. Properties set in |options| will be - // set on the shortcut, others will be ignored. - uint32_t options; -}; - -// This method creates (or updates) a shortcut link at |shortcut_path| using the -// information given through |properties|. -// Ensure you have initialized COM before calling into this function. -// |operation|: a choice from the ShortcutOperation enum. -// If |operation| is SHORTCUT_REPLACE_EXISTING or SHORTCUT_UPDATE_EXISTING and -// |shortcut_path| does not exist, this method is a no-op and returns false. -bool CreateOrUpdateShortcutLink(const FilePath& shortcut_path, - const ShortcutProperties& properties, - ShortcutOperation operation); - -// Resolves Windows shortcut (.LNK file). -// This methods tries to resolve selected properties of a shortcut .LNK file. -// The path of the shortcut to resolve is in |shortcut_path|. |options| is a bit -// field composed of ShortcutProperties::IndividualProperties, to specify which -// properties to read. It should be non-0. The resulting data are read into -// |properties|, which must not be NULL. Note: PROPERTIES_TARGET will retrieve -// the target path as stored in the shortcut but won't attempt to resolve that -// path so it may not be valid. The function returns true if all requested -// properties are successfully read. Otherwise some reads have failed and -// intermediate values written to |properties| should be ignored. -bool ResolveShortcutProperties(const FilePath& shortcut_path, - uint32_t options, - ShortcutProperties* properties); - -// Resolves Windows shortcut (.LNK file). -// This is a wrapper to ResolveShortcutProperties() to handle the common use -// case of resolving target and arguments. |target_path| and |args| are -// optional output variables that are ignored if NULL (but at least one must be -// non-NULL). The function returns true if all requested fields are found -// successfully. Callers can safely use the same variable for both -// |shortcut_path| and |target_path|. -bool ResolveShortcut(const FilePath& shortcut_path, - FilePath* target_path, - string16* args); - -// Pin to taskbar is only supported on Windows 7 and Windows 8. Returns true on -// those platforms. -bool CanPinShortcutToTaskbar(); - -// Pins a shortcut to the taskbar on Windows 7 and 8. The |shortcut| file must -// already exist and be a shortcut that points to an executable. The app id of -// the shortcut is used to group windows and must be set correctly. -bool PinShortcutToTaskbar(const FilePath& shortcut); - -// Unpins a shortcut from the Windows 7+ taskbar. The |shortcut| must exist and -// already be pinned to the taskbar. The app id of the shortcut is used as the -// identifier for the taskbar item to remove and must be set correctly. -bool UnpinShortcutFromTaskbar(const FilePath& shortcut); - -} // namespace win -} // namespace base - -#endif // BASE_WIN_SHORTCUT_H_
diff --git a/base/win/win_client_metrics.h b/base/win/win_client_metrics.h deleted file mode 100644 index d63bf20..0000000 --- a/base/win/win_client_metrics.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file is separate from base/win/win_util.h to avoid pulling windows.h -// into too many translation units. - -#ifndef BASE_WIN_WIN_CLIENT_METRICS_H_ -#define BASE_WIN_WIN_CLIENT_METRICS_H_ - -#include <windows.h> - -// This is the same as NONCLIENTMETRICS except that the -// unused member |iPaddedBorderWidth| has been removed. -struct NONCLIENTMETRICS_XP { - UINT cbSize; - int iBorderWidth; - int iScrollWidth; - int iScrollHeight; - int iCaptionWidth; - int iCaptionHeight; - LOGFONTW lfCaptionFont; - int iSmCaptionWidth; - int iSmCaptionHeight; - LOGFONTW lfSmCaptionFont; - int iMenuWidth; - int iMenuHeight; - LOGFONTW lfMenuFont; - LOGFONTW lfStatusFont; - LOGFONTW lfMessageFont; -}; - -namespace base { -namespace win { - -void GetNonClientMetrics(NONCLIENTMETRICS_XP* metrics); - -} // namespace win -} // namespace base - -#endif // BASE_WIN_WIN_CLIENT_METRICS_H_
diff --git a/base/win/win_util.cc b/base/win/win_util.cc deleted file mode 100644 index d9efb6e..0000000 --- a/base/win/win_util.cc +++ /dev/null
@@ -1,392 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/win/win_util.h" - -#include <aclapi.h> -#include <cfgmgr32.h> -#include <initguid.h> -#include <powrprof.h> -#include <shobjidl.h> // Must be before propkey. - -#include <inspectable.h> -#include <mdmregistration.h> -#include <objbase.h> -#include <propkey.h> -#include <propvarutil.h> -#include <psapi.h> -#include <roapi.h> -#include <sddl.h> -#include <setupapi.h> -#include <shellscalingapi.h> -#include <shlwapi.h> -#include <signal.h> -#include <stddef.h> -#include <stdlib.h> -#include <tchar.h> // Must be before tpcshrd.h or for any use of _T macro -#include <tpcshrd.h> -#include <uiviewsettingsinterop.h> -#include <windows.ui.viewmanagement.h> -#include <winstring.h> -#include <wrl/client.h> -#include <wrl/wrappers/corewrappers.h> - -#include <memory> - -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "base/win/core_winrt_util.h" -#include "base/win/registry.h" -#include "base/win/scoped_co_mem.h" -#include "base/win/scoped_handle.h" -#include "base/win/scoped_hstring.h" -#include "base/win/scoped_propvariant.h" -#include "base/win/win_client_metrics.h" -#include "base/win/windows_version.h" - -namespace base { -namespace win { - -namespace { - -// Sets the value of |property_key| to |property_value| in |property_store|. -bool SetPropVariantValueForPropertyStore( - IPropertyStore* property_store, - const PROPERTYKEY& property_key, - const ScopedPropVariant& property_value) { - DCHECK(property_store); - - HRESULT result = property_store->SetValue(property_key, property_value.get()); - if (result == S_OK) - result = property_store->Commit(); - if (SUCCEEDED(result)) - return true; -#if DCHECK_IS_ON() - ScopedCoMem<OLECHAR> guidString; - ::StringFromCLSID(property_key.fmtid, &guidString); - if (HRESULT_FACILITY(result) == FACILITY_WIN32) - ::SetLastError(HRESULT_CODE(result)); - // See third_party/perl/c/i686-w64-mingw32/include/propkey.h for GUID and - // PID definitions. - DPLOG(ERROR) << "Failed to set property with GUID " << guidString << " PID " - << property_key.pid; -#endif - return false; -} - -void __cdecl ForceCrashOnSigAbort(int) { - *((volatile int*)0) = 0x1337; -} - -// Returns the current platform role. We use the PowerDeterminePlatformRoleEx -// API for that. -POWER_PLATFORM_ROLE GetPlatformRole() { - return PowerDeterminePlatformRoleEx(POWER_PLATFORM_ROLE_V2); -} - -// Method used for Windows 8.1 and later. -// Since we support versions earlier than 8.1, we must dynamically load this -// function from user32.dll, so it won't fail to load in runtime. For earlier -// Windows versions GetProcAddress will return null and report failure so that -// callers can fall back on the deprecated SetProcessDPIAware. -bool SetProcessDpiAwarenessWrapper(PROCESS_DPI_AWARENESS value) { - decltype(&::SetProcessDpiAwareness) set_process_dpi_awareness_func = - reinterpret_cast<decltype(&::SetProcessDpiAwareness)>(GetProcAddress( - GetModuleHandle(L"user32.dll"), "SetProcessDpiAwarenessInternal")); - if (set_process_dpi_awareness_func) { - HRESULT hr = set_process_dpi_awareness_func(value); - if (SUCCEEDED(hr)) - return true; - DLOG_IF(ERROR, hr == E_ACCESSDENIED) - << "Access denied error from SetProcessDpiAwarenessInternal. Function " - "called twice, or manifest was used."; - NOTREACHED() - << "SetProcessDpiAwarenessInternal failed with unexpected error: " - << hr; - return false; - } - - DCHECK_LT(GetVersion(), VERSION_WIN8_1) << "SetProcessDpiAwarenessInternal " - "should be available on all " - "platforms >= Windows 8.1"; - return false; -} - -} // namespace - -static bool g_crash_on_process_detach = false; - -void GetNonClientMetrics(NONCLIENTMETRICS_XP* metrics) { - DCHECK(metrics); - metrics->cbSize = sizeof(*metrics); - const bool success = - !!SystemParametersInfo(SPI_GETNONCLIENTMETRICS, metrics->cbSize, - reinterpret_cast<NONCLIENTMETRICS*>(metrics), 0); - DCHECK(success); -} - -bool GetUserSidString(std::wstring* user_sid) { - // Get the current token. - HANDLE token = NULL; - if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token)) - return false; - ScopedHandle token_scoped(token); - - DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE; - std::unique_ptr<BYTE[]> user_bytes(new BYTE[size]); - TOKEN_USER* user = reinterpret_cast<TOKEN_USER*>(user_bytes.get()); - - if (!::GetTokenInformation(token, TokenUser, user, size, &size)) - return false; - - if (!user->User.Sid) - return false; - - // Convert the data to a string. - wchar_t* sid_string; - if (!::ConvertSidToStringSid(user->User.Sid, &sid_string)) - return false; - - *user_sid = sid_string; - - ::LocalFree(sid_string); - - return true; -} - -bool UserAccountControlIsEnabled() { - RegKey key(HKEY_LOCAL_MACHINE, - L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", - KEY_READ); - DWORD uac_enabled; - if (key.ReadValueDW(L"EnableLUA", &uac_enabled) != ERROR_SUCCESS) - return true; - // Users can set the EnableLUA value to something arbitrary, like 2, which - // Vista will treat as UAC enabled, so we make sure it is not set to 0. - return (uac_enabled != 0); -} - -bool SetBooleanValueForPropertyStore(IPropertyStore* property_store, - const PROPERTYKEY& property_key, - bool property_bool_value) { - ScopedPropVariant property_value; - if (FAILED(InitPropVariantFromBoolean(property_bool_value, - property_value.Receive()))) { - return false; - } - - return SetPropVariantValueForPropertyStore(property_store, property_key, - property_value); -} - -bool SetStringValueForPropertyStore(IPropertyStore* property_store, - const PROPERTYKEY& property_key, - const wchar_t* property_string_value) { - ScopedPropVariant property_value; - if (FAILED(InitPropVariantFromString(property_string_value, - property_value.Receive()))) { - return false; - } - - return SetPropVariantValueForPropertyStore(property_store, property_key, - property_value); -} - -bool SetClsidForPropertyStore(IPropertyStore* property_store, - const PROPERTYKEY& property_key, - const CLSID& property_clsid_value) { - ScopedPropVariant property_value; - if (FAILED(InitPropVariantFromCLSID(property_clsid_value, - property_value.Receive()))) { - return false; - } - - return SetPropVariantValueForPropertyStore(property_store, property_key, - property_value); -} - -bool SetAppIdForPropertyStore(IPropertyStore* property_store, - const wchar_t* app_id) { - // App id should be less than 64 chars and contain no space. And recommended - // format is CompanyName.ProductName[.SubProduct.ProductNumber]. - // See http://msdn.microsoft.com/en-us/library/dd378459%28VS.85%29.aspx - DCHECK(lstrlen(app_id) < 64 && wcschr(app_id, L' ') == NULL); - - return SetStringValueForPropertyStore(property_store, PKEY_AppUserModel_ID, - app_id); -} - -static const char16 kAutoRunKeyPath[] = - L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; - -bool AddCommandToAutoRun(HKEY root_key, - const string16& name, - const string16& command) { - RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_SET_VALUE); - return (autorun_key.WriteValue(name.c_str(), command.c_str()) == - ERROR_SUCCESS); -} - -bool RemoveCommandFromAutoRun(HKEY root_key, const string16& name) { - RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_SET_VALUE); - return (autorun_key.DeleteValue(name.c_str()) == ERROR_SUCCESS); -} - -bool ReadCommandFromAutoRun(HKEY root_key, - const string16& name, - string16* command) { - RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_QUERY_VALUE); - return (autorun_key.ReadValue(name.c_str(), command) == ERROR_SUCCESS); -} - -void SetShouldCrashOnProcessDetach(bool crash) { - g_crash_on_process_detach = crash; -} - -bool ShouldCrashOnProcessDetach() { - return g_crash_on_process_detach; -} - -void SetAbortBehaviorForCrashReporting() { - // Prevent CRT's abort code from prompting a dialog or trying to "report" it. - // Disabling the _CALL_REPORTFAULT behavior is important since otherwise it - // has the sideffect of clearing our exception filter, which means we - // don't get any crash. - _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); - - // Set a SIGABRT handler for good measure. We will crash even if the default - // is left in place, however this allows us to crash earlier. And it also - // lets us crash in response to code which might directly call raise(SIGABRT) - signal(SIGABRT, ForceCrashOnSigAbort); -} - -bool IsUser32AndGdi32Available() { - static auto is_user32_and_gdi32_available = []() { - // If win32k syscalls aren't disabled, then user32 and gdi32 are available. - - // Can't disable win32k prior to windows 8. - if (GetVersion() < VERSION_WIN8) - return true; - - typedef decltype( - GetProcessMitigationPolicy)* GetProcessMitigationPolicyType; - GetProcessMitigationPolicyType get_process_mitigation_policy_func = - reinterpret_cast<GetProcessMitigationPolicyType>(GetProcAddress( - GetModuleHandle(L"kernel32.dll"), "GetProcessMitigationPolicy")); - - if (!get_process_mitigation_policy_func) - return true; - - PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY policy = {}; - if (get_process_mitigation_policy_func(GetCurrentProcess(), - ProcessSystemCallDisablePolicy, - &policy, sizeof(policy))) { - return policy.DisallowWin32kSystemCalls == 0; - } - - return true; - }(); - return is_user32_and_gdi32_available; -} - -bool GetLoadedModulesSnapshot(HANDLE process, std::vector<HMODULE>* snapshot) { - DCHECK(snapshot); - DCHECK_EQ(0u, snapshot->size()); - snapshot->resize(128); - - // We will retry at least once after first determining |bytes_required|. If - // the list of modules changes after we receive |bytes_required| we may retry - // more than once. - int retries_remaining = 5; - do { - DWORD bytes_required = 0; - // EnumProcessModules returns 'success' even if the buffer size is too - // small. - DCHECK_GE(std::numeric_limits<DWORD>::max(), - snapshot->size() * sizeof(HMODULE)); - if (!::EnumProcessModules( - process, &(*snapshot)[0], - static_cast<DWORD>(snapshot->size() * sizeof(HMODULE)), - &bytes_required)) { - DPLOG(ERROR) << "::EnumProcessModules failed."; - return false; - } - DCHECK_EQ(0u, bytes_required % sizeof(HMODULE)); - size_t num_modules = bytes_required / sizeof(HMODULE); - if (num_modules <= snapshot->size()) { - // Buffer size was too big, presumably because a module was unloaded. - snapshot->erase(snapshot->begin() + num_modules, snapshot->end()); - return true; - } else if (num_modules == 0) { - DLOG(ERROR) << "Can't determine the module list size."; - return false; - } else { - // Buffer size was too small. Try again with a larger buffer. A little - // more room is given to avoid multiple expensive calls to - // ::EnumProcessModules() just because one module has been added. - snapshot->resize(num_modules + 8, NULL); - } - } while (--retries_remaining); - - DLOG(ERROR) << "Failed to enumerate modules."; - return false; -} - -void EnableFlicks(HWND hwnd) { - ::RemoveProp(hwnd, MICROSOFT_TABLETPENSERVICE_PROPERTY); -} - -void DisableFlicks(HWND hwnd) { - ::SetProp(hwnd, MICROSOFT_TABLETPENSERVICE_PROPERTY, - reinterpret_cast<HANDLE>(TABLET_DISABLE_FLICKS | - TABLET_DISABLE_FLICKFALLBACKKEYS)); -} - -bool IsProcessPerMonitorDpiAware() { - enum class PerMonitorDpiAware { - UNKNOWN = 0, - PER_MONITOR_DPI_UNAWARE, - PER_MONITOR_DPI_AWARE, - }; - static PerMonitorDpiAware per_monitor_dpi_aware = PerMonitorDpiAware::UNKNOWN; - if (per_monitor_dpi_aware == PerMonitorDpiAware::UNKNOWN) { - per_monitor_dpi_aware = PerMonitorDpiAware::PER_MONITOR_DPI_UNAWARE; - HMODULE shcore_dll = ::LoadLibrary(L"shcore.dll"); - if (shcore_dll) { - auto get_process_dpi_awareness_func = - reinterpret_cast<decltype(::GetProcessDpiAwareness)*>( - ::GetProcAddress(shcore_dll, "GetProcessDpiAwareness")); - if (get_process_dpi_awareness_func) { - PROCESS_DPI_AWARENESS awareness; - if (SUCCEEDED(get_process_dpi_awareness_func(nullptr, &awareness)) && - awareness == PROCESS_PER_MONITOR_DPI_AWARE) - per_monitor_dpi_aware = PerMonitorDpiAware::PER_MONITOR_DPI_AWARE; - } - } - } - return per_monitor_dpi_aware == PerMonitorDpiAware::PER_MONITOR_DPI_AWARE; -} - -void EnableHighDPISupport() { - // Enable per-monitor DPI for Win10 or above instead of Win8.1 since Win8.1 - // does not have EnableChildWindowDpiMessage, necessary for correct non-client - // area scaling across monitors. - PROCESS_DPI_AWARENESS process_dpi_awareness = - GetVersion() >= VERSION_WIN10 ? PROCESS_PER_MONITOR_DPI_AWARE - : PROCESS_SYSTEM_DPI_AWARE; - if (!SetProcessDpiAwarenessWrapper(process_dpi_awareness)) { - // For windows versions where SetProcessDpiAwareness is not available or - // failed, try its predecessor. - BOOL result = ::SetProcessDPIAware(); - DCHECK(result) << "SetProcessDPIAware failed."; - } -} - -} // namespace win -} // namespace base
diff --git a/base/win/win_util.h b/base/win/win_util.h deleted file mode 100644 index 08738cb..0000000 --- a/base/win/win_util.h +++ /dev/null
@@ -1,151 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// ============================================================================= -// 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_ - -#include <stdint.h> -#include "base/win/windows_types.h" - -#include <string> -#include <vector> - -#include "base/strings/string16.h" - -struct IPropertyStore; -struct _tagpropertykey; -typedef _tagpropertykey PROPERTYKEY; - -namespace base { -namespace win { - -inline uint32_t HandleToUint32(HANDLE h) { - // Cast through uintptr_t and then unsigned int to make the truncation to - // 32 bits explicit. Handles are size of-pointer but are always 32-bit values. - // https://msdn.microsoft.com/en-us/library/aa384203(VS.85).aspx says: - // 64-bit versions of Windows use 32-bit handles for interoperability. - return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h)); -} - -inline HANDLE Uint32ToHandle(uint32_t h) { - return reinterpret_cast<HANDLE>( - static_cast<uintptr_t>(static_cast<int32_t>(h))); -} - -// Returns the string representing the current user sid. -bool GetUserSidString(std::wstring* user_sid); - -// 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 -// machines, might still exist and be set to 0 (UAC disabled), in which case -// this function will return false. You should therefore check this flag only -// if the OS is Vista or later. -bool UserAccountControlIsEnabled(); - -// Sets the boolean value for a given key in given IPropertyStore. -bool SetBooleanValueForPropertyStore(IPropertyStore* property_store, - const PROPERTYKEY& property_key, - bool property_bool_value); - -// Sets the string value for a given key in given IPropertyStore. -bool SetStringValueForPropertyStore(IPropertyStore* property_store, - const PROPERTYKEY& property_key, - const wchar_t* property_string_value); - -// Sets the CLSID value for a given key in a given IPropertyStore. -bool SetClsidForPropertyStore(IPropertyStore* property_store, - const PROPERTYKEY& property_key, - const CLSID& property_clsid_value); - -// Sets the application id in given IPropertyStore. The function is intended -// for tagging application/chromium shortcut, browser window and jump list for -// Win7. -bool SetAppIdForPropertyStore(IPropertyStore* property_store, - const wchar_t* app_id); - -// Adds the specified |command| using the specified |name| to the AutoRun key. -// |root_key| could be HKCU or HKLM or the root of any user hive. -bool AddCommandToAutoRun(HKEY root_key, - const string16& name, - const string16& command); -// Removes the command specified by |name| from the AutoRun key. |root_key| -// could be HKCU or HKLM or the root of any user hive. -bool RemoveCommandFromAutoRun(HKEY root_key, const string16& name); - -// Reads the command specified by |name| from the AutoRun key. |root_key| -// could be HKCU or HKLM or the root of any user hive. Used for unit-tests. -bool ReadCommandFromAutoRun(HKEY root_key, - const string16& name, - string16* command); - -// Sets whether to crash the process during exit. This is inspected by DLLMain -// and used to intercept unexpected terminations of the process (via calls to -// exit(), abort(), _exit(), ExitProcess()) and convert them into crashes. -// Note that not all mechanisms for terminating the process are covered by -// this. In particular, TerminateProcess() is not caught. -void SetShouldCrashOnProcessDetach(bool crash); -bool ShouldCrashOnProcessDetach(); - -// Adjusts the abort behavior so that crash reports can be generated when the -// process is aborted. -void SetAbortBehaviorForCrashReporting(); - -// Get the size of a struct up to and including the specified member. -// This is necessary to set compatible struct sizes for different versions -// of certain Windows APIs (e.g. SystemParametersInfo). -#define SIZEOF_STRUCT_WITH_SPECIFIED_LAST_MEMBER(struct_name, member) \ - offsetof(struct_name, member) + \ - (sizeof static_cast<struct_name*>(NULL)->member) - -// Used by tests to mock any wanted state. Call with |state| set to true to -// simulate being in a domain and false otherwise. -void SetDomainStateForTesting(bool state); - -// Returns true if the current process can make USER32 or GDI32 calls such as -// CreateWindow and CreateDC. Windows 8 and above allow the kernel component -// of these calls to be disabled which can cause undefined behaviour such as -// crashes. This function can be used to guard areas of code using these calls -// and provide a fallback path if necessary. -bool IsUser32AndGdi32Available(); - -// Takes a snapshot of the modules loaded in the |process|. The returned -// HMODULEs are not add-ref'd, so they should not be closed and may be -// invalidated at any time (should a module be unloaded). |process| requires -// the PROCESS_QUERY_INFORMATION and PROCESS_VM_READ permissions. -bool GetLoadedModulesSnapshot(HANDLE process, std::vector<HMODULE>* snapshot); - -// Adds or removes the MICROSOFT_TABLETPENSERVICE_PROPERTY property with the -// TABLET_DISABLE_FLICKS & TABLET_DISABLE_FLICKFALLBACKKEYS flags in order to -// disable pen flick gestures for the given HWND. -void EnableFlicks(HWND hwnd); -void DisableFlicks(HWND hwnd); - -// Returns true if the process is per monitor DPI aware. -bool IsProcessPerMonitorDpiAware(); - -// Enable high-DPI support for the current process. -void EnableHighDPISupport(); - -} // namespace win -} // namespace base - -#endif // BASE_WIN_WIN_UTIL_H_
diff --git a/base/win/windows_version.cc b/base/win/windows_version.cc deleted file mode 100644 index dd45286..0000000 --- a/base/win/windows_version.cc +++ /dev/null
@@ -1,254 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/win/windows_version.h" - -#include <windows.h> - -#include <memory> - -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/strings/utf_string_conversions.h" -#include "base/win/registry.h" - -#if !defined(__clang__) && _MSC_FULL_VER < 191125507 -#error VS 2017 Update 3.2 or higher is required -#endif - -#if !defined(NTDDI_WIN10_RS2) -// Windows 10 April 2018 SDK is required to build Chrome. -#error April 2018 SDK (10.0.17134.0) or higher required. -#endif - -namespace { -typedef BOOL(WINAPI* GetProductInfoPtr)(DWORD, DWORD, DWORD, DWORD, PDWORD); -} // namespace - -namespace base { -namespace win { - -namespace { - -// Helper to map a major.minor.x.build version (e.g. 6.1) to a Windows release. -Version MajorMinorBuildToVersion(int major, int minor, int build) { - if ((major == 5) && (minor > 0)) { - // Treat XP Pro x64, Home Server, and Server 2003 R2 as Server 2003. - return (minor == 1) ? VERSION_XP : VERSION_SERVER_2003; - } else if (major == 6) { - switch (minor) { - case 0: - // Treat Windows Server 2008 the same as Windows Vista. - return VERSION_VISTA; - case 1: - // Treat Windows Server 2008 R2 the same as Windows 7. - return VERSION_WIN7; - case 2: - // Treat Windows Server 2012 the same as Windows 8. - return VERSION_WIN8; - default: - DCHECK_EQ(minor, 3); - return VERSION_WIN8_1; - } - } else if (major == 10) { - if (build < 10586) { - return VERSION_WIN10; - } else if (build < 14393) { - return VERSION_WIN10_TH2; - } else if (build < 15063) { - return VERSION_WIN10_RS1; - } else if (build < 16299) { - return VERSION_WIN10_RS2; - } else if (build < 17134) { - return VERSION_WIN10_RS3; - } else { - return VERSION_WIN10_RS4; - } - } else if (major > 6) { - NOTREACHED(); - return VERSION_WIN_LAST; - } - - return VERSION_PRE_XP; -} - -// Returns the the "UBR" value from the registry. Introduced in Windows 10, -// this undocumented value appears to be similar to a patch number. -// Returns 0 if the value does not exist or it could not be read. -int GetUBR() { - // The values under the CurrentVersion registry hive are mirrored under - // the corresponding Wow6432 hive. - static constexpr wchar_t kRegKeyWindowsNTCurrentVersion[] = - L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"; - - base::win::RegKey key; - if (key.Open(HKEY_LOCAL_MACHINE, kRegKeyWindowsNTCurrentVersion, - KEY_QUERY_VALUE) != ERROR_SUCCESS) { - return 0; - } - - DWORD ubr = 0; - key.ReadValueDW(L"UBR", &ubr); - - return static_cast<int>(ubr); -} - -} // namespace - -// static -OSInfo* OSInfo::GetInstance() { - // Note: we don't use the Singleton class because it depends on AtExitManager, - // and it's convenient for other modules to use this classs without it. This - // pattern is copied from gurl.cc. - static OSInfo* info; - if (!info) { - OSInfo* new_info = new OSInfo(); - if (InterlockedCompareExchangePointer(reinterpret_cast<PVOID*>(&info), - new_info, NULL)) { - delete new_info; - } - } - return info; -} - -OSInfo::OSInfo() - : version_(VERSION_PRE_XP), - kernel32_version_(VERSION_PRE_XP), - architecture_(OTHER_ARCHITECTURE), - wow64_status_(GetWOW64StatusForProcess(GetCurrentProcess())) { - OSVERSIONINFOEX version_info = {sizeof version_info}; - ::GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&version_info)); - version_number_.major = version_info.dwMajorVersion; - version_number_.minor = version_info.dwMinorVersion; - version_number_.build = version_info.dwBuildNumber; - version_number_.patch = GetUBR(); - version_ = MajorMinorBuildToVersion( - version_number_.major, version_number_.minor, version_number_.build); - service_pack_.major = version_info.wServicePackMajor; - service_pack_.minor = version_info.wServicePackMinor; - service_pack_str_ = base::WideToUTF8(version_info.szCSDVersion); - - SYSTEM_INFO system_info = {}; - ::GetNativeSystemInfo(&system_info); - switch (system_info.wProcessorArchitecture) { - case PROCESSOR_ARCHITECTURE_INTEL: - architecture_ = X86_ARCHITECTURE; - break; - case PROCESSOR_ARCHITECTURE_AMD64: - architecture_ = X64_ARCHITECTURE; - break; - case PROCESSOR_ARCHITECTURE_IA64: - architecture_ = IA64_ARCHITECTURE; - break; - } - processors_ = system_info.dwNumberOfProcessors; - allocation_granularity_ = system_info.dwAllocationGranularity; - - GetProductInfoPtr get_product_info; - DWORD os_type; - - if (version_info.dwMajorVersion == 6 || version_info.dwMajorVersion == 10) { - // Only present on Vista+. - get_product_info = reinterpret_cast<GetProductInfoPtr>( - ::GetProcAddress(::GetModuleHandle(L"kernel32.dll"), "GetProductInfo")); - - get_product_info(version_info.dwMajorVersion, version_info.dwMinorVersion, - 0, 0, &os_type); - switch (os_type) { - case PRODUCT_CLUSTER_SERVER: - case PRODUCT_DATACENTER_SERVER: - case PRODUCT_DATACENTER_SERVER_CORE: - case PRODUCT_ENTERPRISE_SERVER: - case PRODUCT_ENTERPRISE_SERVER_CORE: - case PRODUCT_ENTERPRISE_SERVER_IA64: - case PRODUCT_SMALLBUSINESS_SERVER: - case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM: - case PRODUCT_STANDARD_SERVER: - case PRODUCT_STANDARD_SERVER_CORE: - case PRODUCT_WEB_SERVER: - version_type_ = SUITE_SERVER; - break; - case PRODUCT_PROFESSIONAL: - case PRODUCT_ULTIMATE: - version_type_ = SUITE_PROFESSIONAL; - break; - case PRODUCT_ENTERPRISE: - case PRODUCT_ENTERPRISE_E: - case PRODUCT_ENTERPRISE_EVALUATION: - case PRODUCT_ENTERPRISE_N: - case PRODUCT_ENTERPRISE_N_EVALUATION: - case PRODUCT_ENTERPRISE_S: - case PRODUCT_ENTERPRISE_S_EVALUATION: - case PRODUCT_ENTERPRISE_S_N: - case PRODUCT_ENTERPRISE_S_N_EVALUATION: - case PRODUCT_BUSINESS: - case PRODUCT_BUSINESS_N: - version_type_ = SUITE_ENTERPRISE; - break; - case PRODUCT_EDUCATION: - case PRODUCT_EDUCATION_N: - version_type_ = SUITE_EDUCATION; - break; - case PRODUCT_HOME_BASIC: - case PRODUCT_HOME_PREMIUM: - case PRODUCT_STARTER: - default: - version_type_ = SUITE_HOME; - break; - } - } else if (version_info.dwMajorVersion == 5 && - version_info.dwMinorVersion == 2) { - if (version_info.wProductType == VER_NT_WORKSTATION && - system_info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { - version_type_ = SUITE_PROFESSIONAL; - } else if (version_info.wSuiteMask & VER_SUITE_WH_SERVER) { - version_type_ = SUITE_HOME; - } else { - version_type_ = SUITE_SERVER; - } - } else if (version_info.dwMajorVersion == 5 && - version_info.dwMinorVersion == 1) { - if (version_info.wSuiteMask & VER_SUITE_PERSONAL) - version_type_ = SUITE_HOME; - else - version_type_ = SUITE_PROFESSIONAL; - } else { - // Windows is pre XP so we don't care but pick a safe default. - version_type_ = SUITE_HOME; - } -} - -OSInfo::~OSInfo() {} - -std::string OSInfo::processor_model_name() { - if (processor_model_name_.empty()) { - const wchar_t kProcessorNameString[] = - L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"; - base::win::RegKey key(HKEY_LOCAL_MACHINE, kProcessorNameString, KEY_READ); - string16 value; - key.ReadValue(L"ProcessorNameString", &value); - processor_model_name_ = UTF16ToUTF8(value); - } - return processor_model_name_; -} - -// static -OSInfo::WOW64Status OSInfo::GetWOW64StatusForProcess(HANDLE process_handle) { - typedef BOOL(WINAPI * IsWow64ProcessFunc)(HANDLE, PBOOL); - IsWow64ProcessFunc is_wow64_process = reinterpret_cast<IsWow64ProcessFunc>( - GetProcAddress(GetModuleHandle(L"kernel32.dll"), "IsWow64Process")); - if (!is_wow64_process) - return WOW64_DISABLED; - BOOL is_wow64 = FALSE; - if (!(*is_wow64_process)(process_handle, &is_wow64)) - return WOW64_UNKNOWN; - return is_wow64 ? WOW64_ENABLED : WOW64_DISABLED; -} - -Version GetVersion() { - return OSInfo::GetInstance()->version(); -} - -} // namespace win -} // namespace base
diff --git a/base/win/windows_version.h b/base/win/windows_version.h deleted file mode 100644 index cd1df78..0000000 --- a/base/win/windows_version.h +++ /dev/null
@@ -1,146 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_WIN_WINDOWS_VERSION_H_ -#define BASE_WIN_WINDOWS_VERSION_H_ - -#include <stddef.h> - -#include <string> - -#include "base/macros.h" - -typedef void* HANDLE; - -namespace base { -namespace win { - -// The running version of Windows. This is declared outside OSInfo for -// syntactic sugar reasons; see the declaration of GetVersion() below. -// NOTE: Keep these in order so callers can do things like -// "if (base::win::GetVersion() >= base::win::VERSION_VISTA) ...". -// -// This enum is used in metrics histograms, so they shouldn't be reordered or -// removed. New values can be added before VERSION_WIN_LAST. -enum Version { - VERSION_PRE_XP = 0, // Not supported. - VERSION_XP = 1, - VERSION_SERVER_2003 = 2, // Also includes XP Pro x64 and Server 2003 R2. - VERSION_VISTA = 3, // Also includes Windows Server 2008. - VERSION_WIN7 = 4, // Also includes Windows Server 2008 R2. - VERSION_WIN8 = 5, // Also includes Windows Server 2012. - VERSION_WIN8_1 = 6, // Also includes Windows Server 2012 R2. - VERSION_WIN10 = 7, // Threshold 1: Version 1507, Build 10240. - VERSION_WIN10_TH2 = 8, // Threshold 2: Version 1511, Build 10586. - VERSION_WIN10_RS1 = 9, // Redstone 1: Version 1607, Build 14393. - VERSION_WIN10_RS2 = 10, // Redstone 2: Version 1703, Build 15063. - VERSION_WIN10_RS3 = 11, // Redstone 3: Version 1709, Build 16299. - VERSION_WIN10_RS4 = 12, // Redstone 4: Version 1803, Build 17134. - // On edit, update tools\metrics\histograms\enums.xml "WindowsVersion" and - // "GpuBlacklistFeatureTestResultsWindows2". - VERSION_WIN_LAST, // Indicates error condition. -}; - -// A rough bucketing of the available types of versions of Windows. This is used -// to distinguish enterprise enabled versions from home versions and potentially -// server versions. Keep these values in the same order, since they are used as -// is for metrics histogram ids. -enum VersionType { - SUITE_HOME = 0, - SUITE_PROFESSIONAL, - SUITE_SERVER, - SUITE_ENTERPRISE, - SUITE_EDUCATION, - SUITE_LAST, -}; - -// A singleton that can be used to query various pieces of information about the -// OS and process state. Note that this doesn't use the base Singleton class, so -// it can be used without an AtExitManager. -class OSInfo { - public: - struct VersionNumber { - int major; - int minor; - int build; - int patch; - }; - - struct ServicePack { - int major; - int minor; - }; - - // The processor architecture this copy of Windows natively uses. For - // example, given an x64-capable processor, we have three possibilities: - // 32-bit Chrome running on 32-bit Windows: X86_ARCHITECTURE - // 32-bit Chrome running on 64-bit Windows via WOW64: X64_ARCHITECTURE - // 64-bit Chrome running on 64-bit Windows: X64_ARCHITECTURE - enum WindowsArchitecture { - X86_ARCHITECTURE, - X64_ARCHITECTURE, - IA64_ARCHITECTURE, - OTHER_ARCHITECTURE, - }; - - // Whether a process is running under WOW64 (the wrapper that allows 32-bit - // processes to run on 64-bit versions of Windows). This will return - // WOW64_DISABLED for both "32-bit Chrome on 32-bit Windows" and "64-bit - // Chrome on 64-bit Windows". WOW64_UNKNOWN means "an error occurred", e.g. - // the process does not have sufficient access rights to determine this. - enum WOW64Status { - WOW64_DISABLED, - WOW64_ENABLED, - WOW64_UNKNOWN, - }; - - static OSInfo* GetInstance(); - - Version version() const { return version_; } - // The next two functions return arrays of values, [major, minor(, build)]. - VersionNumber version_number() const { return version_number_; } - VersionType version_type() const { return version_type_; } - ServicePack service_pack() const { return service_pack_; } - std::string service_pack_str() const { return service_pack_str_; } - WindowsArchitecture architecture() const { return architecture_; } - int processors() const { return processors_; } - size_t allocation_granularity() const { return allocation_granularity_; } - WOW64Status wow64_status() const { return wow64_status_; } - std::string processor_model_name(); - - // Like wow64_status(), but for the supplied handle instead of the current - // process. This doesn't touch member state, so you can bypass the singleton. - static WOW64Status GetWOW64StatusForProcess(HANDLE process_handle); - - private: - OSInfo(); - ~OSInfo(); - - Version version_; - mutable Version kernel32_version_; - VersionNumber version_number_; - VersionType version_type_; - ServicePack service_pack_; - - // A string, such as "Service Pack 3", that indicates the latest Service Pack - // installed on the system. If no Service Pack has been installed, the string - // is empty. - std::string service_pack_str_; - WindowsArchitecture architecture_; - int processors_; - size_t allocation_granularity_; - WOW64Status wow64_status_; - std::string processor_model_name_; - - DISALLOW_COPY_AND_ASSIGN(OSInfo); -}; - -// Because this is by far the most commonly-requested value from the above -// singleton, we add a global-scope accessor here as syntactic sugar. -Version GetVersion(); - -} // namespace win -} // namespace base - -#endif // BASE_WIN_WINDOWS_VERSION_H_
diff --git a/build/gen.py b/build/gen.py index ff6084e..4bf84d9 100755 --- a/build/gen.py +++ b/build/gen.py
@@ -525,20 +525,10 @@ 'base/synchronization/waitable_event_win.cc', 'base/threading/platform_thread_win.cc', 'base/time/time_win.cc', - 'base/win/core_winrt_util.cc', - 'base/win/enum_variant.cc', - 'base/win/iat_patch_function.cc', - 'base/win/iunknown_impl.cc', - 'base/win/pe_image.cc', - 'base/win/process_startup_helper.cc', 'base/win/registry.cc', - 'base/win/resource_util.cc', 'base/win/scoped_handle.cc', 'base/win/scoped_process_information.cc', - 'base/win/shortcut.cc', 'base/win/startup_information.cc', - 'base/win/win_util.cc', - 'base/win/windows_version.cc', ]) libs.extend([