1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "Watchdog"
18
19 #include <watchdog/Watchdog.h>
20
21 #include <android-base/logging.h>
22 #include <android-base/threads.h>
23 #include <signal.h>
24 #include <time.h>
25 #include <cstring>
26 #include <utils/Log.h>
27
28 namespace android {
29
Watchdog(::std::chrono::steady_clock::duration timeout)30 Watchdog::Watchdog(::std::chrono::steady_clock::duration timeout) {
31 // Create the timer.
32 struct sigevent sev;
33 sev.sigev_notify = SIGEV_THREAD_ID;
34 sev.sigev_notify_thread_id = base::GetThreadId();
35 sev.sigev_signo = SIGABRT;
36 sev.sigev_value.sival_ptr = &mTimerId;
37 int err = timer_create(CLOCK_MONOTONIC, &sev, &mTimerId);
38 if (err != 0) {
39 PLOG(FATAL) << "Failed to create timer";
40 }
41
42 // Start the timer.
43 struct itimerspec spec;
44 memset(&spec, 0, sizeof(spec));
45 auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(timeout);
46 LOG_ALWAYS_FATAL_IF(timeout.count() <= 0, "Duration must be positive");
47 spec.it_value.tv_sec = ns.count() / 1000000000;
48 spec.it_value.tv_nsec = ns.count() % 1000000000;
49 err = timer_settime(mTimerId, 0, &spec, nullptr);
50 if (err != 0) {
51 PLOG(FATAL) << "Failed to start timer";
52 }
53 }
54
~Watchdog()55 Watchdog::~Watchdog() {
56 // Delete the timer.
57 int err = timer_delete(mTimerId);
58 if (err != 0) {
59 PLOG(FATAL) << "Failed to delete timer";
60 }
61 }
62
63 } // namespace android
64