profile-handler_unittest.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. // -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
  2. // Copyright 2009 Google Inc. All Rights Reserved.
  3. // Author: Nabeel Mian (nabeelmian@google.com)
  4. // Chris Demetriou (cgd@google.com)
  5. //
  6. // Use of this source code is governed by a BSD-style license that can
  7. // be found in the LICENSE file.
  8. //
  9. //
  10. // This file contains the unit tests for profile-handler.h interface.
  11. #include "config.h"
  12. #include "profile-handler.h"
  13. #include <assert.h>
  14. #include <pthread.h>
  15. #include <sys/time.h>
  16. #include <time.h>
  17. #include "base/logging.h"
  18. #include "base/simple_mutex.h"
  19. // Some helpful macros for the test class
  20. #define TEST_F(cls, fn) void cls :: fn()
  21. // Do we expect the profiler to be enabled?
  22. DEFINE_bool(test_profiler_enabled, true,
  23. "expect profiler to be enabled during tests");
  24. namespace {
  25. // TODO(csilvers): error-checking on the pthreads routines
  26. class Thread {
  27. public:
  28. Thread() : joinable_(false) { }
  29. virtual ~Thread() { }
  30. void SetJoinable(bool value) { joinable_ = value; }
  31. void Start() {
  32. pthread_attr_t attr;
  33. pthread_attr_init(&attr);
  34. pthread_attr_setdetachstate(&attr, joinable_ ? PTHREAD_CREATE_JOINABLE
  35. : PTHREAD_CREATE_DETACHED);
  36. pthread_create(&thread_, &attr, &DoRun, this);
  37. pthread_attr_destroy(&attr);
  38. }
  39. void Join() {
  40. assert(joinable_);
  41. pthread_join(thread_, NULL);
  42. }
  43. virtual void Run() = 0;
  44. private:
  45. static void* DoRun(void* cls) {
  46. ProfileHandlerRegisterThread();
  47. reinterpret_cast<Thread*>(cls)->Run();
  48. return NULL;
  49. }
  50. pthread_t thread_;
  51. bool joinable_;
  52. };
  53. // Sleep interval in nano secs. ITIMER_PROF goes off only afer the specified CPU
  54. // time is consumed. Under heavy load this process may no get scheduled in a
  55. // timely fashion. Therefore, give enough time (20x of ProfileHandle timer
  56. // interval 10ms (100Hz)) for this process to accumulate enought CPU time to get
  57. // a profile tick.
  58. int kSleepInterval = 200000000;
  59. // Sleep interval in nano secs. To ensure that if the timer has expired it is
  60. // reset.
  61. int kTimerResetInterval = 5000000;
  62. static bool linux_per_thread_timers_mode_ = false;
  63. static int timer_type_ = ITIMER_PROF;
  64. // Delays processing by the specified number of nano seconds. 'delay_ns'
  65. // must be less than the number of nano seconds in a second (1000000000).
  66. void Delay(int delay_ns) {
  67. static const int kNumNSecInSecond = 1000000000;
  68. EXPECT_LT(delay_ns, kNumNSecInSecond);
  69. struct timespec delay = { 0, delay_ns };
  70. nanosleep(&delay, 0);
  71. }
  72. // Checks whether the profile timer is enabled for the current thread.
  73. bool IsTimerEnabled() {
  74. itimerval current_timer;
  75. EXPECT_EQ(0, getitimer(timer_type_, &current_timer));
  76. if ((current_timer.it_value.tv_sec == 0) &&
  77. (current_timer.it_value.tv_usec != 0)) {
  78. // May be the timer has expired. Sleep for a bit and check again.
  79. Delay(kTimerResetInterval);
  80. EXPECT_EQ(0, getitimer(timer_type_, &current_timer));
  81. }
  82. return (current_timer.it_value.tv_sec != 0 ||
  83. current_timer.it_value.tv_usec != 0);
  84. }
  85. // Dummy worker thread to accumulate cpu time.
  86. class BusyThread : public Thread {
  87. public:
  88. BusyThread() : stop_work_(false) {
  89. }
  90. // Setter/Getters
  91. bool stop_work() {
  92. MutexLock lock(&mu_);
  93. return stop_work_;
  94. }
  95. void set_stop_work(bool stop_work) {
  96. MutexLock lock(&mu_);
  97. stop_work_ = stop_work;
  98. }
  99. private:
  100. // Protects stop_work_ below.
  101. Mutex mu_;
  102. // Whether to stop work?
  103. bool stop_work_;
  104. // Do work until asked to stop.
  105. void Run() {
  106. while (!stop_work()) {
  107. }
  108. }
  109. };
  110. class NullThread : public Thread {
  111. private:
  112. void Run() {
  113. }
  114. };
  115. // Signal handler which tracks the profile timer ticks.
  116. static void TickCounter(int sig, siginfo_t* sig_info, void *vuc,
  117. void* tick_counter) {
  118. int* counter = static_cast<int*>(tick_counter);
  119. ++(*counter);
  120. }
  121. // This class tests the profile-handler.h interface.
  122. class ProfileHandlerTest {
  123. protected:
  124. // Determines the timer type.
  125. static void SetUpTestCase() {
  126. timer_type_ = (getenv("CPUPROFILE_REALTIME") ? ITIMER_REAL : ITIMER_PROF);
  127. #if HAVE_LINUX_SIGEV_THREAD_ID
  128. linux_per_thread_timers_mode_ = (getenv("CPUPROFILE_PER_THREAD_TIMERS") != NULL);
  129. const char *signal_number = getenv("CPUPROFILE_TIMER_SIGNAL");
  130. if (signal_number) {
  131. //signal_number_ = strtol(signal_number, NULL, 0);
  132. linux_per_thread_timers_mode_ = true;
  133. Delay(kTimerResetInterval);
  134. }
  135. #endif
  136. }
  137. // Sets up the profile timers and SIGPROF/SIGALRM handler in a known state.
  138. // It does the following:
  139. // 1. Unregisters all the callbacks, stops the timer and clears out
  140. // timer_sharing state in the ProfileHandler. This clears out any state
  141. // left behind by the previous test or during module initialization when
  142. // the test program was started.
  143. // 3. Starts a busy worker thread to accumulate CPU usage.
  144. virtual void SetUp() {
  145. // Reset the state of ProfileHandler between each test. This unregisters
  146. // all callbacks and stops the timer.
  147. ProfileHandlerReset();
  148. EXPECT_EQ(0, GetCallbackCount());
  149. VerifyDisabled();
  150. // Start worker to accumulate cpu usage.
  151. StartWorker();
  152. }
  153. virtual void TearDown() {
  154. ProfileHandlerReset();
  155. // Stops the worker thread.
  156. StopWorker();
  157. }
  158. // Starts a busy worker thread to accumulate cpu time. There should be only
  159. // one busy worker running. This is required for the case where there are
  160. // separate timers for each thread.
  161. void StartWorker() {
  162. busy_worker_ = new BusyThread();
  163. busy_worker_->SetJoinable(true);
  164. busy_worker_->Start();
  165. // Wait for worker to start up and register with the ProfileHandler.
  166. // TODO(nabeelmian) This may not work under very heavy load.
  167. Delay(kSleepInterval);
  168. }
  169. // Stops the worker thread.
  170. void StopWorker() {
  171. busy_worker_->set_stop_work(true);
  172. busy_worker_->Join();
  173. delete busy_worker_;
  174. }
  175. // Gets the number of callbacks registered with the ProfileHandler.
  176. uint32 GetCallbackCount() {
  177. ProfileHandlerState state;
  178. ProfileHandlerGetState(&state);
  179. return state.callback_count;
  180. }
  181. // Gets the current ProfileHandler interrupt count.
  182. uint64 GetInterruptCount() {
  183. ProfileHandlerState state;
  184. ProfileHandlerGetState(&state);
  185. return state.interrupts;
  186. }
  187. // Verifies that a callback is correctly registered and receiving
  188. // profile ticks.
  189. void VerifyRegistration(const int& tick_counter) {
  190. // Check the callback count.
  191. EXPECT_GT(GetCallbackCount(), 0);
  192. // Check that the profile timer is enabled.
  193. EXPECT_EQ(FLAGS_test_profiler_enabled, linux_per_thread_timers_mode_ || IsTimerEnabled());
  194. uint64 interrupts_before = GetInterruptCount();
  195. // Sleep for a bit and check that tick counter is making progress.
  196. int old_tick_count = tick_counter;
  197. Delay(kSleepInterval);
  198. int new_tick_count = tick_counter;
  199. uint64 interrupts_after = GetInterruptCount();
  200. if (FLAGS_test_profiler_enabled) {
  201. EXPECT_GT(new_tick_count, old_tick_count);
  202. EXPECT_GT(interrupts_after, interrupts_before);
  203. } else {
  204. EXPECT_EQ(new_tick_count, old_tick_count);
  205. EXPECT_EQ(interrupts_after, interrupts_before);
  206. }
  207. }
  208. // Verifies that a callback is not receiving profile ticks.
  209. void VerifyUnregistration(const int& tick_counter) {
  210. // Sleep for a bit and check that tick counter is not making progress.
  211. int old_tick_count = tick_counter;
  212. Delay(kSleepInterval);
  213. int new_tick_count = tick_counter;
  214. EXPECT_EQ(old_tick_count, new_tick_count);
  215. // If no callbacks, timer should be disabled.
  216. if (GetCallbackCount() == 0) {
  217. EXPECT_FALSE(IsTimerEnabled());
  218. }
  219. }
  220. // Verifies that the timer is disabled. Expects the worker to be running.
  221. void VerifyDisabled() {
  222. // Check that the callback count is 0.
  223. EXPECT_EQ(0, GetCallbackCount());
  224. // Check that the timer is disabled.
  225. EXPECT_FALSE(IsTimerEnabled());
  226. // Verify that the ProfileHandler is not accumulating profile ticks.
  227. uint64 interrupts_before = GetInterruptCount();
  228. Delay(kSleepInterval);
  229. uint64 interrupts_after = GetInterruptCount();
  230. EXPECT_EQ(interrupts_before, interrupts_after);
  231. }
  232. // Registers a callback and waits for kTimerResetInterval for timers to get
  233. // reset.
  234. ProfileHandlerToken* RegisterCallback(void* callback_arg) {
  235. ProfileHandlerToken* token = ProfileHandlerRegisterCallback(
  236. TickCounter, callback_arg);
  237. Delay(kTimerResetInterval);
  238. return token;
  239. }
  240. // Unregisters a callback and waits for kTimerResetInterval for timers to get
  241. // reset.
  242. void UnregisterCallback(ProfileHandlerToken* token) {
  243. ProfileHandlerUnregisterCallback(token);
  244. Delay(kTimerResetInterval);
  245. }
  246. // Busy worker thread to accumulate cpu usage.
  247. BusyThread* busy_worker_;
  248. private:
  249. // The tests to run
  250. void RegisterUnregisterCallback();
  251. void MultipleCallbacks();
  252. void Reset();
  253. void RegisterCallbackBeforeThread();
  254. public:
  255. #define RUN(test) do { \
  256. printf("Running %s\n", #test); \
  257. ProfileHandlerTest pht; \
  258. pht.SetUp(); \
  259. pht.test(); \
  260. pht.TearDown(); \
  261. } while (0)
  262. static int RUN_ALL_TESTS() {
  263. SetUpTestCase();
  264. RUN(RegisterUnregisterCallback);
  265. RUN(MultipleCallbacks);
  266. RUN(Reset);
  267. RUN(RegisterCallbackBeforeThread);
  268. printf("Done\n");
  269. return 0;
  270. }
  271. };
  272. // Verifies ProfileHandlerRegisterCallback and
  273. // ProfileHandlerUnregisterCallback.
  274. TEST_F(ProfileHandlerTest, RegisterUnregisterCallback) {
  275. int tick_count = 0;
  276. ProfileHandlerToken* token = RegisterCallback(&tick_count);
  277. VerifyRegistration(tick_count);
  278. UnregisterCallback(token);
  279. VerifyUnregistration(tick_count);
  280. }
  281. // Verifies that multiple callbacks can be registered.
  282. TEST_F(ProfileHandlerTest, MultipleCallbacks) {
  283. // Register first callback.
  284. int first_tick_count = 0;
  285. ProfileHandlerToken* token1 = RegisterCallback(&first_tick_count);
  286. // Check that callback was registered correctly.
  287. VerifyRegistration(first_tick_count);
  288. EXPECT_EQ(1, GetCallbackCount());
  289. // Register second callback.
  290. int second_tick_count = 0;
  291. ProfileHandlerToken* token2 = RegisterCallback(&second_tick_count);
  292. // Check that callback was registered correctly.
  293. VerifyRegistration(second_tick_count);
  294. EXPECT_EQ(2, GetCallbackCount());
  295. // Unregister first callback.
  296. UnregisterCallback(token1);
  297. VerifyUnregistration(first_tick_count);
  298. EXPECT_EQ(1, GetCallbackCount());
  299. // Verify that second callback is still registered.
  300. VerifyRegistration(second_tick_count);
  301. // Unregister second callback.
  302. UnregisterCallback(token2);
  303. VerifyUnregistration(second_tick_count);
  304. EXPECT_EQ(0, GetCallbackCount());
  305. // Verify that the timers is correctly disabled.
  306. if (!linux_per_thread_timers_mode_) VerifyDisabled();
  307. }
  308. // Verifies ProfileHandlerReset
  309. TEST_F(ProfileHandlerTest, Reset) {
  310. // Verify that the profile timer interrupt is disabled.
  311. if (!linux_per_thread_timers_mode_) VerifyDisabled();
  312. int first_tick_count = 0;
  313. RegisterCallback(&first_tick_count);
  314. VerifyRegistration(first_tick_count);
  315. EXPECT_EQ(1, GetCallbackCount());
  316. // Register second callback.
  317. int second_tick_count = 0;
  318. RegisterCallback(&second_tick_count);
  319. VerifyRegistration(second_tick_count);
  320. EXPECT_EQ(2, GetCallbackCount());
  321. // Reset the profile handler and verify that callback were correctly
  322. // unregistered and the timer is disabled.
  323. ProfileHandlerReset();
  324. VerifyUnregistration(first_tick_count);
  325. VerifyUnregistration(second_tick_count);
  326. if (!linux_per_thread_timers_mode_) VerifyDisabled();
  327. }
  328. // Verifies that ProfileHandler correctly handles a case where a callback was
  329. // registered before the second thread started.
  330. TEST_F(ProfileHandlerTest, RegisterCallbackBeforeThread) {
  331. // Stop the worker.
  332. StopWorker();
  333. // Unregister all existing callbacks and stop the timer.
  334. ProfileHandlerReset();
  335. EXPECT_EQ(0, GetCallbackCount());
  336. VerifyDisabled();
  337. // Start the worker.
  338. StartWorker();
  339. // Register a callback and check that profile ticks are being delivered and
  340. // the timer is enabled.
  341. int tick_count = 0;
  342. RegisterCallback(&tick_count);
  343. EXPECT_EQ(1, GetCallbackCount());
  344. VerifyRegistration(tick_count);
  345. EXPECT_EQ(FLAGS_test_profiler_enabled, linux_per_thread_timers_mode_ || IsTimerEnabled());
  346. }
  347. } // namespace
  348. int main(int argc, char** argv) {
  349. return ProfileHandlerTest::RUN_ALL_TESTS();
  350. }