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

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

Issue 2848683006: Implement the NativeStackSampler for the Mac. (Closed)
Patch Set: fix Created 3 years, 7 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/BUILD.gn ('k') | base/profiler/native_stack_sampler_win.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 2017 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 "base/profiler/native_stack_sampler.h"
6
7 #include <dlfcn.h>
8 #include <libkern/OSByteOrder.h>
9 #include <libunwind.h>
10 #include <mach-o/swap.h>
11 #include <mach/kern_return.h>
12 #include <mach/mach.h>
13 #include <mach/thread_act.h>
14 #include <pthread.h>
15 #include <sys/resource.h>
16 #include <sys/syslimits.h>
17
18 #include <algorithm>
19 #include <map>
20 #include <memory>
21
22 #include "base/logging.h"
23 #include "base/mac/mach_logging.h"
24 #include "base/macros.h"
25 #include "base/memory/ptr_util.h"
26 #include "base/strings/string_number_conversions.h"
27
28 namespace base {
29
30 namespace {
31
32 // Miscellaneous --------------------------------------------------------------
33
34 size_t StackCopyBufferSize() {
35 static size_t stack_size = 0;
36 if (stack_size)
37 return stack_size;
38
39 // In platform_thread_mac's GetDefaultThreadStackSize(), RLIMIT_STACK is used
40 // for all stacks, not just the main thread's, so it is good for use here.
41 struct rlimit stack_rlimit;
42 if (getrlimit(RLIMIT_STACK, &stack_rlimit) == 0 &&
43 stack_rlimit.rlim_cur != RLIM_INFINITY) {
44 stack_size = stack_rlimit.rlim_cur;
45 return stack_size;
46 }
47
48 // If getrlimit somehow fails, return the default macOS main thread stack size
49 // of 8 MB (DFLSSIZ in <i386/vmparam.h>) with extra wiggle room.
50 return 12 * 1024 * 1024;
51 }
52
53 // Stack walking --------------------------------------------------------------
54
55 // Fills |state| with |target_thread|'s context.
56 //
57 // Note that this is called while a thread is suspended. Make very very sure
58 // that no shared resources (e.g. memory allocators) are used for the duration
59 // of this function.
60 bool GetThreadState(thread_act_t target_thread, x86_thread_state64_t* state) {
61 mach_msg_type_number_t count =
62 static_cast<mach_msg_type_number_t>(x86_THREAD_STATE64_COUNT);
63 return thread_get_state(target_thread, x86_THREAD_STATE64,
64 reinterpret_cast<thread_state_t>(state),
65 &count) == KERN_SUCCESS;
66 }
67
68 // If the value at |pointer| points to the original stack, rewrites it to point
69 // to the corresponding location in the copied stack.
70 //
71 // Note that this is called while a thread is suspended. Make very very sure
72 // that no shared resources (e.g. memory allocators) are used for the duration
73 // of this function.
74 uintptr_t RewritePointerIfInOriginalStack(
75 const uintptr_t* original_stack_bottom,
76 const uintptr_t* original_stack_top,
77 uintptr_t* stack_copy_bottom,
78 uintptr_t pointer) {
79 uintptr_t original_stack_bottom_int =
80 reinterpret_cast<uintptr_t>(original_stack_bottom);
81 uintptr_t original_stack_top_int =
82 reinterpret_cast<uintptr_t>(original_stack_top);
83 uintptr_t stack_copy_bottom_int =
84 reinterpret_cast<uintptr_t>(stack_copy_bottom);
85
86 if ((pointer < original_stack_bottom_int) ||
87 (pointer >= original_stack_top_int)) {
88 return pointer;
89 }
90
91 return stack_copy_bottom_int + (pointer - original_stack_bottom_int);
92 }
93
94 // Copies the stack to a buffer while rewriting possible pointers to locations
95 // within the stack to point to the corresponding locations in the copy. This is
96 // necessary to handle stack frames with dynamic stack allocation, where a
97 // pointer to the beginning of the dynamic allocation area is stored on the
98 // stack and/or in a non-volatile register.
99 //
100 // Eager rewriting of anything that looks like a pointer to the stack, as done
101 // in this function, does not adversely affect the stack unwinding. The only
102 // other values on the stack the unwinding depends on are return addresses,
103 // which should not point within the stack memory. The rewriting is guaranteed
104 // to catch all pointers because the stacks are guaranteed by the ABI to be
105 // sizeof(void*) aligned.
106 //
107 // Note that this is called while a thread is suspended. Make very very sure
108 // that no shared resources (e.g. memory allocators) are used for the duration
109 // of this function.
110 void CopyStackAndRewritePointers(uintptr_t* stack_copy_bottom,
111 const uintptr_t* original_stack_bottom,
112 const uintptr_t* original_stack_top,
113 x86_thread_state64_t* thread_state)
114 NO_SANITIZE("address") {
115 size_t count = original_stack_top - original_stack_bottom;
116 for (size_t pos = 0; pos < count; ++pos) {
117 stack_copy_bottom[pos] = RewritePointerIfInOriginalStack(
118 original_stack_bottom, original_stack_top, stack_copy_bottom,
119 original_stack_bottom[pos]);
120 }
121
122 uint64_t* rewrite_registers[] = {&thread_state->__rbx, &thread_state->__rbp,
123 &thread_state->__rsp, &thread_state->__r12,
124 &thread_state->__r13, &thread_state->__r14,
125 &thread_state->__r15};
126 for (auto* reg : rewrite_registers) {
127 *reg = RewritePointerIfInOriginalStack(
128 original_stack_bottom, original_stack_top, stack_copy_bottom, *reg);
129 }
130 }
131
132 // Walks the stack represented by |unwind_context|, calling back to the provided
133 // lambda for each frame. Returns false if an error occurred, otherwise returns
134 // true.
135 template <typename StackFrameCallback>
136 void WalkStackFromContext(unw_context_t* unwind_context,
137 size_t* frame_count,
138 const StackFrameCallback& callback) {
139 unw_cursor_t unwind_cursor;
140 unw_init_local(&unwind_cursor, unwind_context);
141
142 int step_result;
143 unw_word_t ip;
144 do {
145 ++(*frame_count);
146 unw_get_reg(&unwind_cursor, UNW_REG_IP, &ip);
147
148 callback(static_cast<uintptr_t>(ip));
149
150 step_result = unw_step(&unwind_cursor);
151 } while (step_result > 0);
152 }
153
154 // Walks the stack represented by |thread_state|, calling back to the provided
155 // lambda for each frame.
156 template <typename StackFrameCallback>
157 void WalkStack(const x86_thread_state64_t& thread_state,
158 uintptr_t stack_top,
159 const StackFrameCallback& callback) {
160 size_t frame_count = 0;
161 // This uses libunwind to walk the stack. libunwind is designed to be used for
162 // a thread to walk its own stack. This creates two problems.
163
164 // Problem 1: There is no official way to create a unw_context other than to
165 // create it from the current state of the current thread's stack. To get
166 // around this, forge a context. A unw_context is just a copy of the 16 main
167 // registers followed by the instruction pointer, nothing more.
168 // Coincidentally, the first 17 items of the x86_thread_state64_t type are
169 // exactly those registers in exactly the same order, so just bulk copy them
170 // over.
171 unw_context_t unwind_context;
172 memcpy(&unwind_context, &thread_state, sizeof(uintptr_t) * 17);
173 WalkStackFromContext(&unwind_context, &frame_count, callback);
174
175 // The second problem is one-frame walks, but for now see if this one walk
176 // crashes.
177 }
178
179 // Module identifiers ---------------------------------------------------------
180
181 // Returns the hex encoding of a 16-byte ID for the binary loaded at
182 // |module_addr|. Returns an empty string if the UUID cannot be found at
183 // |module_addr|.
184 std::string GetUniqueId(const void* module_addr) {
185 const mach_header_64* mach_header =
186 reinterpret_cast<const mach_header_64*>(module_addr);
187 DCHECK_EQ(MH_MAGIC_64, mach_header->magic);
188
189 size_t offset = sizeof(mach_header_64);
190 size_t offset_limit = sizeof(mach_header_64) + mach_header->sizeofcmds;
191 for (uint32_t i = 0; (i < mach_header->ncmds) &&
192 (offset + sizeof(load_command) < offset_limit);
193 ++i) {
194 const load_command* current_cmd = reinterpret_cast<const load_command*>(
195 reinterpret_cast<const uint8_t*>(mach_header) + offset);
196
197 if (offset + current_cmd->cmdsize > offset_limit) {
198 // This command runs off the end of the command list. This is malformed.
199 return std::string();
200 }
201
202 if (current_cmd->cmd == LC_UUID) {
203 if (current_cmd->cmdsize < sizeof(uuid_command)) {
204 // This "UUID command" is too small. This is malformed.
205 return std::string();
206 }
207
208 const uuid_command* uuid_cmd =
209 reinterpret_cast<const uuid_command*>(current_cmd);
210 static_assert(sizeof(uuid_cmd->uuid) == sizeof(uuid_t),
211 "UUID field of UUID command should be 16 bytes.");
212 return HexEncode(&uuid_cmd->uuid, sizeof(uuid_cmd->uuid));
213 }
214 offset += current_cmd->cmdsize;
215 }
216 return std::string();
217 }
218
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 std::map<const void*, size_t>* profile_module_index) {
226 Dl_info inf;
227 if (!dladdr(reinterpret_cast<const void*>(instruction_pointer), &inf))
228 return StackSamplingProfiler::Frame::kUnknownModuleIndex;
229
230 auto module_index = profile_module_index->find(inf.dli_fbase);
231 if (module_index == profile_module_index->end()) {
232 StackSamplingProfiler::Module module(
233 reinterpret_cast<uintptr_t>(inf.dli_fbase), GetUniqueId(inf.dli_fbase),
234 base::FilePath(inf.dli_fname));
235 modules->push_back(module);
236 module_index =
237 profile_module_index
238 ->insert(std::make_pair(inf.dli_fbase, modules->size() - 1))
239 .first;
240 }
241 return module_index->second;
242 }
243
244 // ScopedSuspendThread --------------------------------------------------------
245
246 // Suspends a thread for the lifetime of the object.
247 class ScopedSuspendThread {
248 public:
249 explicit ScopedSuspendThread(mach_port_t thread_port)
250 : thread_port_(thread_suspend(thread_port) == KERN_SUCCESS
251 ? thread_port
252 : MACH_PORT_NULL) {}
253
254 ~ScopedSuspendThread() {
255 if (!was_successful())
256 return;
257
258 kern_return_t kr = thread_resume(thread_port_);
259 MACH_CHECK(kr == KERN_SUCCESS, kr) << "thread_resume";
260 }
261
262 bool was_successful() const { return thread_port_ != MACH_PORT_NULL; }
263
264 private:
265 mach_port_t thread_port_;
266
267 DISALLOW_COPY_AND_ASSIGN(ScopedSuspendThread);
268 };
269
270 // NativeStackSamplerMac ------------------------------------------------------
271
272 class NativeStackSamplerMac : public NativeStackSampler {
273 public:
274 NativeStackSamplerMac(mach_port_t thread_port,
275 AnnotateCallback annotator,
276 NativeStackSamplerTestDelegate* test_delegate);
277 ~NativeStackSamplerMac() override;
278
279 // StackSamplingProfiler::NativeStackSampler:
280 void ProfileRecordingStarting(
281 std::vector<StackSamplingProfiler::Module>* modules) override;
282 void RecordStackSample(StackSamplingProfiler::Sample* sample) override;
283 void ProfileRecordingStopped() override;
284
285 private:
286 // Suspends the thread with |thread_port_|, copies its stack and resumes the
287 // thread, then records the stack frames and associated modules into |sample|.
288 void SuspendThreadAndRecordStack(StackSamplingProfiler::Sample* sample);
289
290 // Weak reference: Mach port for thread being profiled.
291 mach_port_t thread_port_;
292
293 const AnnotateCallback annotator_;
294
295 NativeStackSamplerTestDelegate* const test_delegate_;
296
297 // The stack base address corresponding to |thread_handle_|.
298 const void* const thread_stack_base_address_;
299
300 // The size of the |stack_copy_buffer_|.
301 const size_t stack_copy_buffer_size_;
302
303 // Buffer to use for copies of the stack. We use the same buffer for all the
304 // samples to avoid the overhead of multiple allocations and frees.
305 const std::unique_ptr<unsigned char[]> stack_copy_buffer_;
306
307 // Weak. Points to the modules associated with the profile being recorded
308 // between ProfileRecordingStarting() and ProfileRecordingStopped().
309 std::vector<StackSamplingProfiler::Module>* current_modules_ = nullptr;
310
311 // Maps a module's base address to the corresponding Module's index within
312 // current_modules_.
313 std::map<const void*, size_t> profile_module_index_;
314
315 DISALLOW_COPY_AND_ASSIGN(NativeStackSamplerMac);
316 };
317
318 NativeStackSamplerMac::NativeStackSamplerMac(
319 mach_port_t thread_port,
320 AnnotateCallback annotator,
321 NativeStackSamplerTestDelegate* test_delegate)
322 : thread_port_(thread_port),
323 annotator_(annotator),
324 test_delegate_(test_delegate),
325 thread_stack_base_address_(
326 pthread_get_stackaddr_np(pthread_from_mach_thread_np(thread_port))),
327 stack_copy_buffer_size_(StackCopyBufferSize()),
328 stack_copy_buffer_(new unsigned char[stack_copy_buffer_size_]) {
329 DCHECK(annotator_);
330
331 // This class suspends threads, and those threads might be suspended in dyld.
332 // Therefore, for all the system functions that might be linked in dynamically
333 // that are used while threads are suspended, make calls to them to make sure
334 // that they are linked up.
335 x86_thread_state64_t thread_state;
336 GetThreadState(thread_port_, &thread_state);
337 }
338
339 NativeStackSamplerMac::~NativeStackSamplerMac() {}
340
341 void NativeStackSamplerMac::ProfileRecordingStarting(
342 std::vector<StackSamplingProfiler::Module>* modules) {
343 current_modules_ = modules;
344 profile_module_index_.clear();
345 }
346
347 void NativeStackSamplerMac::RecordStackSample(
348 StackSamplingProfiler::Sample* sample) {
349 DCHECK(current_modules_);
350
351 SuspendThreadAndRecordStack(sample);
352 }
353
354 void NativeStackSamplerMac::ProfileRecordingStopped() {
355 current_modules_ = nullptr;
356 }
357
358 void NativeStackSamplerMac::SuspendThreadAndRecordStack(
359 StackSamplingProfiler::Sample* sample) {
360 x86_thread_state64_t thread_state;
361
362 // Copy the stack.
363
364 uintptr_t new_stack_top = 0;
365 {
366 // IMPORTANT NOTE: Do not do ANYTHING in this in this scope that might
367 // allocate memory, including indirectly via use of DCHECK/CHECK or other
368 // logging statements. Otherwise this code can deadlock on heap locks in the
369 // default heap acquired by the target thread before it was suspended.
370 ScopedSuspendThread suspend_thread(thread_port_);
371 if (!suspend_thread.was_successful())
372 return;
373
374 if (!GetThreadState(thread_port_, &thread_state))
375 return;
376 uintptr_t stack_top =
377 reinterpret_cast<uintptr_t>(thread_stack_base_address_);
378 uintptr_t stack_bottom = thread_state.__rsp;
379 if (stack_bottom >= stack_top)
380 return;
381 uintptr_t stack_size = stack_top - stack_bottom;
382
383 if (stack_size > stack_copy_buffer_size_)
384 return;
385
386 (*annotator_)(sample);
387
388 CopyStackAndRewritePointers(
389 reinterpret_cast<uintptr_t*>(stack_copy_buffer_.get()),
390 reinterpret_cast<uintptr_t*>(stack_bottom),
391 reinterpret_cast<uintptr_t*>(stack_top), &thread_state);
392
393 new_stack_top =
394 reinterpret_cast<uintptr_t>(stack_copy_buffer_.get()) + stack_size;
395 } // ScopedSuspendThread
396
397 if (test_delegate_)
398 test_delegate_->OnPreStackWalk();
399
400 // Walk the stack and record it.
401
402 // Reserve enough memory for most stacks, to avoid repeated allocations.
403 // Approximately 99.9% of recorded stacks are 128 frames or fewer.
404 sample->frames.reserve(128);
405
406 auto* current_modules = current_modules_;
407 auto* profile_module_index = &profile_module_index_;
408 WalkStack(
409 thread_state, new_stack_top,
410 [sample, current_modules, profile_module_index](uintptr_t frame_ip) {
411 sample->frames.push_back(StackSamplingProfiler::Frame(
412 frame_ip,
413 GetModuleIndex(frame_ip, current_modules, profile_module_index)));
414 });
415 }
416
417 } // namespace
418
419 std::unique_ptr<NativeStackSampler> NativeStackSampler::Create(
420 PlatformThreadId thread_id,
421 AnnotateCallback annotator,
422 NativeStackSamplerTestDelegate* test_delegate) {
423 return base::MakeUnique<NativeStackSamplerMac>(thread_id, annotator,
424 test_delegate);
425 }
426
427 } // namespace base
OLDNEW
« no previous file with comments | « base/BUILD.gn ('k') | base/profiler/native_stack_sampler_win.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698