1 // Copyright 2018 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/profiler/module_cache.h"
12 #include "base/debug/alias.h"
13 #include "base/process/process_handle.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/win/pe_image.h"
18 #include "base/win/scoped_handle.h"
19 #include "base/win/win_util.h"
25 // Gets the unique build ID and the corresponding debug path for a module.
26 // Windows build IDs are created by a concatenation of a GUID and AGE fields
27 // found in the headers of a module. The GUID is stored in the first 16 bytes
28 // and the AGE is stored in the last 4 bytes. Returns the empty string if the
29 // function fails to get the build ID. The debug path (pdb file) can be found
30 // in the PE file and is the build time path where the debug file was produced.
33 // dumpbin chrome.exe /headers | find "Format:"
34 // ... Format: RSDS, {16B2A428-1DED-442E-9A36-FCE8CBD29726}, 10, ...
36 // The resulting buildID string of this instance of chrome.exe is
37 // "16B2A4281DED442E9A36FCE8CBD2972610".
39 // Note that the AGE field is encoded in decimal, not hex.
40 void GetDebugInfoForModule(HMODULE module_handle,
41 std::string* build_id,
45 LPCSTR pdb_file = nullptr;
46 size_t pdb_file_length = 0;
47 if (!win::PEImage(module_handle)
48 .GetDebugId(&guid, &age, &pdb_file, &pdb_file_length)) {
52 FilePath::StringType pdb_filename;
53 if (!UTF8ToWide(pdb_file, pdb_file_length, &pdb_filename))
55 *pdb_name = FilePath(std::move(pdb_filename)).BaseName();
57 auto buffer = win::WStringFromGUID(guid);
58 RemoveChars(buffer, L"{}-", &buffer);
59 buffer.append(NumberToWString(age));
60 *build_id = WideToUTF8(buffer);
63 // Returns true if the address is in the address space accessible to
64 // applications and DLLs, as reported by ::GetSystemInfo.
65 bool IsValidUserSpaceAddress(uintptr_t address) {
66 static LPVOID max_app_addr = 0;
67 static LPVOID min_app_addr = 0;
70 ::GetSystemInfo(&sys_info);
71 max_app_addr = sys_info.lpMaximumApplicationAddress;
72 min_app_addr = sys_info.lpMinimumApplicationAddress;
74 return reinterpret_cast<LPVOID>(address) >= min_app_addr &&
75 reinterpret_cast<LPVOID>(address) <= max_app_addr;
78 // Traits class to adapt GenericScopedHandle for HMODULES.
79 class ModuleHandleTraits : public win::HandleTraits {
81 using Handle = HMODULE;
83 ModuleHandleTraits() = delete;
84 ModuleHandleTraits(const ModuleHandleTraits&) = delete;
85 ModuleHandleTraits& operator=(const ModuleHandleTraits&) = delete;
87 static bool CloseHandle(HMODULE handle) { return ::FreeLibrary(handle) != 0; }
88 static bool IsHandleValid(HMODULE handle) { return handle != nullptr; }
89 static HMODULE NullHandle() { return nullptr; }
92 // HMODULE is not really a handle, and has reference count semantics, so the
93 // standard VerifierTraits does not apply.
94 using ScopedModuleHandle =
95 win::GenericScopedHandle<ModuleHandleTraits, win::DummyVerifierTraits>;
97 class WindowsModule : public ModuleCache::Module {
99 WindowsModule(ScopedModuleHandle module_handle,
100 const MODULEINFO module_info,
101 const std::string& id,
102 const FilePath& debug_basename)
103 : module_handle_(std::move(module_handle)),
104 module_info_(module_info),
106 debug_basename_(debug_basename) {}
108 WindowsModule(const WindowsModule&) = delete;
109 WindowsModule& operator=(const WindowsModule&) = delete;
111 // ModuleCache::Module
112 uintptr_t GetBaseAddress() const override {
113 return reinterpret_cast<uintptr_t>(module_info_.lpBaseOfDll);
116 std::string GetId() const override { return id_; }
117 FilePath GetDebugBasename() const override { return debug_basename_; }
118 size_t GetSize() const override { return module_info_.SizeOfImage; }
119 bool IsNative() const override { return true; }
122 ScopedModuleHandle module_handle_;
123 const MODULEINFO module_info_;
125 FilePath debug_basename_;
128 ScopedModuleHandle GetModuleHandleForAddress(uintptr_t address) {
129 // Record the address in crash dumps to help understand the source of
130 // GetModuleHandleEx crashes on Windows 11 observed in
131 // https://crbug.com/1297776.
132 debug::Alias(&address);
133 if (!IsValidUserSpaceAddress(address))
134 return ScopedModuleHandle(nullptr);
136 HMODULE module_handle = nullptr;
138 // GetModuleHandleEx() increments the module reference count, which is then
139 // managed and ultimately decremented by ScopedModuleHandle.
140 if (!::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
141 reinterpret_cast<LPCTSTR>(address),
143 const DWORD error = ::GetLastError();
144 DCHECK_EQ(ERROR_MOD_NOT_FOUND, static_cast<int>(error));
146 return ScopedModuleHandle(module_handle);
149 std::unique_ptr<ModuleCache::Module> CreateModuleForHandle(
150 ScopedModuleHandle module_handle) {
152 std::string build_id;
153 GetDebugInfoForModule(module_handle.get(), &build_id, &pdb_name);
155 MODULEINFO module_info;
156 if (!::GetModuleInformation(GetCurrentProcessHandle(), module_handle.get(),
157 &module_info, sizeof(module_info))) {
161 return std::make_unique<WindowsModule>(std::move(module_handle), module_info,
168 std::unique_ptr<const ModuleCache::Module> ModuleCache::CreateModuleForAddress(
170 ScopedModuleHandle module_handle = GetModuleHandleForAddress(address);
171 if (!module_handle.is_valid())
173 return CreateModuleForHandle(std::move(module_handle));