OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2015 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #include <dlfcn.h> | |
6 #include <libkern/OSByteOrder.h> | |
7 #include <mach/mach.h> | |
8 #include <mach/thread_status.h> | |
9 #include <mach-o/swap.h> | |
10 #include <stdlib.h> | |
11 #include <uuid/uuid.h> | |
12 | |
13 #include <map> | |
14 | |
15 #include "base/profiler/native_stack_sampler.h" | |
16 #include "base/strings/string_number_conversions.h" | |
17 | |
18 namespace base { | |
19 | |
20 namespace { | |
21 | |
22 // Copy of x86_64 thread context structure from x86_thread_state64_t type. | |
23 // Copied struct since fields can have different names on different versions of | |
24 // Darwin. | |
25 struct ThreadContext { | |
26 uint64_t rax; | |
27 uint64_t rbx; | |
28 uint64_t rcx; | |
29 uint64_t rdx; | |
30 uint64_t rdi; | |
31 uint64_t rsi; | |
32 uint64_t rbp; | |
33 uint64_t rsp; | |
34 uint64_t r8; | |
35 uint64_t r9; | |
36 uint64_t r10; | |
37 uint64_t r11; | |
38 uint64_t r12; | |
39 uint64_t r13; | |
40 uint64_t r14; | |
41 uint64_t r15; | |
42 uint64_t rip; | |
43 uint64_t rflags; | |
44 uint64_t cs; | |
45 uint64_t fs; | |
46 uint64_t gs; | |
47 }; | |
48 | |
49 // Struct for stack walking (represents stack state on any function call that | |
50 // pushes a frame pointer). | |
51 struct StackFrame { | |
52 // Pointer to caller's frame (rbp). | |
53 uintptr_t base_pointer; | |
54 // Address in caller for callee to return to. | |
55 uintptr_t return_address; | |
56 }; | |
57 | |
58 // Helper that swaps byte order in |x| if |swap| flag is set. | |
59 uint32_t SwapIfBig32(uint32_t x, bool swap) { | |
60 if (swap) | |
61 return OSSwapBigToHostInt32(x); | |
62 return x; | |
63 } | |
64 | |
65 // Overwrites |dst| with StackFrame referenced in |src|. Returns true if stack | |
66 // read was successful. Failure implies address in |src| is corrupt. | |
67 bool SafeStackFrameRead(uintptr_t src, StackFrame* dst) { | |
68 vm_size_t ignored_bytes_copied = 0; | |
69 return vm_read_overwrite(mach_task_self(), static_cast<vm_address_t>(src), | |
70 static_cast<vm_size_t>(sizeof(StackFrame)), | |
71 reinterpret_cast<vm_address_t>(dst), | |
72 &ignored_bytes_copied) == KERN_SUCCESS; | |
73 } | |
74 | |
75 // Functions related to retrieving Mach-O Identifer | |
76 // This walker only supports modules built for x86_64 architecture. More detail | |
77 // can be found in the OS X ABI Mach-O File Format Reference. | |
78 | |
79 // Returns offset in bytes where the x86_64 header is located in binary | |
80 // loaded at |module_addr|. Returns 0 if |module_addr| is not a valid FAT | |
81 // Mach-O binary or has not been built for x86_64. | |
82 off_t GetMach64HeaderOffset(const void* module_addr) { | |
83 const fat_header* header = reinterpret_cast<const fat_header*>(module_addr); | |
84 if (header->magic != FAT_MAGIC && header->magic != FAT_CIGAM) | |
85 return 0; | |
86 | |
87 // Search all FAT architectures for x86_64. | |
88 const fat_arch* fat_arches = reinterpret_cast<const fat_arch*>( | |
89 reinterpret_cast<const uint8_t*>(module_addr) + sizeof(header)); | |
90 for (uint32_t i = 0; i < OSSwapBigToHostInt32(header->nfat_arch); ++i) { | |
robliao
2015/09/16 01:41:45
Cache the result of OSSwapBigToHostInt32(header->n
sydli
2015/09/18 20:29:20
Done.
| |
91 const fat_arch& arch = fat_arches[i]; | |
92 if (OSSwapBigToHostInt32(arch.cputype) == CPU_TYPE_X86_64) | |
93 return OSSwapBigToHostInt32(arch.offset); | |
94 } | |
95 return 0; | |
96 } | |
97 | |
98 // Returns true if Mach-O binary at |module_addr| was built specifically for | |
99 // x86_64 cpu architecture. | |
100 bool IsX64Header(const void* module_addr) { | |
101 const mach_header_64* header = | |
102 reinterpret_cast<const mach_header_64*>(module_addr); | |
103 if (header->magic != MH_MAGIC_64 && header->magic != MH_CIGAM_64) | |
104 return false; | |
105 bool swap = header->magic == MH_CIGAM_64; | |
106 return SwapIfBig32(header->cputype, swap) == CPU_TYPE_X86_64; | |
107 } | |
108 | |
109 // Fills |id| with the UUID of the x86_64 Mach-O binary loaded at |module_addr|. | |
110 // |offset| is the offset in bytes into |module_addr| where the x86_64 header | |
111 // is located. |offset| is only relevant if binary is FAT and contains | |
112 // multiple architecture headers. Returns false if header is malformed or the | |
113 // header does not specify the UUID load command. | |
114 bool GetX64UUIDAt(const void* module_addr, unsigned char* id, off_t offset) { | |
115 const mach_header_64* header = reinterpret_cast<const mach_header_64*>( | |
116 reinterpret_cast<const uint8_t*>(module_addr) + offset); | |
117 if (header->magic != MH_MAGIC_64 && header->magic != MH_CIGAM_64) | |
118 return false; | |
119 bool swap = header->magic == MH_CIGAM_64; | |
robliao
2015/09/16 01:41:45
Nit: Group statement with the next set of statemen
sydli
2015/09/18 20:29:20
Done.
| |
120 | |
121 // Search all load commands for UUID command. | |
122 offset += sizeof(mach_header_64); | |
123 for (uint32_t i = 0; i < SwapIfBig32(header->ncmds, swap); ++i) { | |
124 const load_command* current_cmd = reinterpret_cast<const load_command*>( | |
125 reinterpret_cast<const uint8_t*>(module_addr) + offset); | |
126 | |
127 if (SwapIfBig32(current_cmd->cmd, swap) == LC_UUID) { | |
128 const uuid_command* uuid_cmd = | |
129 reinterpret_cast<const uuid_command*>(current_cmd); | |
130 memcpy(id, &uuid_cmd->uuid, sizeof(uuid_t)); | |
131 return true; | |
132 } | |
133 offset += SwapIfBig32(current_cmd->cmdsize, swap); | |
134 } | |
135 return false; | |
136 } | |
137 | |
138 // Fills |id| with Mach-O UUID retrieved from Mach-O binary loaded at | |
139 // |module_addr|. This function returns false if the binary was not built for | |
140 // X86_64 or if UUID cannot be found. | |
141 bool GetUUID(const void* module_addr, unsigned char* id) { | |
142 off_t offset = 0; | |
143 // If module is not x86_64 exclusive, it could be a module that supports | |
144 // multiple architectures. In this case, the appropriate header will be at | |
145 // some non-zero offset. | |
146 if (!IsX64Header(module_addr) && | |
147 !(offset = GetMach64HeaderOffset(module_addr))) { | |
148 return false; | |
149 } | |
150 return GetX64UUIDAt(module_addr, id, offset); | |
151 } | |
152 | |
153 // Returns hex encoding of a 16-byte ID for binary loaded at |module_addr|. | |
154 // Returns empty string if UUID cannot be found at |module_addr|. | |
155 std::string GetUniqueId(const void* module_addr) { | |
156 unsigned char id[sizeof(uuid_t)]; | |
157 if (!GetUUID(module_addr, id)) | |
158 return ""; | |
159 return HexEncode(id, sizeof(uuid_t)); | |
160 } | |
161 | |
162 // Functions related to grabbing a stack trace --------------------------------- | |
163 | |
164 // Fills |state| with |target_thread|'s context. | |
165 bool GetThreadContext(thread_act_t target_thread, ThreadContext* state) { | |
166 mach_msg_type_number_t count = | |
167 static_cast<mach_msg_type_number_t>(MACHINE_THREAD_STATE_COUNT); | |
168 return thread_get_state(target_thread, x86_THREAD_STATE64, | |
169 reinterpret_cast<thread_state_t>(state), | |
170 &count) == KERN_SUCCESS; | |
171 } | |
172 | |
173 // Walks |thread_handle|'s stack and fills |instruction_pointers|. | |
174 // Returns number of frames in stack, unless there's a corrupt frame pointer | |
175 // (likely if module compiled with -fno_omit_frame_pointer), in which this | |
176 // function will return the number of frames up until the frame with a corrupt | |
177 // frame pointer. This procedure occurs while thread is suspended, so it should | |
178 // take as little time as possible. | |
179 int RecordStack(mach_port_t thread_handle, | |
180 int max_stack_size, | |
181 uintptr_t instruction_pointers[]) { | |
182 ThreadContext state; | |
183 if (!GetThreadContext(thread_handle, &state)) | |
184 return 0; | |
185 | |
186 StackFrame frame; | |
187 frame.base_pointer = state.rbp; | |
188 int i = 0; | |
189 for (; i < max_stack_size; i++) { | |
190 // Three cases for end-of-stack condition: | |
191 // 1) A frame pointer was corrupt. | |
192 // 2) The next recovered rsp is not lower than the previously recovered | |
193 // one, indicating the stack is not growing down. | |
194 // 3) Return (instruction) address is 0. | |
195 uintptr_t old_rsp = frame.base_pointer; | |
196 if (!SafeStackFrameRead(frame.base_pointer, &frame) || | |
197 frame.base_pointer < old_rsp || !frame.return_address) { | |
198 return i; | |
199 } | |
200 instruction_pointers[i] = frame.return_address; | |
201 } | |
202 return i; | |
203 } | |
204 | |
205 // NativeStackSamplerMac ------------------------------------------------------ | |
206 | |
207 class NativeStackSamplerMac : public NativeStackSampler { | |
208 public: | |
209 explicit NativeStackSamplerMac(pid_t thread_handle); | |
210 ~NativeStackSamplerMac() override; | |
211 | |
212 // StackSamplingProfiler::NativeStackSampler: | |
213 void ProfileRecordingStarting( | |
214 std::vector<StackSamplingProfiler::Module>* modules) override; | |
215 void RecordStackSample(StackSamplingProfiler::Sample* sample) override; | |
216 void ProfileRecordingStopped() override; | |
217 | |
218 private: | |
219 // Gets the index for the Module containing |instruction_pointer| in | |
220 // |modules|, adding it if it's not already present. Returns | |
221 // StackSamplingProfiler::Frame::kUnknownModuleIndex if no Module can be | |
222 // determined for |module|. | |
223 size_t GetModuleIndex(const uintptr_t instruction_pointer, | |
224 std::vector<StackSamplingProfiler::Module>* modules); | |
225 | |
226 // Copies the stack information represented by |instruction_pointers| into | |
227 // |sample| and |modules|. | |
228 void CopyToSample(const uintptr_t instruction_pointers[], | |
229 int stack_depth, | |
230 StackSamplingProfiler::Sample* sample, | |
231 std::vector<StackSamplingProfiler::Module>* modules); | |
232 | |
233 // Weak reference: Mach handle for thread being profiled. | |
234 mach_port_t thread_handle_; | |
235 | |
236 // Weak. Points to the modules associated with the profile being recorded | |
237 // between ProfileRecordingStarting() and ProfileRecordingStopped(). | |
238 std::vector<StackSamplingProfiler::Module>* current_modules_; | |
239 | |
240 // Maps a module's base address to the corresponding Module's index within | |
241 // current_modules_. | |
242 std::map<const void*, size_t> profile_module_index_; | |
243 | |
244 DISALLOW_COPY_AND_ASSIGN(NativeStackSamplerMac); | |
245 }; | |
246 | |
247 // The PlatformThreadId of the given thread is actually a typedef of | |
248 // mach_port_t. | |
249 // (base/threading/platform_thread_posix.cc:128) | |
250 NativeStackSamplerMac::NativeStackSamplerMac(pid_t thread_handle) | |
251 : thread_handle_(static_cast<mach_port_t>(thread_handle)), | |
252 current_modules_(nullptr) {} | |
253 | |
254 NativeStackSamplerMac::~NativeStackSamplerMac() {} | |
255 | |
256 void NativeStackSamplerMac::ProfileRecordingStarting( | |
257 std::vector<StackSamplingProfiler::Module>* modules) { | |
258 current_modules_ = modules; | |
259 profile_module_index_.clear(); | |
260 } | |
261 | |
262 void NativeStackSamplerMac::RecordStackSample( | |
263 StackSamplingProfiler::Sample* sample) { | |
264 DCHECK(current_modules_); | |
265 | |
266 const int max_stack_size = 64; | |
robliao
2015/09/16 01:41:45
Optional: It would be nice to unify this value som
| |
267 uintptr_t instruction_pointers[max_stack_size] = {0}; | |
268 | |
269 thread_suspend(thread_handle_); | |
Robert Sesek
2015/09/17 22:06:56
In the email thread, Mark mentioned that this coul
sydli
2015/09/18 20:29:20
Now forcibly binds library used during stack walk.
| |
270 int stack_depth = | |
271 RecordStack(thread_handle_, max_stack_size, instruction_pointers); | |
272 thread_resume(thread_handle_); | |
273 CopyToSample(instruction_pointers, stack_depth, sample, current_modules_); | |
274 } | |
275 | |
276 void NativeStackSamplerMac::ProfileRecordingStopped() { | |
277 current_modules_ = nullptr; | |
278 } | |
279 | |
280 size_t NativeStackSamplerMac::GetModuleIndex( | |
281 const uintptr_t instruction_pointer, | |
282 std::vector<StackSamplingProfiler::Module>* modules) { | |
283 Dl_info inf; | |
284 if (!dladdr(reinterpret_cast<const void*>(instruction_pointer), &inf)) | |
285 return StackSamplingProfiler::Frame::kUnknownModuleIndex; | |
286 | |
287 auto module_index = profile_module_index_.find(inf.dli_fbase); | |
288 if (module_index == profile_module_index_.end()) { | |
289 StackSamplingProfiler::Module module(inf.dli_fbase, | |
290 GetUniqueId(inf.dli_fbase), | |
291 base::FilePath(inf.dli_fname)); | |
292 modules->push_back(module); | |
293 module_index = profile_module_index_.insert( | |
294 std::make_pair(inf.dli_fbase, modules->size() - 1)).first; | |
295 } | |
296 return module_index->second; | |
297 } | |
298 | |
299 void NativeStackSamplerMac::CopyToSample( | |
300 const uintptr_t instruction_pointers[], | |
301 int stack_depth, | |
302 StackSamplingProfiler::Sample* sample, | |
303 std::vector<StackSamplingProfiler::Module>* modules) { | |
304 sample->clear(); | |
305 sample->reserve(stack_depth); | |
306 | |
307 for (int i = 0; i < stack_depth; i++) { | |
308 sample->push_back(StackSamplingProfiler::Frame( | |
309 reinterpret_cast<const void*>(instruction_pointers[i]), | |
310 GetModuleIndex(instruction_pointers[i], modules))); | |
311 } | |
312 } | |
313 | |
314 } // namespace | |
315 | |
316 scoped_ptr<NativeStackSampler> NativeStackSampler::Create( | |
317 PlatformThreadId thread_id) { | |
318 #if defined(__i386__) | |
319 return nullptr; | |
320 #endif | |
321 return scoped_ptr<NativeStackSampler>(new NativeStackSamplerMac(thread_id)); | |
322 } | |
323 | |
324 } // namespace base | |
OLD | NEW |