| 6 |
| 7 | #include <signal.h> |
| 8 | #include <sys/time.h> |
| 9 | #include <ucontext.h> |
| 10 | #include <unistd.h> |
| 11 |
| 12 | #include <atomic> |
| 13 |
| 14 | #include "base/android/library_loader/anchor_functions.h" |
| 15 | #include "base/android/orderfile/orderfile_buildflags.h" |
| 16 | #include "base/android/reached_addresses_bitset.h" |
| 17 | #include "base/base_switches.h" |
| 18 | #include "base/bind.h" |
| 19 | #include "base/command_line.h" |
| 20 | #include "base/feature_list.h" |
| 21 | #include "base/files/file_path.h" |
| 22 | #include "base/files/file_util.h" |
| 23 | #include "base/files/important_file_writer.h" |
| 24 | #include "base/linux_util.h" |
| 25 | #include "base/logging.h" |
| 26 | #include "base/no_destructor.h" |
| 27 | #include "base/optional.h" |
| 28 | #include "base/path_service.h" |
| 29 | #include "base/scoped_generic.h" |
| 30 | #include "base/single_thread_task_runner.h" |
| 31 | #include "base/strings/string_piece.h" |
| 32 | #include "base/strings/stringprintf.h" |
| 33 | #include "base/synchronization/lock.h" |
| 34 | #include "base/threading/thread.h" |
| 35 | #include "base/timer/timer.h" |
| 36 |
| 37 | #if !BUILDFLAG(SUPPORTS_CODE_ORDERING) |
| 38 | #error Code ordering support is required for the reached code profiler. |
| 39 | #endif |
| 40 |
| 41 | namespace base { |
| 42 | namespace android { |
| 43 |
| 44 | namespace { |
| 45 |
| 46 | #if !defined(NDEBUG) || defined(COMPONENT_BUILD) |
| 47 | // Always disabled for debug builds to avoid hitting a limit of signal |
| 48 | // interrupts that can get delivered into a single HANDLE_EINTR. Also |
| 49 | // debugging experience would be bad if there are a lot of signals flying |
| 50 | // around. |
| 51 | // Always disabled for component builds because in this case the code is not |
| 52 | // organized in one contiguous region which is required for the reached code |
| 53 | // profiler. |
| 54 | constexpr const bool kConfigurationSupported = false; |
| 55 | #else |
| 56 | constexpr const bool kConfigurationSupported = true; |
| 57 | #endif |
| 58 |
| 59 | constexpr const char kDumpToFileFlag[] = "reached-code-profiler-dump-to-file"; |
| 60 |
| 61 | constexpr uint64_t kIterationsBeforeSkipping = 50; |
| 62 | constexpr uint64_t kIterationsBetweenUpdates = 100; |
| 63 | constexpr int kProfilerSignal = SIGURG; |
| 64 |
| 65 | constexpr base::TimeDelta kSamplingInterval = |
| 66 | base::TimeDelta::FromMilliseconds(10); |
| 67 | constexpr base::TimeDelta kDumpInterval = base::TimeDelta::FromSeconds(30); |
| 68 |
| 69 | void HandleSignal(int signal, siginfo_t* info, void* context) { |
| 70 | if (signal != kProfilerSignal) |
| 71 | return; |
| 72 |
| 73 | ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context); |
| 74 | uint32_t address = ucontext->uc_mcontext.arm_pc; |
| 75 | ReachedAddressesBitset::GetTextBitset()->RecordAddress(address); |
| 76 | } |
| 77 |
| 78 | struct ScopedTimerCloseTraits { |
| 79 | static base::Optional<timer_t> InvalidValue() { return base::nullopt; } |
| 80 |
| 81 | static void Free(base::Optional<timer_t> x) { timer_delete(*x); } |
| 82 | }; |
| 83 |
| 84 | // RAII object holding an interval timer. |
| 85 | using ScopedTimer = |
| 86 | base::ScopedGeneric<base::Optional<timer_t>, ScopedTimerCloseTraits>; |
| 87 |
| 88 | void DumpToFile(const base::FilePath& path, |
| 89 | scoped_refptr<base::SingleThreadTaskRunner> task_runner) { |
| 90 | DCHECK(task_runner->BelongsToCurrentThread()); |
| 91 |
| 92 | auto dir_path = path.DirName(); |
| 93 | if (!base::DirectoryExists(dir_path) && !base::CreateDirectory(dir_path)) { |
| 94 | PLOG(ERROR) << "Could not create " << dir_path; |
| 95 | return; |
| 96 | } |
| 97 |
| 98 | std::vector<uint32_t> reached_offsets = |
| 99 | ReachedAddressesBitset::GetTextBitset()->GetReachedOffsets(); |
| 100 | base::StringPiece contents( |
| 101 | reinterpret_cast<const char*>(reached_offsets.data()), |
| 102 | reached_offsets.size()); |
| 103 | if (!base::ImportantFileWriter::WriteFileAtomically(path, contents, |
| 104 | "ReachedDump")) { |
| 105 | LOG(ERROR) << "Could not write reached dump into " << path; |
| 106 | } |
| 107 |
| 108 | task_runner->PostDelayedTask( |
| 109 | FROM_HERE, base::BindOnce(&DumpToFile, path, task_runner), kDumpInterval); |
| 110 | } |
| 111 |
| 112 | class ReachedCodeProfiler { |
| 113 | public: |
| 114 | static ReachedCodeProfiler* GetInstance() { |
| 115 | static base::NoDestructor<ReachedCodeProfiler> instance; |
| 116 | return instance.get(); |
| 117 | } |
| 118 |
| 119 | // Starts to periodically send |kProfilerSignal| to all threads. |
| 120 | void Start(LibraryProcessType library_process_type) { |
| 121 | if (is_enabled_) |
| 122 | return; |
| 123 |
| 124 | // Set |kProfilerSignal| signal handler. |
| 125 | // TODO(crbug.com/916263): consider restoring |old_handler| after the |
| 126 | // profiler gets stopped. |
| 127 | struct sigaction old_handler; |
| 128 | struct sigaction sa; |
| 129 | sigemptyset(&sa.sa_mask); |
| 130 | sa.sa_sigaction = &HandleSignal; |
| 131 | sa.sa_flags = SA_RESTART | SA_SIGINFO; |
| 132 | int ret = sigaction(kProfilerSignal, &sa, &old_handler); |
| 133 | if (ret) { |
| 134 | PLOG(ERROR) << "Error setting signal handler. The reached code profiler " |
| 135 | "is disabled"; |
| 136 | return; |
| 137 | } |
| 138 |
| 139 | // Create a new interval timer. |
| 140 | struct sigevent sevp; |
| 141 | memset(&sevp, 0, sizeof(sevp)); |
| 142 | sevp.sigev_notify = SIGEV_THREAD; |
| 143 | sevp.sigev_notify_function = &OnTimerNotify; |
| 144 | timer_t timerid; |
| 145 | ret = timer_create(CLOCK_PROCESS_CPUTIME_ID, &sevp, &timerid); |
| 146 | if (ret) { |
| 147 | PLOG(ERROR) |
| 148 | << "timer_create() failed. The reached code profiler is disabled"; |
| 149 | return; |
| 150 | } |
| 151 |
| 152 | timer_.reset(timerid); |
| 153 |
| 154 | // Start the interval timer. |
| 155 | struct itimerspec its; |
| 156 | memset(&its, 0, sizeof(its)); |
| 157 | its.it_interval.tv_nsec = kSamplingInterval.InNanoseconds(); |
| 158 | its.it_value = its.it_interval; |
| 159 | ret = timer_settime(timerid, 0, &its, nullptr); |
| 160 | if (ret) { |
| 161 | PLOG(ERROR) |
| 162 | << "timer_settime() failed. The reached code profiler is disabled"; |
| 163 | return; |
| 164 | } |
| 165 |
| 166 | if (library_process_type == PROCESS_BROWSER) |
| 167 | StartDumpingReachedCode(); |
| 168 |
| 169 | is_enabled_ = true; |
| 170 | } |
| 171 |
| 172 | // Stops profiling. |
| 173 | void Stop() { |
| 174 | timer_.reset(); |
| 175 | dumping_thread_.reset(); |
| 176 | is_enabled_ = false; |
| 177 | } |
| 178 |
| 179 | // Returns whether the profiler is currently enabled. |
| 180 | bool IsEnabled() { return is_enabled_; } |
| 181 |
| 182 | private: |
| 183 | ReachedCodeProfiler() |
| 184 | : current_pid_(getpid()), iteration_number_(0), is_enabled_(false) {} |
| 185 |
| 186 | static void OnTimerNotify(sigval_t ignored) { |
| 187 | ReachedCodeProfiler::GetInstance()->SendSignalToAllThreads(); |
| 188 | } |
| 189 |
| 190 | void SendSignalToAllThreads() { |
| 191 | // This code should be thread-safe. |
| 192 | base::AutoLock scoped_lock(lock_); |
| 193 | ++iteration_number_; |
| 194 |
| 195 | if (iteration_number_ <= kIterationsBeforeSkipping || |
| 196 | iteration_number_ % kIterationsBetweenUpdates == 0) { |
| 197 | tids_.clear(); |
| 198 | if (!base::GetThreadsForProcess(current_pid_, &tids_)) { |
| 199 | LOG(WARNING) << "Failed to get a list of threads for process " |
| 200 | << current_pid_; |
| 201 | return; |
| 202 | } |
| 203 | } |
| 204 |
| 205 | pid_t current_tid = gettid(); |
| 206 | for (pid_t tid : tids_) { |
| 207 | if (tid != current_tid) |
| 208 | tgkill(current_pid_, tid, kProfilerSignal); |
| 209 | } |
| 210 | } |
| 211 |
| 212 | void StartDumpingReachedCode() { |
| 213 | const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); |
| 214 | if (!cmdline->HasSwitch(kDumpToFileFlag)) |
| 215 | return; |
| 216 |
| 217 | base::FilePath dir_path(cmdline->GetSwitchValueASCII(kDumpToFileFlag)); |
| 218 | if (dir_path.empty()) { |
| 219 | if (!base::PathService::Get(base::DIR_CACHE, &dir_path)) { |
| 220 | LOG(WARNING) << "Failed to get cache dir path."; |
| 221 | return; |
| 222 | } |
| 223 | } |
| 224 |
| 225 | auto file_path = |
| 226 | dir_path.Append(base::StringPrintf("reached-code-%d.txt", getpid())); |
| 227 |
| 228 | dumping_thread_ = |
| 229 | std::make_unique<base::Thread>("ReachedCodeProfilerDumpingThread"); |
| 230 | base::Thread::Options options; |
| 231 | options.priority = base::ThreadPriority::BACKGROUND; |
| 232 | dumping_thread_->StartWithOptions(options); |
| 233 | dumping_thread_->task_runner()->PostDelayedTask( |
| 234 | FROM_HERE, |
| 235 | base::BindOnce(&DumpToFile, file_path, dumping_thread_->task_runner()), |
| 236 | kDumpInterval); |
| 237 | } |
| 238 |
| 239 | base::Lock lock_; |
| 240 | std::vector<pid_t> tids_; |
| 241 | const pid_t current_pid_; |
| 242 | uint64_t iteration_number_; |
| 243 | ScopedTimer timer_; |
| 244 | std::unique_ptr<base::Thread> dumping_thread_; |
| 245 |
| 246 | bool is_enabled_; |
| 247 |
| 248 | friend class NoDestructor<ReachedCodeProfiler>; |
| 249 |
| 250 | DISALLOW_COPY_AND_ASSIGN(ReachedCodeProfiler); |
| 251 | }; |
| 252 |
| 253 | bool ShouldEnableReachedCodeProfiler() { |
| 254 | if (!kConfigurationSupported) |
| 255 | return false; |
| 256 |
| 257 | const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); |
| 258 | return cmdline->HasSwitch(switches::kEnableReachedCodeProfiler); |
| 259 | } |
| 260 |
| 261 | } // namespace |
| 262 |
| 263 | void InitReachedCodeProfilerAtStartup(LibraryProcessType library_process_type) { |
| 264 | // The profiler shouldn't be run as part of webview. |
| 265 | CHECK(library_process_type == PROCESS_BROWSER || |
| 266 | library_process_type == PROCESS_CHILD); |
| 267 |
| 268 | if (!ShouldEnableReachedCodeProfiler()) |
| 269 | return; |
| 270 |
| 271 | ReachedCodeProfiler::GetInstance()->Start(library_process_type); |
| 272 | } |
| 273 |
| 274 | bool IsReachedCodeProfilerEnabled() { |
| 275 | return ReachedCodeProfiler::GetInstance()->IsEnabled(); |
| 276 | } |
| 277 |
| 278 | bool IsReachedCodeProfilerSupported() { |
| 279 | return kConfigurationSupported; |
| 280 | } |
| 281 |
| 282 | } // namespace android |
| 283 | } // namespace base |
| 284 |