1 // Copyright 2021 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.
4
5 #include "base/profiler/stack_sampler.h"
6
7 #include "base/memory/ptr_util.h"
8 #include "base/profiler/profiler_buildflags.h"
9 #include "build/build_config.h"
10
11 #if BUILDFLAG(IOS_STACK_PROFILER_ENABLED)
12 #include "base/check.h"
13 #include "base/functional/bind.h"
14 #include "base/profiler/frame_pointer_unwinder.h"
15 #include "base/profiler/stack_copier_suspend.h"
16 #include "base/profiler/suspendable_thread_delegate_mac.h"
17 #endif
18
19 namespace base {
20
21 #if BUILDFLAG(IOS_STACK_PROFILER_ENABLED)
22 namespace {
23
CreateUnwinders()24 std::vector<std::unique_ptr<Unwinder>> CreateUnwinders() {
25 std::vector<std::unique_ptr<Unwinder>> unwinders;
26 if (__builtin_available(iOS 12.0, *)) {
27 unwinders.push_back(std::make_unique<FramePointerUnwinder>());
28 }
29 return unwinders;
30 }
31
32 } // namespace
33 #endif
34
35 // static
Create(SamplingProfilerThreadToken thread_token,ModuleCache * module_cache,UnwindersFactory core_unwinders_factory,RepeatingClosure record_sample_callback,StackSamplerTestDelegate * test_delegate)36 std::unique_ptr<StackSampler> StackSampler::Create(
37 SamplingProfilerThreadToken thread_token,
38 ModuleCache* module_cache,
39 UnwindersFactory core_unwinders_factory,
40 RepeatingClosure record_sample_callback,
41 StackSamplerTestDelegate* test_delegate) {
42 DCHECK(!core_unwinders_factory);
43 #if BUILDFLAG(IOS_STACK_PROFILER_ENABLED)
44 return base::WrapUnique(new StackSampler(
45 std::make_unique<StackCopierSuspend>(
46 std::make_unique<SuspendableThreadDelegateMac>(thread_token)),
47 BindOnce(&CreateUnwinders), module_cache,
48 std::move(record_sample_callback), test_delegate));
49 #else
50 return nullptr;
51 #endif
52 }
53
54 // static
GetStackBufferSize()55 size_t StackSampler::GetStackBufferSize() {
56 #if BUILDFLAG(IOS_STACK_PROFILER_ENABLED)
57 size_t stack_size = PlatformThread::GetDefaultThreadStackSize();
58
59 // If getrlimit somehow fails, return the default iOS main thread stack size
60 // of 1 MB with extra wiggle room.
61 return stack_size > 0 ? stack_size : 1536 * 1024;
62 #else
63 return 0;
64 #endif
65 }
66
67 } // namespace base
68