blob: 0db17bbea1855b70fccfe8f7804bc08482daf881 [file] [log] [blame]
Austin Schuh745610d2015-09-06 18:19:50 -07001// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
2// Copyright (c) 2009, Google Inc.
3// All rights reserved.
Brian Silverman20350ac2021-11-17 18:19:55 -08004//
Austin Schuh745610d2015-09-06 18:19:50 -07005// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
Brian Silverman20350ac2021-11-17 18:19:55 -08008//
Austin Schuh745610d2015-09-06 18:19:50 -07009// * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11// * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15// * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
Brian Silverman20350ac2021-11-17 18:19:55 -080018//
Austin Schuh745610d2015-09-06 18:19:50 -070019// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31// ---
32// Author: Sanjay Ghemawat
33// Nabeel Mian
34//
35// Implements management of profile timers and the corresponding signal handler.
36
37#include "config.h"
38#include "profile-handler.h"
39
40#if !(defined(__CYGWIN__) || defined(__CYGWIN32__))
41
42#include <stdio.h>
43#include <errno.h>
44#include <sys/time.h>
45
46#include <list>
47#include <string>
48
49#if HAVE_LINUX_SIGEV_THREAD_ID
50// for timer_{create,settime} and associated typedefs & constants
51#include <time.h>
Brian Silverman20350ac2021-11-17 18:19:55 -080052// for sigevent
53#include <signal.h>
54// for SYS_gettid
55#include <sys/syscall.h>
56
Austin Schuh745610d2015-09-06 18:19:50 -070057// for perftools_pthread_key_create
58#include "maybe_threads.h"
59#endif
60
61#include "base/dynamic_annotations.h"
62#include "base/googleinit.h"
63#include "base/logging.h"
64#include "base/spinlock.h"
65#include "maybe_threads.h"
66
Brian Silverman20350ac2021-11-17 18:19:55 -080067// Some Linux systems don't have sigev_notify_thread_id defined in
68// signal.h (despite having SIGEV_THREAD_ID defined) and also lack
69// working linux/signal.h. So lets workaround. Note, we know that at
70// least on Linux sigev_notify_thread_id is macro.
71//
72// See https://sourceware.org/bugzilla/show_bug.cgi?id=27417 and
73// https://bugzilla.kernel.org/show_bug.cgi?id=200081
74//
75#if __linux__ && HAVE_LINUX_SIGEV_THREAD_ID && !defined(sigev_notify_thread_id)
76#define sigev_notify_thread_id _sigev_un._tid
77#endif
78
Austin Schuh745610d2015-09-06 18:19:50 -070079using std::list;
80using std::string;
81
82// This structure is used by ProfileHandlerRegisterCallback and
83// ProfileHandlerUnregisterCallback as a handle to a registered callback.
84struct ProfileHandlerToken {
85 // Sets the callback and associated arg.
86 ProfileHandlerToken(ProfileHandlerCallback cb, void* cb_arg)
87 : callback(cb),
88 callback_arg(cb_arg) {
89 }
90
91 // Callback function to be invoked on receiving a profile timer interrupt.
92 ProfileHandlerCallback callback;
93 // Argument for the callback function.
94 void* callback_arg;
95};
96
Brian Silverman20350ac2021-11-17 18:19:55 -080097// Blocks a signal from being delivered to the current thread while the object
98// is alive. Unblocks it upon destruction.
99class ScopedSignalBlocker {
100 public:
101 ScopedSignalBlocker(int signo) {
102 sigemptyset(&sig_set_);
103 sigaddset(&sig_set_, signo);
104 RAW_CHECK(sigprocmask(SIG_BLOCK, &sig_set_, NULL) == 0,
105 "sigprocmask (block)");
106 }
107 ~ScopedSignalBlocker() {
108 RAW_CHECK(sigprocmask(SIG_UNBLOCK, &sig_set_, NULL) == 0,
109 "sigprocmask (unblock)");
110 }
111
112 private:
113 sigset_t sig_set_;
114};
115
Austin Schuh745610d2015-09-06 18:19:50 -0700116// This class manages profile timers and associated signal handler. This is a
117// a singleton.
118class ProfileHandler {
119 public:
Brian Silverman20350ac2021-11-17 18:19:55 -0800120 // Registers the current thread with the profile handler.
Austin Schuh745610d2015-09-06 18:19:50 -0700121 void RegisterThread();
122
123 // Registers a callback routine to receive profile timer ticks. The returned
124 // token is to be used when unregistering this callback and must not be
Brian Silverman20350ac2021-11-17 18:19:55 -0800125 // deleted by the caller.
Austin Schuh745610d2015-09-06 18:19:50 -0700126 ProfileHandlerToken* RegisterCallback(ProfileHandlerCallback callback,
127 void* callback_arg);
128
129 // Unregisters a previously registered callback. Expects the token returned
Brian Silverman20350ac2021-11-17 18:19:55 -0800130 // by the corresponding RegisterCallback routine.
Austin Schuh745610d2015-09-06 18:19:50 -0700131 void UnregisterCallback(ProfileHandlerToken* token)
132 NO_THREAD_SAFETY_ANALYSIS;
133
Brian Silverman20350ac2021-11-17 18:19:55 -0800134 // Unregisters all the callbacks and stops the timer(s).
Austin Schuh745610d2015-09-06 18:19:50 -0700135 void Reset();
136
137 // Gets the current state of profile handler.
138 void GetState(ProfileHandlerState* state);
139
140 // Initializes and returns the ProfileHandler singleton.
141 static ProfileHandler* Instance();
142
143 private:
144 ProfileHandler();
145 ~ProfileHandler();
146
147 // Largest allowed frequency.
148 static const int32 kMaxFrequency = 4000;
149 // Default frequency.
150 static const int32 kDefaultFrequency = 100;
151
152 // ProfileHandler singleton.
153 static ProfileHandler* instance_;
154
155 // pthread_once_t for one time initialization of ProfileHandler singleton.
156 static pthread_once_t once_;
157
158 // Initializes the ProfileHandler singleton via GoogleOnceInit.
159 static void Init();
160
Brian Silverman20350ac2021-11-17 18:19:55 -0800161 // Timer state as configured previously.
162 bool timer_running_;
163
164 // The number of profiling signal interrupts received.
Austin Schuh745610d2015-09-06 18:19:50 -0700165 int64 interrupts_ GUARDED_BY(signal_lock_);
166
Brian Silverman20350ac2021-11-17 18:19:55 -0800167 // Profiling signal interrupt frequency, read-only after construction.
Austin Schuh745610d2015-09-06 18:19:50 -0700168 int32 frequency_;
169
Brian Silverman20350ac2021-11-17 18:19:55 -0800170 // ITIMER_PROF (which uses SIGPROF), or ITIMER_REAL (which uses SIGALRM).
171 // Translated into an equivalent choice of clock if per_thread_timer_enabled_
172 // is true.
Austin Schuh745610d2015-09-06 18:19:50 -0700173 int timer_type_;
174
175 // Signal number for timer signal.
176 int signal_number_;
177
178 // Counts the number of callbacks registered.
179 int32 callback_count_ GUARDED_BY(control_lock_);
180
181 // Is profiling allowed at all?
182 bool allowed_;
183
Brian Silverman20350ac2021-11-17 18:19:55 -0800184 // Must be false if HAVE_LINUX_SIGEV_THREAD_ID is not defined.
Austin Schuh745610d2015-09-06 18:19:50 -0700185 bool per_thread_timer_enabled_;
186
187#ifdef HAVE_LINUX_SIGEV_THREAD_ID
188 // this is used to destroy per-thread profiling timers on thread
189 // termination
190 pthread_key_t thread_timer_key;
191#endif
192
Austin Schuh745610d2015-09-06 18:19:50 -0700193 // This lock serializes the registration of threads and protects the
194 // callbacks_ list below.
195 // Locking order:
196 // In the context of a signal handler, acquire signal_lock_ to walk the
197 // callback list. Otherwise, acquire control_lock_, disable the signal
198 // handler and then acquire signal_lock_.
199 SpinLock control_lock_ ACQUIRED_BEFORE(signal_lock_);
200 SpinLock signal_lock_;
201
202 // Holds the list of registered callbacks. We expect the list to be pretty
203 // small. Currently, the cpu profiler (base/profiler) and thread module
204 // (base/thread.h) are the only two components registering callbacks.
205 // Following are the locking requirements for callbacks_:
206 // For read-write access outside the SIGPROF handler:
207 // - Acquire control_lock_
208 // - Disable SIGPROF handler.
209 // - Acquire signal_lock_
210 // For read-only access in the context of SIGPROF handler
211 // (Read-write access is *not allowed* in the SIGPROF handler)
212 // - Acquire signal_lock_
213 // For read-only access outside SIGPROF handler:
214 // - Acquire control_lock_
215 typedef list<ProfileHandlerToken*> CallbackList;
216 typedef CallbackList::iterator CallbackIterator;
217 CallbackList callbacks_ GUARDED_BY(signal_lock_);
218
Brian Silverman20350ac2021-11-17 18:19:55 -0800219 // Starts or stops the interval timer.
220 // Will ignore any requests to enable or disable when
221 // per_thread_timer_enabled_ is true.
222 void UpdateTimer(bool enable) EXCLUSIVE_LOCKS_REQUIRED(signal_lock_);
Austin Schuh745610d2015-09-06 18:19:50 -0700223
224 // Returns true if the handler is not being used by something else.
225 // This checks the kernel's signal handler table.
226 bool IsSignalHandlerAvailable();
227
Brian Silverman20350ac2021-11-17 18:19:55 -0800228 // Signal handler. Iterates over and calls all the registered callbacks.
Austin Schuh745610d2015-09-06 18:19:50 -0700229 static void SignalHandler(int sig, siginfo_t* sinfo, void* ucontext);
230
231 DISALLOW_COPY_AND_ASSIGN(ProfileHandler);
232};
233
234ProfileHandler* ProfileHandler::instance_ = NULL;
235pthread_once_t ProfileHandler::once_ = PTHREAD_ONCE_INIT;
236
237const int32 ProfileHandler::kMaxFrequency;
238const int32 ProfileHandler::kDefaultFrequency;
239
Brian Silverman20350ac2021-11-17 18:19:55 -0800240// If we are LD_PRELOAD-ed against a non-pthreads app, then these functions
241// won't be defined. We declare them here, for that case (with weak linkage)
242// which will cause the non-definition to resolve to NULL. We can then check
243// for NULL or not in Instance.
244extern "C" {
245int pthread_once(pthread_once_t *, void (*)(void)) ATTRIBUTE_WEAK;
246int pthread_kill(pthread_t thread_id, int signo) ATTRIBUTE_WEAK;
Austin Schuh745610d2015-09-06 18:19:50 -0700247
248#if HAVE_LINUX_SIGEV_THREAD_ID
Brian Silverman20350ac2021-11-17 18:19:55 -0800249int timer_create(clockid_t clockid, struct sigevent* evp,
250 timer_t* timerid) ATTRIBUTE_WEAK;
251int timer_delete(timer_t timerid) ATTRIBUTE_WEAK;
252int timer_settime(timer_t timerid, int flags, const struct itimerspec* value,
253 struct itimerspec* ovalue) ATTRIBUTE_WEAK;
254#endif
Austin Schuh745610d2015-09-06 18:19:50 -0700255}
256
Brian Silverman20350ac2021-11-17 18:19:55 -0800257#if HAVE_LINUX_SIGEV_THREAD_ID
258
Austin Schuh745610d2015-09-06 18:19:50 -0700259struct timer_id_holder {
260 timer_t timerid;
261 timer_id_holder(timer_t _timerid) : timerid(_timerid) {}
262};
263
264extern "C" {
265 static void ThreadTimerDestructor(void *arg) {
266 if (!arg) {
267 return;
268 }
269 timer_id_holder *holder = static_cast<timer_id_holder *>(arg);
270 timer_delete(holder->timerid);
271 delete holder;
272 }
273}
274
275static void CreateThreadTimerKey(pthread_key_t *pkey) {
276 int rv = perftools_pthread_key_create(pkey, ThreadTimerDestructor);
277 if (rv) {
278 RAW_LOG(FATAL, "aborting due to pthread_key_create error: %s", strerror(rv));
279 }
280}
281
282static void StartLinuxThreadTimer(int timer_type, int signal_number,
283 int32 frequency, pthread_key_t timer_key) {
284 int rv;
285 struct sigevent sevp;
286 timer_t timerid;
287 struct itimerspec its;
288 memset(&sevp, 0, sizeof(sevp));
289 sevp.sigev_notify = SIGEV_THREAD_ID;
Brian Silverman20350ac2021-11-17 18:19:55 -0800290 sevp.sigev_notify_thread_id = syscall(SYS_gettid);
Austin Schuh745610d2015-09-06 18:19:50 -0700291 sevp.sigev_signo = signal_number;
292 clockid_t clock = CLOCK_THREAD_CPUTIME_ID;
293 if (timer_type == ITIMER_REAL) {
294 clock = CLOCK_MONOTONIC;
295 }
296 rv = timer_create(clock, &sevp, &timerid);
297 if (rv) {
298 RAW_LOG(FATAL, "aborting due to timer_create error: %s", strerror(errno));
299 }
300
301 timer_id_holder *holder = new timer_id_holder(timerid);
302 rv = perftools_pthread_setspecific(timer_key, holder);
303 if (rv) {
304 RAW_LOG(FATAL, "aborting due to pthread_setspecific error: %s", strerror(rv));
305 }
306
307 its.it_interval.tv_sec = 0;
308 its.it_interval.tv_nsec = 1000000000 / frequency;
309 its.it_value = its.it_interval;
310 rv = timer_settime(timerid, 0, &its, 0);
311 if (rv) {
312 RAW_LOG(FATAL, "aborting due to timer_settime error: %s", strerror(errno));
313 }
314}
315#endif
316
317void ProfileHandler::Init() {
318 instance_ = new ProfileHandler();
319}
320
321ProfileHandler* ProfileHandler::Instance() {
322 if (pthread_once) {
323 pthread_once(&once_, Init);
324 }
325 if (instance_ == NULL) {
326 // This will be true on systems that don't link in pthreads,
327 // including on FreeBSD where pthread_once has a non-zero address
328 // (but doesn't do anything) even when pthreads isn't linked in.
329 Init();
330 assert(instance_ != NULL);
331 }
332 return instance_;
333}
334
335ProfileHandler::ProfileHandler()
Brian Silverman20350ac2021-11-17 18:19:55 -0800336 : timer_running_(false),
337 interrupts_(0),
Austin Schuh745610d2015-09-06 18:19:50 -0700338 callback_count_(0),
339 allowed_(true),
Brian Silverman20350ac2021-11-17 18:19:55 -0800340 per_thread_timer_enabled_(false) {
Austin Schuh745610d2015-09-06 18:19:50 -0700341 SpinLockHolder cl(&control_lock_);
342
343 timer_type_ = (getenv("CPUPROFILE_REALTIME") ? ITIMER_REAL : ITIMER_PROF);
344 signal_number_ = (timer_type_ == ITIMER_PROF ? SIGPROF : SIGALRM);
345
346 // Get frequency of interrupts (if specified)
347 char junk;
348 const char* fr = getenv("CPUPROFILE_FREQUENCY");
349 if (fr != NULL && (sscanf(fr, "%u%c", &frequency_, &junk) == 1) &&
350 (frequency_ > 0)) {
351 // Limit to kMaxFrequency
352 frequency_ = (frequency_ > kMaxFrequency) ? kMaxFrequency : frequency_;
353 } else {
354 frequency_ = kDefaultFrequency;
355 }
356
357 if (!allowed_) {
358 return;
359 }
360
361#if HAVE_LINUX_SIGEV_THREAD_ID
362 // Do this early because we might be overriding signal number.
363
364 const char *per_thread = getenv("CPUPROFILE_PER_THREAD_TIMERS");
365 const char *signal_number = getenv("CPUPROFILE_TIMER_SIGNAL");
366
367 if (per_thread || signal_number) {
368 if (timer_create && pthread_once) {
Austin Schuh745610d2015-09-06 18:19:50 -0700369 CreateThreadTimerKey(&thread_timer_key);
370 per_thread_timer_enabled_ = true;
371 // Override signal number if requested.
372 if (signal_number) {
373 signal_number_ = strtol(signal_number, NULL, 0);
374 }
375 } else {
376 RAW_LOG(INFO,
377 "Ignoring CPUPROFILE_PER_THREAD_TIMERS and\n"
378 " CPUPROFILE_TIMER_SIGNAL due to lack of timer_create().\n"
379 " Preload or link to librt.so for this to work");
380 }
381 }
382#endif
383
384 // If something else is using the signal handler,
385 // assume it has priority over us and stop.
386 if (!IsSignalHandlerAvailable()) {
387 RAW_LOG(INFO, "Disabling profiler because signal %d handler is already in use.",
388 signal_number_);
389 allowed_ = false;
390 return;
391 }
392
Brian Silverman20350ac2021-11-17 18:19:55 -0800393 // Install the signal handler.
394 struct sigaction sa;
395 sa.sa_sigaction = SignalHandler;
396 sa.sa_flags = SA_RESTART | SA_SIGINFO;
397 sigemptyset(&sa.sa_mask);
398 RAW_CHECK(sigaction(signal_number_, &sa, NULL) == 0, "sigprof (enable)");
Austin Schuh745610d2015-09-06 18:19:50 -0700399}
400
401ProfileHandler::~ProfileHandler() {
402 Reset();
403#ifdef HAVE_LINUX_SIGEV_THREAD_ID
404 if (per_thread_timer_enabled_) {
405 perftools_pthread_key_delete(thread_timer_key);
406 }
407#endif
408}
409
410void ProfileHandler::RegisterThread() {
411 SpinLockHolder cl(&control_lock_);
412
413 if (!allowed_) {
414 return;
415 }
416
Brian Silverman20350ac2021-11-17 18:19:55 -0800417 // Record the thread identifier and start the timer if profiling is on.
418 ScopedSignalBlocker block(signal_number_);
419 SpinLockHolder sl(&signal_lock_);
420#if HAVE_LINUX_SIGEV_THREAD_ID
421 if (per_thread_timer_enabled_) {
422 StartLinuxThreadTimer(timer_type_, signal_number_, frequency_,
423 thread_timer_key);
424 return;
Austin Schuh745610d2015-09-06 18:19:50 -0700425 }
Brian Silverman20350ac2021-11-17 18:19:55 -0800426#endif
427 UpdateTimer(callback_count_ > 0);
Austin Schuh745610d2015-09-06 18:19:50 -0700428}
429
430ProfileHandlerToken* ProfileHandler::RegisterCallback(
431 ProfileHandlerCallback callback, void* callback_arg) {
432
433 ProfileHandlerToken* token = new ProfileHandlerToken(callback, callback_arg);
434
435 SpinLockHolder cl(&control_lock_);
Austin Schuh745610d2015-09-06 18:19:50 -0700436 {
Brian Silverman20350ac2021-11-17 18:19:55 -0800437 ScopedSignalBlocker block(signal_number_);
Austin Schuh745610d2015-09-06 18:19:50 -0700438 SpinLockHolder sl(&signal_lock_);
439 callbacks_.push_back(token);
Brian Silverman20350ac2021-11-17 18:19:55 -0800440 ++callback_count_;
441 UpdateTimer(true);
Austin Schuh745610d2015-09-06 18:19:50 -0700442 }
Austin Schuh745610d2015-09-06 18:19:50 -0700443 return token;
444}
445
446void ProfileHandler::UnregisterCallback(ProfileHandlerToken* token) {
447 SpinLockHolder cl(&control_lock_);
448 for (CallbackIterator it = callbacks_.begin(); it != callbacks_.end();
449 ++it) {
450 if ((*it) == token) {
451 RAW_CHECK(callback_count_ > 0, "Invalid callback count");
Austin Schuh745610d2015-09-06 18:19:50 -0700452 {
Brian Silverman20350ac2021-11-17 18:19:55 -0800453 ScopedSignalBlocker block(signal_number_);
Austin Schuh745610d2015-09-06 18:19:50 -0700454 SpinLockHolder sl(&signal_lock_);
455 delete *it;
456 callbacks_.erase(it);
Brian Silverman20350ac2021-11-17 18:19:55 -0800457 --callback_count_;
458 if (callback_count_ == 0)
459 UpdateTimer(false);
Austin Schuh745610d2015-09-06 18:19:50 -0700460 }
461 return;
462 }
463 }
464 // Unknown token.
465 RAW_LOG(FATAL, "Invalid token");
466}
467
468void ProfileHandler::Reset() {
469 SpinLockHolder cl(&control_lock_);
Austin Schuh745610d2015-09-06 18:19:50 -0700470 {
Brian Silverman20350ac2021-11-17 18:19:55 -0800471 ScopedSignalBlocker block(signal_number_);
Austin Schuh745610d2015-09-06 18:19:50 -0700472 SpinLockHolder sl(&signal_lock_);
473 CallbackIterator it = callbacks_.begin();
474 while (it != callbacks_.end()) {
475 CallbackIterator tmp = it;
476 ++it;
477 delete *tmp;
478 callbacks_.erase(tmp);
479 }
Brian Silverman20350ac2021-11-17 18:19:55 -0800480 callback_count_ = 0;
481 UpdateTimer(false);
Austin Schuh745610d2015-09-06 18:19:50 -0700482 }
Austin Schuh745610d2015-09-06 18:19:50 -0700483}
484
485void ProfileHandler::GetState(ProfileHandlerState* state) {
486 SpinLockHolder cl(&control_lock_);
Austin Schuh745610d2015-09-06 18:19:50 -0700487 {
Brian Silverman20350ac2021-11-17 18:19:55 -0800488 ScopedSignalBlocker block(signal_number_);
Austin Schuh745610d2015-09-06 18:19:50 -0700489 SpinLockHolder sl(&signal_lock_); // Protects interrupts_.
490 state->interrupts = interrupts_;
491 }
Austin Schuh745610d2015-09-06 18:19:50 -0700492 state->frequency = frequency_;
493 state->callback_count = callback_count_;
494 state->allowed = allowed_;
495}
496
Brian Silverman20350ac2021-11-17 18:19:55 -0800497void ProfileHandler::UpdateTimer(bool enable) {
498 if (per_thread_timer_enabled_) {
499 // Ignore any attempts to disable it because that's not supported, and it's
500 // always enabled so enabling is always a NOP.
Austin Schuh745610d2015-09-06 18:19:50 -0700501 return;
502 }
503
Brian Silverman20350ac2021-11-17 18:19:55 -0800504 if (enable == timer_running_) {
Austin Schuh745610d2015-09-06 18:19:50 -0700505 return;
506 }
Brian Silverman20350ac2021-11-17 18:19:55 -0800507 timer_running_ = enable;
Austin Schuh745610d2015-09-06 18:19:50 -0700508
509 struct itimerval timer;
Brian Silverman20350ac2021-11-17 18:19:55 -0800510 static const int kMillion = 1000000;
511 int interval_usec = enable ? kMillion / frequency_ : 0;
512 timer.it_interval.tv_sec = interval_usec / kMillion;
513 timer.it_interval.tv_usec = interval_usec % kMillion;
Austin Schuh745610d2015-09-06 18:19:50 -0700514 timer.it_value = timer.it_interval;
515 setitimer(timer_type_, &timer, 0);
516}
517
Austin Schuh745610d2015-09-06 18:19:50 -0700518bool ProfileHandler::IsSignalHandlerAvailable() {
519 struct sigaction sa;
520 RAW_CHECK(sigaction(signal_number_, NULL, &sa) == 0, "is-signal-handler avail");
521
522 // We only take over the handler if the current one is unset.
523 // It must be SIG_IGN or SIG_DFL, not some other function.
524 // SIG_IGN must be allowed because when profiling is allowed but
525 // not actively in use, this code keeps the handler set to SIG_IGN.
526 // That setting will be inherited across fork+exec. In order for
527 // any child to be able to use profiling, SIG_IGN must be treated
528 // as available.
529 return sa.sa_handler == SIG_IGN || sa.sa_handler == SIG_DFL;
530}
531
532void ProfileHandler::SignalHandler(int sig, siginfo_t* sinfo, void* ucontext) {
533 int saved_errno = errno;
534 // At this moment, instance_ must be initialized because the handler is
535 // enabled in RegisterThread or RegisterCallback only after
536 // ProfileHandler::Instance runs.
Brian Silverman20350ac2021-11-17 18:19:55 -0800537 ProfileHandler* instance = instance_;
Austin Schuh745610d2015-09-06 18:19:50 -0700538 RAW_CHECK(instance != NULL, "ProfileHandler is not initialized");
539 {
540 SpinLockHolder sl(&instance->signal_lock_);
541 ++instance->interrupts_;
542 for (CallbackIterator it = instance->callbacks_.begin();
543 it != instance->callbacks_.end();
544 ++it) {
545 (*it)->callback(sig, sinfo, ucontext, (*it)->callback_arg);
546 }
547 }
548 errno = saved_errno;
549}
550
551// This module initializer registers the main thread, so it must be
552// executed in the context of the main thread.
553REGISTER_MODULE_INITIALIZER(profile_main, ProfileHandlerRegisterThread());
554
Brian Silverman20350ac2021-11-17 18:19:55 -0800555void ProfileHandlerRegisterThread() {
Austin Schuh745610d2015-09-06 18:19:50 -0700556 ProfileHandler::Instance()->RegisterThread();
557}
558
Brian Silverman20350ac2021-11-17 18:19:55 -0800559ProfileHandlerToken* ProfileHandlerRegisterCallback(
Austin Schuh745610d2015-09-06 18:19:50 -0700560 ProfileHandlerCallback callback, void* callback_arg) {
561 return ProfileHandler::Instance()->RegisterCallback(callback, callback_arg);
562}
563
Brian Silverman20350ac2021-11-17 18:19:55 -0800564void ProfileHandlerUnregisterCallback(ProfileHandlerToken* token) {
Austin Schuh745610d2015-09-06 18:19:50 -0700565 ProfileHandler::Instance()->UnregisterCallback(token);
566}
567
Brian Silverman20350ac2021-11-17 18:19:55 -0800568void ProfileHandlerReset() {
Austin Schuh745610d2015-09-06 18:19:50 -0700569 return ProfileHandler::Instance()->Reset();
570}
571
Brian Silverman20350ac2021-11-17 18:19:55 -0800572void ProfileHandlerGetState(ProfileHandlerState* state) {
Austin Schuh745610d2015-09-06 18:19:50 -0700573 ProfileHandler::Instance()->GetState(state);
574}
575
576#else // OS_CYGWIN
577
578// ITIMER_PROF doesn't work under cygwin. ITIMER_REAL is available, but doesn't
579// work as well for profiling, and also interferes with alarm(). Because of
580// these issues, unless a specific need is identified, profiler support is
581// disabled under Cygwin.
Brian Silverman20350ac2021-11-17 18:19:55 -0800582void ProfileHandlerRegisterThread() {
Austin Schuh745610d2015-09-06 18:19:50 -0700583}
584
Brian Silverman20350ac2021-11-17 18:19:55 -0800585ProfileHandlerToken* ProfileHandlerRegisterCallback(
Austin Schuh745610d2015-09-06 18:19:50 -0700586 ProfileHandlerCallback callback, void* callback_arg) {
587 return NULL;
588}
589
Brian Silverman20350ac2021-11-17 18:19:55 -0800590void ProfileHandlerUnregisterCallback(ProfileHandlerToken* token) {
Austin Schuh745610d2015-09-06 18:19:50 -0700591}
592
Brian Silverman20350ac2021-11-17 18:19:55 -0800593void ProfileHandlerReset() {
Austin Schuh745610d2015-09-06 18:19:50 -0700594}
595
Brian Silverman20350ac2021-11-17 18:19:55 -0800596void ProfileHandlerGetState(ProfileHandlerState* state) {
Austin Schuh745610d2015-09-06 18:19:50 -0700597}
598
599#endif // OS_CYGWIN