Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(501)

Side by Side Diff: base/profiler/native_stack_sampler_mac.cc

Issue 1346453004: NativeStackSampler implementation for Mac. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Addressed Rob's comments. Created 5 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « base/base.gypi ('k') | base/profiler/stack_sampling_profiler_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(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 <assert.h>
6 #include <dlfcn.h>
7 #include <mach/mach.h>
8 #include <mach/thread_status.h>
9 #include <mach-o/swap.h>
10 #include <stdlib.h>
11
12 #include <map>
13
14 #include "base/logging.h"
15 #include "base/md5.h"
16 #include "base/profiler/native_stack_sampler.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/time/time.h"
19
20 namespace base {
21
22 namespace {
23
24 // Copy of x86_64 thread context structure from x86_thread_state64_t type.
25 // Copied struct since fields can have different names on different versions of
26 // Darwin.
27 struct ThreadContext {
28 uint64_t rax;
29 uint64_t rbx;
30 uint64_t rcx;
31 uint64_t rdx;
32 uint64_t rdi;
33 uint64_t rsi;
34 uint64_t rbp;
35 uint64_t rsp;
36 uint64_t r8;
37 uint64_t r9;
38 uint64_t r10;
39 uint64_t r11;
40 uint64_t r12;
41 uint64_t r13;
42 uint64_t r14;
43 uint64_t r15;
44 uint64_t rip;
45 uint64_t rflags;
46 uint64_t cs;
47 uint64_t fs;
48 uint64_t gs;
49 };
50
51 // Struct for stack walking (represents stack state on any function call that
52 // pushes a frame pointer).
53 struct StackFrame {
54 // Pointer to caller's frame (rbp).
55 uintptr_t prev;
56 // Address in caller for callee to return to.
57 uintptr_t return_addr;
58 };
59
60 // Overwrites |dst| with StackFrame referenced in |src|. Returns true if stack
61 // jump was successful. Failure implies address in |src| is corrupt.
62 bool SafeJump(uintptr_t src, StackFrame* dst) {
63 vm_size_t ignored_bytes_copied = 0;
64 return vm_read_overwrite(mach_task_self(), (vm_address_t)src,
65 (vm_size_t)sizeof(StackFrame), (vm_address_t)dst,
66 &ignored_bytes_copied) == KERN_SUCCESS;
67 }
68
69 // Functions related to retrieving Mach-O Identifer
70 //
71 // These functions were cannibalized from Mach-O Identifier procedures found in
72 // breakpad/src/common/mac. Support for non-X86_64 architectures and MD5 IDs
73 // were removed to simplify the code.
74
75 // Returns offset in bytes where the x86_64 header is located in binary
76 // loaded at |module_addr|. Returns 0 if |module_addr| is not a valid FAT
77 // Mach-O binary or has not been built for x86_64.
78 off_t GetMach64HeaderOffset(const void* module_addr) {
79 fat_header hdr;
80 memcpy(&hdr, module_addr, sizeof(hdr));
81 if (hdr.magic != FAT_MAGIC && hdr.magic != FAT_CIGAM)
82 return 0;
83
84 if (hdr.magic == FAT_CIGAM)
85 swap_fat_header(&hdr, NXHostByteOrder());
86
87 // Search all FAT architectures for x86_64.
88 off_t offset = sizeof(hdr);
89 fat_arch arch;
90 for (uint32_t i = 0; i < hdr.nfat_arch; ++i) {
91 memcpy(&arch, reinterpret_cast<const char*>(module_addr) + offset,
92 sizeof(arch));
93
94 if (NXHostByteOrder() != NX_BigEndian)
95 swap_fat_arch(&arch, 1, NXHostByteOrder());
96
97 if (arch.cputype == CPU_TYPE_X86_64)
98 return arch.offset;
99 offset += sizeof(arch);
100 }
101 return 0;
102 }
103
104 // Returns true if Mach-O binary at |module_addr| was built specifically for
105 // x86_64 cpu architecture.
106 bool IsX64Header(const void* module_addr) {
107 mach_header_64 hdr;
108 memcpy(&hdr, module_addr, sizeof(hdr));
109 if (hdr.magic != MH_MAGIC_64 && hdr.magic != MH_CIGAM_64)
110 return false;
111 if (hdr.magic == MH_CIGAM_64)
112 swap_mach_header_64(&hdr, NXHostByteOrder());
113
114 return (hdr.cputype == CPU_TYPE_X86_64);
115 }
116
117 // Fills |id| with the UUID of the x86_64 Mach-O binary loaded at |module_addr|.
118 // |offset| is the offset in bytes into |module_addr| where the x86_64 header
119 // is located. |offset| is only relevant if binary is FAT and contains
120 // multiple architecture headers. See spec here:
121 // https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptu al/MachORuntime/
122 // Returns false if header is malformed or the
123 // header does not specify the UUID load command.
124 bool GetX64UUIDAt(const void* module_addr, unsigned char id[16], off_t offset) {
125 mach_header_64 hdr;
126 if (!memcpy(&hdr, reinterpret_cast<const char*>(module_addr) + offset,
127 sizeof(hdr)) ||
128 (hdr.magic != MH_MAGIC_64 && hdr.magic != MH_CIGAM_64))
129 return false;
130
131 bool swap = hdr.magic == MH_CIGAM_64;
132 if (swap)
133 swap_mach_header_64(&hdr, NXHostByteOrder());
134
135 // Search all load commands for UUID command.
136 offset += sizeof(hdr);
137 load_command cmd;
138 for (uint32_t i = 0; i < hdr.ncmds; ++i) {
139 const void* command_loc =
140 reinterpret_cast<const char*>(module_addr) + offset;
141 memcpy(&cmd, command_loc, sizeof(cmd));
142
143 if (swap)
144 swap_load_command(&cmd, NXHostByteOrder());
145 if (cmd.cmd == LC_UUID) {
146 uuid_command uuid_cmd;
147 memcpy(&uuid_cmd, command_loc, sizeof(uuid_cmd));
148 if (swap)
149 swap_uuid_command(&uuid_cmd, NXHostByteOrder());
150 // STATIC assert that length (uuid_cmd.uuid == id)
robliao 2015/09/14 23:28:06 Remove comment since we can see the assertion belo
sydli 2015/09/15 00:20:13 My bad- done.
151 static_assert(sizeof(id) == sizeof(uuid_cmd.uuid));
152 memcpy(id, &uuid_cmd.uuid, sizeof(uuid_cmd));
robliao 2015/09/14 23:28:06 Ah, so this was a bug before? ;-) The comment sti
sydli 2015/09/15 00:20:13 Since parameter arrays are passed as pointers, the
153 return true;
154 }
155 offset += cmd.cmdsize;
156 }
157 return false;
158 }
159
160 // Fills |id| with Mach-O UUID retrieved from Mach-O binary loaded at
161 // |module_addr|. This function returns false if the binary was not built for
162 // X86_64 or if UUID cannot be found.
163 bool GetUUID(const void* module_addr, unsigned char id[16]) {
164 off_t offset = 0;
165 if (!IsX64Header(module_addr) &&
166 !(offset = GetMach64HeaderOffset(module_addr)))
167 return false;
168 return GetX64UUIDAt(module_addr, id, offset);
169 }
170
171 // Returns hex encoding of a 16-byte ID for binary loaded at |module_addr|.
172 // Returns empty string if UUID cannot be found at |module_addr|.
173 std::string GetUniqueId(const void* module_addr) {
174 unsigned char id[16];
175 if (!GetUUID(module_addr, id))
176 return "";
177 return HexEncode(id, 16);
178 }
179
180 // Functions related to grabbing a stack trace --------------------------------
181
182 // Fills |state| with |target_thread|'s context.
183 bool GetThreadState(thread_act_t target_thread, ThreadContext* state) {
184 mach_msg_type_number_t count =
185 static_cast<mach_msg_type_number_t>(MACHINE_THREAD_STATE_COUNT);
186 return thread_get_state(target_thread, x86_THREAD_STATE64,
187 reinterpret_cast<thread_state_t>(state),
188 &count) == KERN_SUCCESS;
189 }
190
191 // Walks |thread_handle|'s stack and fills |instruction_pointers|.
192 // Returns number of frames in stack, unless there's a corrupt frame pointer
193 // (likely if module compiled with -fomit-base-pointer), in which this function
194 // will return the number of frames up until the frame with a corrupt frame
195 // pointer. This procedure occurs while thread is suspended, so it should take
196 // as little time as possible.
197 int RecordStack(mach_port_t thread_handle,
198 int instruction_pointers_size,
199 uintptr_t instruction_pointers[]) {
200 ThreadContext state;
201 if (!GetThreadState(thread_handle, &state))
202 return 0;
203
204 StackFrame frame;
205 frame.prev = state.rbp;
206 int i = 0;
207 for (; i < instruction_pointers_size; i++) {
208 // Three cases for end-of-stack condition:
209 // 1) We tried to jump off the stack.
210 // 2) We jumped to a lower address.
211 // 3) We reached a return (instruction) address of 0.
212 uintptr_t old_esp = frame.prev;
213 if (!SafeJump(frame.prev, &frame) || frame.prev < old_esp ||
214 !frame.return_addr) {
215 return i;
216 }
217 instruction_pointers[i] = frame.return_addr;
218 }
219 return i;
220 }
221
222 // Adds library referenced by |instruction_pointer| to |sample| and |modules|.
223 // Records library's (1) filepath, (2) base address, and (3) unique ID.
224 void AddModule(StackSamplingProfiler::Sample* sample,
225 std::vector<StackSamplingProfiler::Module>* modules,
226 std::map<void*, size_t>* module_to_index,
227 const uintptr_t instruction_pointer) {
228 char filepath[PATH_MAX + 1];
229 Dl_info inf;
230 dladdr(reinterpret_cast<const void*>(instruction_pointer), &inf);
231 auto module_index = module_to_index->find(inf.dli_fbase);
232 if (module_index == module_to_index->end()) {
233 realpath(inf.dli_fname, filepath);
234 StackSamplingProfiler::Module module(
235 inf.dli_fbase, GetUniqueId(inf.dli_fbase), base::FilePath(filepath));
236 modules->push_back(module);
237
238 module_index = module_to_index->
239 insert(std::make_pair(inf.dli_fbase, modules->size() - 1)).first;
240 }
241 sample->push_back(StackSamplingProfiler::Frame(
242 reinterpret_cast<const void*>(instruction_pointer),
243 module_index->second));
244 }
245
246 // Fills |sample| with Frames and Modules referenced by |instruction_pointers|.
247 void FillSample(const uintptr_t instruction_pointers[],
248 std::vector<StackSamplingProfiler::Module>* modules,
249 int stack_depth,
250 StackSamplingProfiler::Sample* sample) {
251 std::map<void*, size_t> module_index;
252 for (int i = 0; i < stack_depth; i++) {
253 AddModule(sample, modules, &module_index, instruction_pointers[i]);
254 }
255 }
256
257 // NativeStackSamplerMac ------------------------------------------------------
258
259 class NativeStackSamplerMac : public NativeStackSampler {
260 public:
261 explicit NativeStackSamplerMac(pid_t thread_handle);
262 ~NativeStackSamplerMac() override;
263
264 // StackSamplingProfiler::NativeStackSampler:
265 void ProfileRecordingStarting(
266 std::vector<StackSamplingProfiler::Module>* modules) override;
267 void RecordStackSample(StackSamplingProfiler::Sample* sample) override;
268 void ProfileRecordingStopped() override;
269
270 static const int kMaxStackSize = 64;
robliao 2015/09/14 23:28:05 Constants go before the constructor. https://goog
sydli 2015/09/15 00:20:13 Done.
271
272 private:
273 mach_port_t thread_handle_;
274
275 // Weak. Points to the modules associated with the profile being recorded
276 // between ProfileRecordingStarting() and ProfileRecordingStopped().
277 std::vector<StackSamplingProfiler::Module>* current_modules_;
278
279 DISALLOW_COPY_AND_ASSIGN(NativeStackSamplerMac);
280 };
281
282 // The PlatformThreadId of the given thread is actually a typedef of
283 // mach_port_t.
284 // (base/threading/platform_thread_posix.cc:128)
285 NativeStackSamplerMac::NativeStackSamplerMac(pid_t thread_handle)
286 : thread_handle_(static_cast<mach_port_t>(thread_handle)) {}
287
288 NativeStackSamplerMac::~NativeStackSamplerMac() {}
289
290 void NativeStackSamplerMac::ProfileRecordingStarting(
291 std::vector<StackSamplingProfiler::Module>* modules) {
292 current_modules_ = modules;
293 }
294
295 void NativeStackSamplerMac::RecordStackSample(
296 StackSamplingProfiler::Sample* sample) {
297 DCHECK(current_modules_);
298 uintptr_t instruction_pointers[kMaxStackSize] = {0};
robliao 2015/09/14 23:28:05 Oh yeah, and {} should work here.
sydli 2015/09/15 00:20:13 Done.
299
300 thread_suspend(thread_handle_);
301 int stack_depth =
302 RecordStack(thread_handle_, kMaxStackSize, instruction_pointers);
303 thread_resume(thread_handle_);
304 FillSample(instruction_pointers, current_modules_, stack_depth, sample);
305 }
306
307 void NativeStackSamplerMac::ProfileRecordingStopped() {
308 current_modules_ = nullptr;
309 }
310
311 } // namespace
312
313 scoped_ptr<NativeStackSampler> NativeStackSampler::Create(
314 PlatformThreadId thread_id) {
315 #if defined(OS_MACOSX) && !defined(OS_NACL)
316 return scoped_ptr<NativeStackSampler>(new NativeStackSamplerMac(thread_id));
317 #endif
318 return scoped_ptr<NativeStackSampler>();
319 }
320
321 } // namespace base
OLDNEW
« no previous file with comments | « base/base.gypi ('k') | base/profiler/stack_sampling_profiler_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698