profile-handler.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. // -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
  2. // Copyright (c) 2009, Google Inc.
  3. // All rights reserved.
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * 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.
  18. //
  19. // 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. // Author: Sanjay Ghemawat
  32. // Nabeel Mian
  33. //
  34. // Implements management of profile timers and the corresponding signal handler.
  35. #include "config.h"
  36. #include "profile-handler.h"
  37. #if !(defined(__CYGWIN__) || defined(__CYGWIN32__))
  38. #include <stdio.h>
  39. #include <errno.h>
  40. #include <sys/time.h>
  41. #include <list>
  42. #include <string>
  43. #if HAVE_LINUX_SIGEV_THREAD_ID
  44. // for timer_{create,settime} and associated typedefs & constants
  45. #include <time.h>
  46. // for sys_gettid
  47. #include "base/linux_syscall_support.h"
  48. // for perftools_pthread_key_create
  49. #include "maybe_threads.h"
  50. #endif
  51. #include "base/dynamic_annotations.h"
  52. #include "base/googleinit.h"
  53. #include "base/logging.h"
  54. #include "base/spinlock.h"
  55. #include "maybe_threads.h"
  56. using std::list;
  57. using std::string;
  58. // This structure is used by ProfileHandlerRegisterCallback and
  59. // ProfileHandlerUnregisterCallback as a handle to a registered callback.
  60. struct ProfileHandlerToken {
  61. // Sets the callback and associated arg.
  62. ProfileHandlerToken(ProfileHandlerCallback cb, void* cb_arg)
  63. : callback(cb),
  64. callback_arg(cb_arg) {
  65. }
  66. // Callback function to be invoked on receiving a profile timer interrupt.
  67. ProfileHandlerCallback callback;
  68. // Argument for the callback function.
  69. void* callback_arg;
  70. };
  71. // Blocks a signal from being delivered to the current thread while the object
  72. // is alive. Unblocks it upon destruction.
  73. class ScopedSignalBlocker {
  74. public:
  75. ScopedSignalBlocker(int signo) {
  76. sigemptyset(&sig_set_);
  77. sigaddset(&sig_set_, signo);
  78. RAW_CHECK(sigprocmask(SIG_BLOCK, &sig_set_, NULL) == 0,
  79. "sigprocmask (block)");
  80. }
  81. ~ScopedSignalBlocker() {
  82. RAW_CHECK(sigprocmask(SIG_UNBLOCK, &sig_set_, NULL) == 0,
  83. "sigprocmask (unblock)");
  84. }
  85. private:
  86. sigset_t sig_set_;
  87. };
  88. // This class manages profile timers and associated signal handler. This is a
  89. // a singleton.
  90. class ProfileHandler {
  91. public:
  92. // Registers the current thread with the profile handler.
  93. void RegisterThread();
  94. // Registers a callback routine to receive profile timer ticks. The returned
  95. // token is to be used when unregistering this callback and must not be
  96. // deleted by the caller.
  97. ProfileHandlerToken* RegisterCallback(ProfileHandlerCallback callback,
  98. void* callback_arg);
  99. // Unregisters a previously registered callback. Expects the token returned
  100. // by the corresponding RegisterCallback routine.
  101. void UnregisterCallback(ProfileHandlerToken* token)
  102. NO_THREAD_SAFETY_ANALYSIS;
  103. // Unregisters all the callbacks and stops the timer(s).
  104. void Reset();
  105. // Gets the current state of profile handler.
  106. void GetState(ProfileHandlerState* state);
  107. // Initializes and returns the ProfileHandler singleton.
  108. static ProfileHandler* Instance();
  109. private:
  110. ProfileHandler();
  111. ~ProfileHandler();
  112. // Largest allowed frequency.
  113. static const int32 kMaxFrequency = 4000;
  114. // Default frequency.
  115. static const int32 kDefaultFrequency = 100;
  116. // ProfileHandler singleton.
  117. static ProfileHandler* instance_;
  118. // pthread_once_t for one time initialization of ProfileHandler singleton.
  119. static pthread_once_t once_;
  120. // Initializes the ProfileHandler singleton via GoogleOnceInit.
  121. static void Init();
  122. // Timer state as configured previously.
  123. bool timer_running_;
  124. // The number of profiling signal interrupts received.
  125. int64 interrupts_ GUARDED_BY(signal_lock_);
  126. // Profiling signal interrupt frequency, read-only after construction.
  127. int32 frequency_;
  128. // ITIMER_PROF (which uses SIGPROF), or ITIMER_REAL (which uses SIGALRM).
  129. // Translated into an equivalent choice of clock if per_thread_timer_enabled_
  130. // is true.
  131. int timer_type_;
  132. // Signal number for timer signal.
  133. int signal_number_;
  134. // Counts the number of callbacks registered.
  135. int32 callback_count_ GUARDED_BY(control_lock_);
  136. // Is profiling allowed at all?
  137. bool allowed_;
  138. // Must be false if HAVE_LINUX_SIGEV_THREAD_ID is not defined.
  139. bool per_thread_timer_enabled_;
  140. #ifdef HAVE_LINUX_SIGEV_THREAD_ID
  141. // this is used to destroy per-thread profiling timers on thread
  142. // termination
  143. pthread_key_t thread_timer_key;
  144. #endif
  145. // This lock serializes the registration of threads and protects the
  146. // callbacks_ list below.
  147. // Locking order:
  148. // In the context of a signal handler, acquire signal_lock_ to walk the
  149. // callback list. Otherwise, acquire control_lock_, disable the signal
  150. // handler and then acquire signal_lock_.
  151. SpinLock control_lock_ ACQUIRED_BEFORE(signal_lock_);
  152. SpinLock signal_lock_;
  153. // Holds the list of registered callbacks. We expect the list to be pretty
  154. // small. Currently, the cpu profiler (base/profiler) and thread module
  155. // (base/thread.h) are the only two components registering callbacks.
  156. // Following are the locking requirements for callbacks_:
  157. // For read-write access outside the SIGPROF handler:
  158. // - Acquire control_lock_
  159. // - Disable SIGPROF handler.
  160. // - Acquire signal_lock_
  161. // For read-only access in the context of SIGPROF handler
  162. // (Read-write access is *not allowed* in the SIGPROF handler)
  163. // - Acquire signal_lock_
  164. // For read-only access outside SIGPROF handler:
  165. // - Acquire control_lock_
  166. typedef list<ProfileHandlerToken*> CallbackList;
  167. typedef CallbackList::iterator CallbackIterator;
  168. CallbackList callbacks_ GUARDED_BY(signal_lock_);
  169. // Starts or stops the interval timer.
  170. // Will ignore any requests to enable or disable when
  171. // per_thread_timer_enabled_ is true.
  172. void UpdateTimer(bool enable) EXCLUSIVE_LOCKS_REQUIRED(signal_lock_);
  173. // Returns true if the handler is not being used by something else.
  174. // This checks the kernel's signal handler table.
  175. bool IsSignalHandlerAvailable();
  176. // Signal handler. Iterates over and calls all the registered callbacks.
  177. static void SignalHandler(int sig, siginfo_t* sinfo, void* ucontext);
  178. DISALLOW_COPY_AND_ASSIGN(ProfileHandler);
  179. };
  180. ProfileHandler* ProfileHandler::instance_ = NULL;
  181. pthread_once_t ProfileHandler::once_ = PTHREAD_ONCE_INIT;
  182. const int32 ProfileHandler::kMaxFrequency;
  183. const int32 ProfileHandler::kDefaultFrequency;
  184. // If we are LD_PRELOAD-ed against a non-pthreads app, then these functions
  185. // won't be defined. We declare them here, for that case (with weak linkage)
  186. // which will cause the non-definition to resolve to NULL. We can then check
  187. // for NULL or not in Instance.
  188. extern "C" {
  189. int pthread_once(pthread_once_t *, void (*)(void)) ATTRIBUTE_WEAK;
  190. int pthread_kill(pthread_t thread_id, int signo) ATTRIBUTE_WEAK;
  191. #if HAVE_LINUX_SIGEV_THREAD_ID
  192. int timer_create(clockid_t clockid, struct sigevent* evp,
  193. timer_t* timerid) ATTRIBUTE_WEAK;
  194. int timer_delete(timer_t timerid) ATTRIBUTE_WEAK;
  195. int timer_settime(timer_t timerid, int flags, const struct itimerspec* value,
  196. struct itimerspec* ovalue) ATTRIBUTE_WEAK;
  197. #endif
  198. }
  199. #if HAVE_LINUX_SIGEV_THREAD_ID
  200. struct timer_id_holder {
  201. timer_t timerid;
  202. timer_id_holder(timer_t _timerid) : timerid(_timerid) {}
  203. };
  204. extern "C" {
  205. static void ThreadTimerDestructor(void *arg) {
  206. if (!arg) {
  207. return;
  208. }
  209. timer_id_holder *holder = static_cast<timer_id_holder *>(arg);
  210. timer_delete(holder->timerid);
  211. delete holder;
  212. }
  213. }
  214. static void CreateThreadTimerKey(pthread_key_t *pkey) {
  215. int rv = perftools_pthread_key_create(pkey, ThreadTimerDestructor);
  216. if (rv) {
  217. RAW_LOG(FATAL, "aborting due to pthread_key_create error: %s", strerror(rv));
  218. }
  219. }
  220. static void StartLinuxThreadTimer(int timer_type, int signal_number,
  221. int32 frequency, pthread_key_t timer_key) {
  222. int rv;
  223. struct sigevent sevp;
  224. timer_t timerid;
  225. struct itimerspec its;
  226. memset(&sevp, 0, sizeof(sevp));
  227. sevp.sigev_notify = SIGEV_THREAD_ID;
  228. sevp._sigev_un._tid = sys_gettid();
  229. sevp.sigev_signo = signal_number;
  230. clockid_t clock = CLOCK_THREAD_CPUTIME_ID;
  231. if (timer_type == ITIMER_REAL) {
  232. clock = CLOCK_MONOTONIC;
  233. }
  234. rv = timer_create(clock, &sevp, &timerid);
  235. if (rv) {
  236. RAW_LOG(FATAL, "aborting due to timer_create error: %s", strerror(errno));
  237. }
  238. timer_id_holder *holder = new timer_id_holder(timerid);
  239. rv = perftools_pthread_setspecific(timer_key, holder);
  240. if (rv) {
  241. RAW_LOG(FATAL, "aborting due to pthread_setspecific error: %s", strerror(rv));
  242. }
  243. its.it_interval.tv_sec = 0;
  244. its.it_interval.tv_nsec = 1000000000 / frequency;
  245. its.it_value = its.it_interval;
  246. rv = timer_settime(timerid, 0, &its, 0);
  247. if (rv) {
  248. RAW_LOG(FATAL, "aborting due to timer_settime error: %s", strerror(errno));
  249. }
  250. }
  251. #endif
  252. void ProfileHandler::Init() {
  253. instance_ = new ProfileHandler();
  254. }
  255. ProfileHandler* ProfileHandler::Instance() {
  256. if (pthread_once) {
  257. pthread_once(&once_, Init);
  258. }
  259. if (instance_ == NULL) {
  260. // This will be true on systems that don't link in pthreads,
  261. // including on FreeBSD where pthread_once has a non-zero address
  262. // (but doesn't do anything) even when pthreads isn't linked in.
  263. Init();
  264. assert(instance_ != NULL);
  265. }
  266. return instance_;
  267. }
  268. ProfileHandler::ProfileHandler()
  269. : timer_running_(false),
  270. interrupts_(0),
  271. callback_count_(0),
  272. allowed_(true),
  273. per_thread_timer_enabled_(false) {
  274. SpinLockHolder cl(&control_lock_);
  275. timer_type_ = (getenv("CPUPROFILE_REALTIME") ? ITIMER_REAL : ITIMER_PROF);
  276. signal_number_ = (timer_type_ == ITIMER_PROF ? SIGPROF : SIGALRM);
  277. // Get frequency of interrupts (if specified)
  278. char junk;
  279. const char* fr = getenv("CPUPROFILE_FREQUENCY");
  280. if (fr != NULL && (sscanf(fr, "%u%c", &frequency_, &junk) == 1) &&
  281. (frequency_ > 0)) {
  282. // Limit to kMaxFrequency
  283. frequency_ = (frequency_ > kMaxFrequency) ? kMaxFrequency : frequency_;
  284. } else {
  285. frequency_ = kDefaultFrequency;
  286. }
  287. if (!allowed_) {
  288. return;
  289. }
  290. #if HAVE_LINUX_SIGEV_THREAD_ID
  291. // Do this early because we might be overriding signal number.
  292. const char *per_thread = getenv("CPUPROFILE_PER_THREAD_TIMERS");
  293. const char *signal_number = getenv("CPUPROFILE_TIMER_SIGNAL");
  294. if (per_thread || signal_number) {
  295. if (timer_create && pthread_once) {
  296. CreateThreadTimerKey(&thread_timer_key);
  297. per_thread_timer_enabled_ = true;
  298. // Override signal number if requested.
  299. if (signal_number) {
  300. signal_number_ = strtol(signal_number, NULL, 0);
  301. }
  302. } else {
  303. RAW_LOG(INFO,
  304. "Ignoring CPUPROFILE_PER_THREAD_TIMERS and\n"
  305. " CPUPROFILE_TIMER_SIGNAL due to lack of timer_create().\n"
  306. " Preload or link to librt.so for this to work");
  307. }
  308. }
  309. #endif
  310. // If something else is using the signal handler,
  311. // assume it has priority over us and stop.
  312. if (!IsSignalHandlerAvailable()) {
  313. RAW_LOG(INFO, "Disabling profiler because signal %d handler is already in use.",
  314. signal_number_);
  315. allowed_ = false;
  316. return;
  317. }
  318. // Install the signal handler.
  319. struct sigaction sa;
  320. sa.sa_sigaction = SignalHandler;
  321. sa.sa_flags = SA_RESTART | SA_SIGINFO;
  322. sigemptyset(&sa.sa_mask);
  323. RAW_CHECK(sigaction(signal_number_, &sa, NULL) == 0, "sigprof (enable)");
  324. }
  325. ProfileHandler::~ProfileHandler() {
  326. Reset();
  327. #ifdef HAVE_LINUX_SIGEV_THREAD_ID
  328. if (per_thread_timer_enabled_) {
  329. perftools_pthread_key_delete(thread_timer_key);
  330. }
  331. #endif
  332. }
  333. void ProfileHandler::RegisterThread() {
  334. SpinLockHolder cl(&control_lock_);
  335. if (!allowed_) {
  336. return;
  337. }
  338. // Record the thread identifier and start the timer if profiling is on.
  339. ScopedSignalBlocker block(signal_number_);
  340. SpinLockHolder sl(&signal_lock_);
  341. #if HAVE_LINUX_SIGEV_THREAD_ID
  342. if (per_thread_timer_enabled_) {
  343. StartLinuxThreadTimer(timer_type_, signal_number_, frequency_,
  344. thread_timer_key);
  345. return;
  346. }
  347. #endif
  348. UpdateTimer(callback_count_ > 0);
  349. }
  350. ProfileHandlerToken* ProfileHandler::RegisterCallback(
  351. ProfileHandlerCallback callback, void* callback_arg) {
  352. ProfileHandlerToken* token = new ProfileHandlerToken(callback, callback_arg);
  353. SpinLockHolder cl(&control_lock_);
  354. {
  355. ScopedSignalBlocker block(signal_number_);
  356. SpinLockHolder sl(&signal_lock_);
  357. callbacks_.push_back(token);
  358. ++callback_count_;
  359. UpdateTimer(true);
  360. }
  361. return token;
  362. }
  363. void ProfileHandler::UnregisterCallback(ProfileHandlerToken* token) {
  364. SpinLockHolder cl(&control_lock_);
  365. for (CallbackIterator it = callbacks_.begin(); it != callbacks_.end();
  366. ++it) {
  367. if ((*it) == token) {
  368. RAW_CHECK(callback_count_ > 0, "Invalid callback count");
  369. {
  370. ScopedSignalBlocker block(signal_number_);
  371. SpinLockHolder sl(&signal_lock_);
  372. delete *it;
  373. callbacks_.erase(it);
  374. --callback_count_;
  375. if (callback_count_ == 0)
  376. UpdateTimer(false);
  377. }
  378. return;
  379. }
  380. }
  381. // Unknown token.
  382. RAW_LOG(FATAL, "Invalid token");
  383. }
  384. void ProfileHandler::Reset() {
  385. SpinLockHolder cl(&control_lock_);
  386. {
  387. ScopedSignalBlocker block(signal_number_);
  388. SpinLockHolder sl(&signal_lock_);
  389. CallbackIterator it = callbacks_.begin();
  390. while (it != callbacks_.end()) {
  391. CallbackIterator tmp = it;
  392. ++it;
  393. delete *tmp;
  394. callbacks_.erase(tmp);
  395. }
  396. callback_count_ = 0;
  397. UpdateTimer(false);
  398. }
  399. }
  400. void ProfileHandler::GetState(ProfileHandlerState* state) {
  401. SpinLockHolder cl(&control_lock_);
  402. {
  403. ScopedSignalBlocker block(signal_number_);
  404. SpinLockHolder sl(&signal_lock_); // Protects interrupts_.
  405. state->interrupts = interrupts_;
  406. }
  407. state->frequency = frequency_;
  408. state->callback_count = callback_count_;
  409. state->allowed = allowed_;
  410. }
  411. void ProfileHandler::UpdateTimer(bool enable) {
  412. if (per_thread_timer_enabled_) {
  413. // Ignore any attempts to disable it because that's not supported, and it's
  414. // always enabled so enabling is always a NOP.
  415. return;
  416. }
  417. if (enable == timer_running_) {
  418. return;
  419. }
  420. timer_running_ = enable;
  421. struct itimerval timer;
  422. static const int kMillion = 1000000;
  423. int interval_usec = enable ? kMillion / frequency_ : 0;
  424. timer.it_interval.tv_sec = interval_usec / kMillion;
  425. timer.it_interval.tv_usec = interval_usec % kMillion;
  426. timer.it_value = timer.it_interval;
  427. setitimer(timer_type_, &timer, 0);
  428. }
  429. bool ProfileHandler::IsSignalHandlerAvailable() {
  430. struct sigaction sa;
  431. RAW_CHECK(sigaction(signal_number_, NULL, &sa) == 0, "is-signal-handler avail");
  432. // We only take over the handler if the current one is unset.
  433. // It must be SIG_IGN or SIG_DFL, not some other function.
  434. // SIG_IGN must be allowed because when profiling is allowed but
  435. // not actively in use, this code keeps the handler set to SIG_IGN.
  436. // That setting will be inherited across fork+exec. In order for
  437. // any child to be able to use profiling, SIG_IGN must be treated
  438. // as available.
  439. return sa.sa_handler == SIG_IGN || sa.sa_handler == SIG_DFL;
  440. }
  441. void ProfileHandler::SignalHandler(int sig, siginfo_t* sinfo, void* ucontext) {
  442. int saved_errno = errno;
  443. // At this moment, instance_ must be initialized because the handler is
  444. // enabled in RegisterThread or RegisterCallback only after
  445. // ProfileHandler::Instance runs.
  446. ProfileHandler* instance = ANNOTATE_UNPROTECTED_READ(instance_);
  447. RAW_CHECK(instance != NULL, "ProfileHandler is not initialized");
  448. {
  449. SpinLockHolder sl(&instance->signal_lock_);
  450. ++instance->interrupts_;
  451. for (CallbackIterator it = instance->callbacks_.begin();
  452. it != instance->callbacks_.end();
  453. ++it) {
  454. (*it)->callback(sig, sinfo, ucontext, (*it)->callback_arg);
  455. }
  456. }
  457. errno = saved_errno;
  458. }
  459. // This module initializer registers the main thread, so it must be
  460. // executed in the context of the main thread.
  461. REGISTER_MODULE_INITIALIZER(profile_main, ProfileHandlerRegisterThread());
  462. void ProfileHandlerRegisterThread() {
  463. ProfileHandler::Instance()->RegisterThread();
  464. }
  465. ProfileHandlerToken* ProfileHandlerRegisterCallback(
  466. ProfileHandlerCallback callback, void* callback_arg) {
  467. return ProfileHandler::Instance()->RegisterCallback(callback, callback_arg);
  468. }
  469. void ProfileHandlerUnregisterCallback(ProfileHandlerToken* token) {
  470. ProfileHandler::Instance()->UnregisterCallback(token);
  471. }
  472. void ProfileHandlerReset() {
  473. return ProfileHandler::Instance()->Reset();
  474. }
  475. void ProfileHandlerGetState(ProfileHandlerState* state) {
  476. ProfileHandler::Instance()->GetState(state);
  477. }
  478. #else // OS_CYGWIN
  479. // ITIMER_PROF doesn't work under cygwin. ITIMER_REAL is available, but doesn't
  480. // work as well for profiling, and also interferes with alarm(). Because of
  481. // these issues, unless a specific need is identified, profiler support is
  482. // disabled under Cygwin.
  483. void ProfileHandlerRegisterThread() {
  484. }
  485. ProfileHandlerToken* ProfileHandlerRegisterCallback(
  486. ProfileHandlerCallback callback, void* callback_arg) {
  487. return NULL;
  488. }
  489. void ProfileHandlerUnregisterCallback(ProfileHandlerToken* token) {
  490. }
  491. void ProfileHandlerReset() {
  492. }
  493. void ProfileHandlerGetState(ProfileHandlerState* state) {
  494. }
  495. #endif // OS_CYGWIN