1 /*
2 * Copyright (C) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "time_system_ability.h"
16
17 #include <chrono>
18 #include <dirent.h>
19 #include <fstream>
20 #include <linux/rtc.h>
21 #include <mutex>
22 #include <sstream>
23 #include <string>
24 #include <sys/ioctl.h>
25 #include <sys/time.h>
26 #include <sys/timerfd.h>
27
28 #include "iservice_registry.h"
29 #include "ntp_update_time.h"
30 #include "ntp_trusted_time.h"
31 #include "pthread.h"
32 #include "system_ability.h"
33 #include "system_ability_definition.h"
34 #include "time_common.h"
35 #include "time_tick_notify.h"
36 #include "time_zone_info.h"
37 #include "timer_notify_callback.h"
38 #include "timer_manager_interface.h"
39 #include "timer_proxy.h"
40 #include "timer_database.h"
41 #include "time_file_utils.h"
42 #include "common_event_manager.h"
43 #include "common_event_support.h"
44 #include "power_subscriber.h"
45 #include "nitz_subscriber.h"
46 #include "init_param.h"
47 #include "parameters.h"
48 #include "os_account.h"
49 #include "os_account_manager.h"
50
51 using namespace std::chrono;
52 using namespace OHOS::EventFwk;
53
54 namespace OHOS {
55 namespace MiscServices {
56 namespace {
57 // Unit of measure conversion , BASE: second
58 static const int MILLI_TO_BASE = 1000LL;
59 static const int MICR_TO_BASE = 1000000LL;
60 static const int NANO_TO_BASE = 1000000000LL;
61 static const std::int32_t INIT_INTERVAL = 10L;
62 static const uint32_t TIMER_TYPE_REALTIME_MASK = 1 << 0;
63 static const uint32_t TIMER_TYPE_REALTIME_WAKEUP_MASK = 1 << 1;
64 static const uint32_t TIMER_TYPE_EXACT_MASK = 1 << 2;
65 static const uint32_t TIMER_TYPE_IDLE_MASK = 1 << 3;
66 static const uint32_t TIMER_TYPE_INEXACT_REMINDER_MASK = 1 << 4;
67 constexpr int32_t MILLI_TO_MICR = MICR_TO_BASE / MILLI_TO_BASE;
68 constexpr int32_t NANO_TO_MILLI = NANO_TO_BASE / MILLI_TO_BASE;
69 constexpr int32_t ONE_MILLI = 1000;
70 constexpr uint64_t TWO_MINUTES_TO_MILLI = 120000;
71 static const std::vector<std::string> ALL_DATA = { "timerId", "type", "flag", "windowLength", "interval", \
72 "uid", "bundleName", "wantAgent", "state", "triggerTime", \
73 "pid"};
74 const std::string BOOTEVENT_PARAMETER = "bootevent.boot.completed";
75 const std::string SUBSCRIBE_REMOVED = "UserRemoved";
76 } // namespace
77
78 REGISTER_SYSTEM_ABILITY_BY_ID(TimeSystemAbility, TIME_SERVICE_ID, true);
79
80 std::mutex TimeSystemAbility::instanceLock_;
81 sptr<TimeSystemAbility> TimeSystemAbility::instance_;
82
83 class UserRemovedSubscriber : public AccountSA::OsAccountSubscriber {
84 public:
UserRemovedSubscriber(const AccountSA::OsAccountSubscribeInfo &subscribeInfo)85 explicit UserRemovedSubscriber(const AccountSA::OsAccountSubscribeInfo &subscribeInfo)
86 : AccountSA::OsAccountSubscriber(subscribeInfo)
87 {}
88
OnAccountsChanged(const int &id)89 void OnAccountsChanged(const int &id)
90 {
91 TimerManager::GetInstance()->OnUserRemoved(id);
92 }
93
OnAccountsSwitch(const int &newId, const int &oldId)94 void OnAccountsSwitch(const int &newId, const int &oldId) {}
95 };
96
TimeSystemAbility(int32_t systemAbilityId, bool runOnCreate)97 TimeSystemAbility::TimeSystemAbility(int32_t systemAbilityId, bool runOnCreate)
98 : SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START),
99 rtcId(GetWallClockRtcId())
100 {
101 TIME_HILOGD(TIME_MODULE_SERVICE, " TimeSystemAbility Start.");
102 }
103
TimeSystemAbility()104 TimeSystemAbility::TimeSystemAbility() : state_(ServiceRunningState::STATE_NOT_START), rtcId(GetWallClockRtcId())
105 {
106 }
107
~TimeSystemAbility()108 TimeSystemAbility::~TimeSystemAbility(){};
109
GetInstance()110 sptr<TimeSystemAbility> TimeSystemAbility::GetInstance()
111 {
112 if (instance_ == nullptr) {
113 std::lock_guard<std::mutex> autoLock(instanceLock_);
114 if (instance_ == nullptr) {
115 instance_ = new TimeSystemAbility;
116 }
117 }
118 return instance_;
119 }
120
InitDumpCmd()121 void TimeSystemAbility::InitDumpCmd()
122 {
123 auto cmdTime = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-time" }),
124 "dump current time info,include localtime,timezone info",
125 [this](int fd, const std::vector<std::string> &input) { DumpAllTimeInfo(fd, input); });
126 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTime);
127
128 auto cmdTimerAll = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-timer", "-a" }),
129 "dump all timer info", [this](int fd, const std::vector<std::string> &input) { DumpTimerInfo(fd, input); });
130 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerAll);
131
132 auto cmdTimerInfo = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-timer", "-i", "[n]" }),
133 "dump the timer info with timer id",
134 [this](int fd, const std::vector<std::string> &input) { DumpTimerInfoById(fd, input); });
135 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerInfo);
136
137 auto cmdTimerTrigger = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-timer", "-s", "[n]" }),
138 "dump current time info,include localtime,timezone info",
139 [this](int fd, const std::vector<std::string> &input) { DumpTimerTriggerById(fd, input); });
140 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerTrigger);
141
142 auto cmdTimerIdle = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-idle", "-a" }),
143 "dump idle state and timer info, include pending delay timers and delayed info.",
144 [this](int fd, const std::vector<std::string> &input) { DumpIdleTimerInfo(fd, input); });
145 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerIdle);
146
147 auto cmdProxyTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-ProxyTimer", "-l" }),
148 "dump proxy timer info.",
149 [this](int fd, const std::vector<std::string> &input) { DumpProxyTimerInfo(fd, input); });
150 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdProxyTimer);
151
152 auto cmdPidTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-PidTimer", "-l" }),
153 "dump pid timer map.",
154 [this](int fd, const std::vector<std::string> &input) { DumpPidTimerMapInfo(fd, input); });
155 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdPidTimer);
156
157 auto cmdUidTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-UidTimer", "-l" }),
158 "dump uid timer map.",
159 [this](int fd, const std::vector<std::string> &input) { DumpUidTimerMapInfo(fd, input); });
160 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdUidTimer);
161
162 auto cmdShowDelayTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-ProxyDelayTime", "-l" }),
163 "dump proxy delay time.",
164 [this](int fd, const std::vector<std::string> &input) { DumpProxyDelayTime(fd, input); });
165 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdShowDelayTimer);
166
167 auto cmdAdjustTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-adjust", "-a" }),
168 "dump adjust time.",
169 [this](int fd, const std::vector<std::string> &input) { DumpAdjustTime(fd, input); });
170 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdAdjustTimer);
171 }
172
OnStart()173 void TimeSystemAbility::OnStart()
174 {
175 TIME_HILOGI(TIME_MODULE_SERVICE, "TimeSystemAbility OnStart.");
176 if (state_ == ServiceRunningState::STATE_RUNNING) {
177 TIME_HILOGE(TIME_MODULE_SERVICE, "TimeSystemAbility is already running.");
178 return;
179 }
180 TimerManager::GetInstance();
181 TimeTickNotify::GetInstance().Init();
182 TimeZoneInfo::GetInstance().Init();
183 NtpUpdateTime::GetInstance().Init();
184 // This parameter is set to true by init only after all services have been started,
185 // and is automatically set to false after shutdown. Otherwise it will not be modified.
186 std::string bootCompleted = system::GetParameter(BOOTEVENT_PARAMETER, "");
187 TIME_HILOGI(TIME_MODULE_SERVICE, "bootCompleted: %{public}s", bootCompleted.c_str());
188 if (bootCompleted != "true") {
189 TimeDatabase::GetInstance().ClearDropOnReboot();
190 }
191 AddSystemAbilityListener(ABILITY_MGR_SERVICE_ID);
192 AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
193 AddSystemAbilityListener(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
194 AddSystemAbilityListener(POWER_MANAGER_SERVICE_ID);
195 AddSystemAbilityListener(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID);
196 AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN);
197 InitDumpCmd();
198 if (Init() != ERR_OK) {
199 auto callback = [this]() {
200 sleep(INIT_INTERVAL);
201 Init();
202 };
203 std::thread thread(callback);
204 thread.detach();
205 TIME_HILOGE(TIME_MODULE_SERVICE, "Init failed. Try again 10s later.");
206 }
207 }
208
OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)209 void TimeSystemAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
210 {
211 TIME_HILOGD(TIME_MODULE_SERVICE, "OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
212 switch (systemAbilityId) {
213 case COMMON_EVENT_SERVICE_ID:
214 RegisterCommonEventSubscriber();
215 RemoveSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
216 break;
217 case DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID:
218 RegisterRSSDeathCallback();
219 break;
220 case POWER_MANAGER_SERVICE_ID:
221 RegisterPowerStateListener();
222 break;
223 case COMM_NET_CONN_MANAGER_SYS_ABILITY_ID:
224 NtpUpdateTime::GetInstance().MonitorNetwork();
225 break;
226 case ABILITY_MGR_SERVICE_ID:
227 RecoverTimer();
228 break;
229 case SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN:
230 RegisterOsAccountSubscriber();
231 break;
232 default:
233 TIME_HILOGE(TIME_MODULE_SERVICE, "OnAddSystemAbility systemAbilityId is not valid, id is %{public}d",
234 systemAbilityId);
235 }
236 }
237
RegisterScreenOnSubscriber()238 void TimeSystemAbility::RegisterScreenOnSubscriber()
239 {
240 MatchingSkills matchingSkills;
241 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_ON);
242 CommonEventSubscribeInfo subscriberInfo(matchingSkills);
243 std::shared_ptr<PowerSubscriber> subscriberPtr = std::make_shared<PowerSubscriber>(subscriberInfo);
244 bool subscribeResult = CommonEventManager::SubscribeCommonEvent(subscriberPtr);
245 if (!subscribeResult) {
246 TIME_HILOGE(TIME_MODULE_SERVICE, "Register COMMON_EVENT_SCREEN_ON failed");
247 } else {
248 TIME_HILOGI(TIME_MODULE_SERVICE, "Register COMMON_EVENT_SCREEN_ON success.");
249 }
250 }
251
RegisterNitzTimeSubscriber()252 void TimeSystemAbility::RegisterNitzTimeSubscriber()
253 {
254 MatchingSkills matchingNITZSkills;
255 matchingNITZSkills.AddEvent(CommonEventSupport::COMMON_EVENT_NITZ_TIME_CHANGED);
256 CommonEventSubscribeInfo subscriberNITZInfo(matchingNITZSkills);
257 std::shared_ptr<NITZSubscriber> subscriberNITZPtr = std::make_shared<NITZSubscriber>(subscriberNITZInfo);
258 bool subscribeNITZResult = CommonEventManager::SubscribeCommonEvent(subscriberNITZPtr);
259 if (!subscribeNITZResult) {
260 TIME_HILOGE(TIME_MODULE_SERVICE, "Register COMMON_EVENT_NITZ_TIME_CHANGED failed");
261 } else {
262 TIME_HILOGI(TIME_MODULE_SERVICE, "Register COMMON_EVENT_NITZ_TIME_CHANGED success.");
263 }
264 }
265
RegisterCommonEventSubscriber()266 void TimeSystemAbility::RegisterCommonEventSubscriber()
267 {
268 TIME_HILOGD(TIME_MODULE_SERVICE, "RegisterCommonEventSubscriber Started");
269 bool subRes = TimeServiceNotify::GetInstance().RepublishEvents();
270 if (!subRes) {
271 TIME_HILOGE(TIME_MODULE_SERVICE, "failed to RegisterCommonEventSubscriber");
272 auto callback = [this]() {
273 sleep(INIT_INTERVAL);
274 TimeServiceNotify::GetInstance().RepublishEvents();
275 };
276 std::thread thread(callback);
277 thread.detach();
278 }
279 RegisterScreenOnSubscriber();
280 RegisterNitzTimeSubscriber();
281 }
282
RegisterOsAccountSubscriber()283 void TimeSystemAbility::RegisterOsAccountSubscriber()
284 {
285 TIME_HILOGD(TIME_MODULE_SERVICE, "RegisterOsAccountSubscriber Started");
286 AccountSA::OsAccountSubscribeInfo subscribeInfo(AccountSA::OS_ACCOUNT_SUBSCRIBE_TYPE::REMOVED, SUBSCRIBE_REMOVED);
287 auto userChangedSubscriber = std::make_shared<UserRemovedSubscriber>(subscribeInfo);
288 int err = AccountSA::OsAccountManager::SubscribeOsAccount(userChangedSubscriber);
289 if (err != ERR_OK) {
290 TIME_HILOGE(TIME_MODULE_SERVICE, "Subscribe user removed event failed, errcode: %{public}d", err);
291 }
292 }
293
Init()294 int32_t TimeSystemAbility::Init()
295 {
296 bool ret = Publish(TimeSystemAbility::GetInstance());
297 if (!ret) {
298 TIME_HILOGE(TIME_MODULE_SERVICE, "Init Failed.");
299 return E_TIME_PUBLISH_FAIL;
300 }
301 TIME_HILOGI(TIME_MODULE_SERVICE, "Init success.");
302 state_ = ServiceRunningState::STATE_RUNNING;
303 return ERR_OK;
304 }
305
OnStop()306 void TimeSystemAbility::OnStop()
307 {
308 TIME_HILOGD(TIME_MODULE_SERVICE, "OnStop Started.");
309 if (state_ != ServiceRunningState::STATE_RUNNING) {
310 TIME_HILOGI(TIME_MODULE_SERVICE, "state is running.");
311 return;
312 }
313 TimeTickNotify::GetInstance().Stop();
314 state_ = ServiceRunningState::STATE_NOT_START;
315 TIME_HILOGI(TIME_MODULE_SERVICE, "OnStop End.");
316 }
317
ParseTimerPara(const std::shared_ptr<ITimerInfo> &timerOptions, TimerPara ¶s)318 void TimeSystemAbility::ParseTimerPara(const std::shared_ptr<ITimerInfo> &timerOptions, TimerPara ¶s)
319 {
320 auto uIntType = static_cast<uint32_t>(timerOptions->type);
321 auto disposable = timerOptions->disposable;
322 bool isRealtime = (uIntType & TIMER_TYPE_REALTIME_MASK) > 0;
323 bool isWakeup = (uIntType & TIMER_TYPE_REALTIME_WAKEUP_MASK) > 0;
324 paras.windowLength = (uIntType & TIMER_TYPE_EXACT_MASK) > 0 ? 0 : -1;
325 paras.flag = (uIntType & TIMER_TYPE_EXACT_MASK) > 0 ? 1 : 0;
326 if (isRealtime && isWakeup) {
327 paras.timerType = ITimerManager::TimerType::ELAPSED_REALTIME_WAKEUP;
328 } else if (isRealtime) {
329 paras.timerType = ITimerManager::TimerType::ELAPSED_REALTIME;
330 } else if (isWakeup) {
331 paras.timerType = ITimerManager::TimerType::RTC_WAKEUP;
332 } else {
333 paras.timerType = ITimerManager::TimerType::RTC;
334 }
335 if ((uIntType & TIMER_TYPE_IDLE_MASK) > 0) {
336 paras.flag += ITimerManager::TimerFlag::IDLE_UNTIL;
337 }
338 if ((uIntType & TIMER_TYPE_INEXACT_REMINDER_MASK) > 0) {
339 paras.flag += ITimerManager::TimerFlag::INEXACT_REMINDER;
340 }
341 if (disposable) {
342 paras.flag += ITimerManager::TimerFlag::IS_DISPOSABLE;
343 }
344 paras.interval = timerOptions->repeat ? timerOptions->interval : 0;
345 }
346
CreateTimer(const std::shared_ptr<ITimerInfo> &timerOptions, sptr<IRemoteObject> &obj, uint64_t &timerId)347 int32_t TimeSystemAbility::CreateTimer(const std::shared_ptr<ITimerInfo> &timerOptions, sptr<IRemoteObject> &obj,
348 uint64_t &timerId)
349 {
350 if (obj == nullptr) {
351 TIME_HILOGE(TIME_MODULE_SERVICE, "Input nullptr.");
352 return E_TIME_NULLPTR;
353 }
354 sptr<ITimerCallback> timerCallback = iface_cast<ITimerCallback>(obj);
355 if (timerCallback == nullptr) {
356 TIME_HILOGE(TIME_MODULE_SERVICE, "ITimerCallback nullptr.");
357 return E_TIME_NULLPTR;
358 }
359 struct TimerPara paras {};
360 ParseTimerPara(timerOptions, paras);
361 auto timerManager = TimerManager::GetInstance();
362 if (timerManager == nullptr) {
363 return E_TIME_NULLPTR;
364 }
365 auto callbackFunc = [timerCallback, timerOptions, timerManager](uint64_t id) -> int32_t {
366 #ifdef POWER_MANAGER_ENABLE
367 if (timerOptions->type == ITimerManager::TimerType::RTC_WAKEUP ||
368 timerOptions->type == ITimerManager::TimerType::ELAPSED_REALTIME_WAKEUP) {
369 auto notifyCallback = TimerNotifyCallback::GetInstance(timerManager);
370 return timerCallback->NotifyTimer(id, notifyCallback->AsObject());
371 } else {
372 return timerCallback->NotifyTimer(id, nullptr);
373 }
374 #else
375 return timerCallback->NotifyTimer(id, nullptr);
376 #endif
377 };
378 if ((static_cast<uint32_t>(paras.flag) & static_cast<uint32_t>(ITimerManager::TimerFlag::IDLE_UNTIL)) > 0 &&
379 !TimePermission::CheckProxyCallingPermission()) {
380 TIME_HILOGW(TIME_MODULE_SERVICE, "App not support create idle timer.");
381 paras.flag = 0;
382 }
383 auto type = DatabaseType::NOT_STORE;
384 if (timerOptions->wantAgent != nullptr) {
385 type = DatabaseType::STORE;
386 }
387 int uid = IPCSkeleton::GetCallingUid();
388 int pid = IPCSkeleton::GetCallingPid();
389 return timerManager->CreateTimer(paras, callbackFunc, timerOptions->wantAgent,
390 uid, pid, timerId, type);
391 }
392
CreateTimer(TimerPara ¶s, std::function<int32_t (const uint64_t)> callback, uint64_t &timerId)393 int32_t TimeSystemAbility::CreateTimer(TimerPara ¶s, std::function<int32_t (const uint64_t)> callback,
394 uint64_t &timerId)
395 {
396 auto timerManager = TimerManager::GetInstance();
397 if (timerManager == nullptr) {
398 return E_TIME_NULLPTR;
399 }
400 return timerManager->CreateTimer(paras, std::move(callback), nullptr, 0, 0, timerId, NOT_STORE);
401 }
402
StartTimer(uint64_t timerId, uint64_t triggerTime)403 int32_t TimeSystemAbility::StartTimer(uint64_t timerId, uint64_t triggerTime)
404 {
405 auto timerManager = TimerManager::GetInstance();
406 if (timerManager == nullptr) {
407 return E_TIME_NULLPTR;
408 }
409 auto ret = timerManager->StartTimer(timerId, triggerTime);
410 return ret;
411 }
412
StopTimer(uint64_t timerId)413 int32_t TimeSystemAbility::StopTimer(uint64_t timerId)
414 {
415 auto timerManager = TimerManager::GetInstance();
416 if (timerManager == nullptr) {
417 return E_TIME_NULLPTR;
418 }
419 auto ret = timerManager->StopTimer(timerId);
420 return ret;
421 }
422
DestroyTimer(uint64_t timerId, bool isAsync)423 int32_t TimeSystemAbility::DestroyTimer(uint64_t timerId, bool isAsync)
424 {
425 auto timerManager = TimerManager::GetInstance();
426 if (timerManager == nullptr) {
427 return E_TIME_NULLPTR;
428 }
429 auto ret = timerManager->DestroyTimer(timerId);
430 return ret;
431 }
432
IsValidTime(int64_t time)433 bool TimeSystemAbility::IsValidTime(int64_t time)
434 {
435 #if __SIZEOF_POINTER__ == 4
436 if (time / MILLI_TO_BASE > LONG_MAX) {
437 return false;
438 }
439 #endif
440 return true;
441 }
442
SetRealTime(int64_t time)443 bool TimeSystemAbility::SetRealTime(int64_t time)
444 {
445 if (!IsValidTime(time)) {
446 TIME_HILOGE(TIME_MODULE_SERVICE, "time is invalid: %{public}s", std::to_string(time).c_str());
447 return false;
448 }
449 sptr<TimeSystemAbility> instance = TimeSystemAbility::GetInstance();
450 int64_t beforeTime = 0;
451 instance->GetWallTimeMs(beforeTime);
452 int64_t bootTime = 0;
453 instance->GetBootTimeMs(bootTime);
454 TIME_HILOGI(TIME_MODULE_SERVICE,
455 "Before Current Time: %{public}s"
456 " Set time: %{public}s"
457 " Difference: %{public}s"
458 " uid:%{public}d pid:%{public}d ",
459 std::to_string(beforeTime).c_str(), std::to_string(time).c_str(), std::to_string(time - bootTime).c_str(),
460 IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid());
461 if (time < 0) {
462 TIME_HILOGE(TIME_MODULE_SERVICE, "input param error %{public}" PRId64 "", time);
463 return false;
464 }
465 int64_t currentTime = 0;
466 if (GetWallTimeMs(currentTime) != ERR_OK) {
467 TIME_HILOGE(TIME_MODULE_SERVICE, "currentTime get failed");
468 return false;
469 }
470 struct timeval tv {};
471 tv.tv_sec = (time_t)(time / MILLI_TO_BASE);
472 tv.tv_usec = (suseconds_t)((time % MILLI_TO_BASE) * MILLI_TO_MICR);
473 int result = settimeofday(&tv, nullptr);
474 if (result < 0) {
475 TIME_HILOGE(TIME_MODULE_SERVICE, "settimeofday time fail: %{public}d. error: %{public}s", result,
476 strerror(errno));
477 return false;
478 }
479 auto ret = SetRtcTime(tv.tv_sec);
480 if (ret == E_TIME_SET_RTC_FAILED) {
481 TIME_HILOGE(TIME_MODULE_SERVICE, "set rtc fail: %{public}d.", ret);
482 return false;
483 }
484 TIME_HILOGD(TIME_MODULE_SERVICE, "getting currentTime to milliseconds: %{public}" PRId64 "", currentTime);
485 if (currentTime < (time - ONE_MILLI) || currentTime > (time + ONE_MILLI)) {
486 TimeServiceNotify::GetInstance().PublishTimeChangeEvents(currentTime);
487 }
488 TimeTickNotify::GetInstance().PowerCallback();
489 return true;
490 }
491
SetTime(int64_t time, APIVersion apiVersion)492 int32_t TimeSystemAbility::SetTime(int64_t time, APIVersion apiVersion)
493 {
494 if (!SetRealTime(time)) {
495 return E_TIME_DEAL_FAILED;
496 }
497 return ERR_OK;
498 }
499
Dump(int fd, const std::vector<std::u16string> &args)500 int TimeSystemAbility::Dump(int fd, const std::vector<std::u16string> &args)
501 {
502 int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
503 const int maxUid = 10000;
504 if (uid > maxUid) {
505 return E_TIME_DEAL_FAILED;
506 }
507
508 std::vector<std::string> argsStr;
509 for (auto &item : args) {
510 argsStr.emplace_back(Str16ToStr8(item));
511 }
512
513 TimeCmdDispatcher::GetInstance().Dispatch(fd, argsStr);
514 return ERR_OK;
515 }
516
DumpAllTimeInfo(int fd, const std::vector<std::string> &input)517 void TimeSystemAbility::DumpAllTimeInfo(int fd, const std::vector<std::string> &input)
518 {
519 dprintf(fd, "\n - dump all time info :\n");
520 struct timespec ts{};
521 struct tm timestr{};
522 char date_time[64];
523 if (GetTimeByClockId(CLOCK_BOOTTIME, ts)) {
524 auto localTime = localtime_r(&ts.tv_sec, ×tr);
525 if (localTime == nullptr) {
526 return;
527 }
528 strftime(date_time, sizeof(date_time), "%Y-%m-%d %H:%M:%S", localTime);
529 dprintf(fd, " * date time = %s\n", date_time);
530 } else {
531 dprintf(fd, " * dump date time error.\n");
532 }
533 dprintf(fd, " - dump the time Zone:\n");
534 std::string timeZone;
535 int32_t bRet = GetTimeZone(timeZone);
536 if (bRet == ERR_OK) {
537 dprintf(fd, " * time zone = %s\n", timeZone.c_str());
538 } else {
539 dprintf(fd, " * dump time zone error,is %s\n", timeZone.c_str());
540 }
541 }
542
DumpTimerInfo(int fd, const std::vector<std::string> &input)543 void TimeSystemAbility::DumpTimerInfo(int fd, const std::vector<std::string> &input)
544 {
545 dprintf(fd, "\n - dump all timer info :\n");
546 auto timerManager = TimerManager::GetInstance();
547 if (timerManager == nullptr) {
548 return;
549 }
550 timerManager->ShowTimerEntryMap(fd);
551 }
552
DumpTimerInfoById(int fd, const std::vector<std::string> &input)553 void TimeSystemAbility::DumpTimerInfoById(int fd, const std::vector<std::string> &input)
554 {
555 dprintf(fd, "\n - dump the timer info with timer id:\n");
556 int paramNumPos = 2;
557 auto timerManager = TimerManager::GetInstance();
558 if (timerManager == nullptr) {
559 return;
560 }
561 timerManager->ShowTimerEntryById(fd, std::atoi(input.at(paramNumPos).c_str()));
562 }
563
DumpTimerTriggerById(int fd, const std::vector<std::string> &input)564 void TimeSystemAbility::DumpTimerTriggerById(int fd, const std::vector<std::string> &input)
565 {
566 dprintf(fd, "\n - dump timer trigger statics with timer id:\n");
567 int paramNumPos = 2;
568 auto timerManager = TimerManager::GetInstance();
569 if (timerManager == nullptr) {
570 return;
571 }
572 timerManager->ShowTimerTriggerById(fd, std::atoi(input.at(paramNumPos).c_str()));
573 }
574
DumpIdleTimerInfo(int fd, const std::vector<std::string> &input)575 void TimeSystemAbility::DumpIdleTimerInfo(int fd, const std::vector<std::string> &input)
576 {
577 dprintf(fd, "\n - dump idle timer info :\n");
578 auto timerManager = TimerManager::GetInstance();
579 if (timerManager == nullptr) {
580 return;
581 }
582 timerManager->ShowIdleTimerInfo(fd);
583 }
584
DumpProxyTimerInfo(int fd, const std::vector<std::string> &input)585 void TimeSystemAbility::DumpProxyTimerInfo(int fd, const std::vector<std::string> &input)
586 {
587 dprintf(fd, "\n - dump proxy map:\n");
588 int64_t times;
589 GetBootTimeNs(times);
590 TimerProxy::GetInstance().ShowProxyTimerInfo(fd, times);
591 }
592
DumpUidTimerMapInfo(int fd, const std::vector<std::string> &input)593 void TimeSystemAbility::DumpUidTimerMapInfo(int fd, const std::vector<std::string> &input)
594 {
595 dprintf(fd, "\n - dump uid timer map:\n");
596 int64_t times;
597 GetBootTimeNs(times);
598 TimerProxy::GetInstance().ShowUidTimerMapInfo(fd, times);
599 }
600
DumpProxyDelayTime(int fd, const std::vector<std::string> &input)601 void TimeSystemAbility::DumpProxyDelayTime(int fd, const std::vector<std::string> &input)
602 {
603 dprintf(fd, "\n - dump proxy delay time:\n");
604 TimerProxy::GetInstance().ShowProxyDelayTime(fd);
605 }
606
DumpPidTimerMapInfo(int fd, const std::vector<std::string> &input)607 void TimeSystemAbility::DumpPidTimerMapInfo(int fd, const std::vector<std::string> &input)
608 {
609 dprintf(fd, "\n - dump pid timer map:\n");
610 int64_t times;
611 GetBootTimeNs(times);
612 TimerProxy::GetInstance().ShowPidTimerMapInfo(fd, times);
613 }
614
DumpAdjustTime(int fd, const std::vector<std::string> &input)615 void TimeSystemAbility::DumpAdjustTime(int fd, const std::vector<std::string> &input)
616 {
617 dprintf(fd, "\n - dump adjust timer info:\n");
618 TimerProxy::GetInstance().ShowAdjustTimerInfo(fd);
619 }
620
SetRtcTime(time_t sec)621 int TimeSystemAbility::SetRtcTime(time_t sec)
622 {
623 struct rtc_time rtc {};
624 struct tm tm {};
625 struct tm *gmtime_res = nullptr;
626 int fd = -1;
627 int res;
628 if (rtcId < 0) {
629 TIME_HILOGE(TIME_MODULE_SERVICE, "invalid rtc id: %{public}s:", strerror(ENODEV));
630 return E_TIME_SET_RTC_FAILED;
631 }
632 std::stringstream strs;
633 strs << "/dev/rtc" << rtcId;
634 auto rtcDev = strs.str();
635 TIME_HILOGI(TIME_MODULE_SERVICE, "rtc_dev : %{public}s:", rtcDev.data());
636 auto rtcData = rtcDev.data();
637 fd = open(rtcData, O_RDWR);
638 if (fd < 0) {
639 TIME_HILOGE(TIME_MODULE_SERVICE, "open failed %{public}s: %{public}s", rtcDev.data(), strerror(errno));
640 return E_TIME_SET_RTC_FAILED;
641 }
642 gmtime_res = gmtime_r(&sec, &tm);
643 if (gmtime_res) {
644 rtc.tm_sec = tm.tm_sec;
645 rtc.tm_min = tm.tm_min;
646 rtc.tm_hour = tm.tm_hour;
647 rtc.tm_mday = tm.tm_mday;
648 rtc.tm_mon = tm.tm_mon;
649 rtc.tm_year = tm.tm_year;
650 rtc.tm_wday = tm.tm_wday;
651 rtc.tm_yday = tm.tm_yday;
652 rtc.tm_isdst = tm.tm_isdst;
653 res = ioctl(fd, RTC_SET_TIME, &rtc);
654 if (res < 0) {
655 TIME_HILOGE(TIME_MODULE_SERVICE, "ioctl RTC_SET_TIME failed,errno: %{public}s, res: %{public}d",
656 strerror(errno), res);
657 }
658 } else {
659 TIME_HILOGE(TIME_MODULE_SERVICE, "convert rtc time failed: %{public}s", strerror(errno));
660 res = E_TIME_SET_RTC_FAILED;
661 }
662 close(fd);
663 return res;
664 }
665
CheckRtc(const std::string &rtcPath, uint64_t rtcId)666 bool TimeSystemAbility::CheckRtc(const std::string &rtcPath, uint64_t rtcId)
667 {
668 std::stringstream strs;
669 strs << rtcPath << "/rtc" << rtcId << "/hctosys";
670 auto hctosys_path = strs.str();
671
672 std::fstream file(hctosys_path.data(), std::ios_base::in);
673 if (file.is_open()) {
674 return true;
675 } else {
676 TIME_HILOGE(TIME_MODULE_SERVICE, "failed to open %{public}s", hctosys_path.data());
677 return false;
678 }
679 }
680
GetWallClockRtcId()681 int TimeSystemAbility::GetWallClockRtcId()
682 {
683 std::string rtcPath = "/sys/class/rtc";
684
685 std::unique_ptr<DIR, int (*)(DIR *)> dir(opendir(rtcPath.c_str()), closedir);
686 if (!dir.get()) {
687 TIME_HILOGE(TIME_MODULE_SERVICE, "failed to open %{public}s: %{public}s", rtcPath.c_str(), strerror(errno));
688 return -1;
689 }
690
691 struct dirent *dirent;
692 std::string s = "rtc";
693 while (errno = 0, dirent = readdir(dir.get())) {
694 std::string name(dirent->d_name);
695 unsigned long rtcId = 0;
696 auto index = name.find(s);
697 if (index == std::string::npos) {
698 continue;
699 } else {
700 auto rtcIdStr = name.substr(index + s.length());
701 rtcId = std::stoul(rtcIdStr);
702 }
703 if (CheckRtc(rtcPath, rtcId)) {
704 TIME_HILOGD(TIME_MODULE_SERVICE, "found wall clock rtc %{public}ld", rtcId);
705 return rtcId;
706 }
707 }
708
709 if (errno == 0) {
710 TIME_HILOGE(TIME_MODULE_SERVICE, "no wall clock rtc found");
711 } else {
712 TIME_HILOGE(TIME_MODULE_SERVICE, "failed to check rtc: %{public}s", strerror(errno));
713 }
714 return -1;
715 }
716
SetTimeZone(const std::string &timeZoneId, APIVersion apiVersion)717 int32_t TimeSystemAbility::SetTimeZone(const std::string &timeZoneId, APIVersion apiVersion)
718 {
719 if (!TimeZoneInfo::GetInstance().SetTimezone(timeZoneId)) {
720 TIME_HILOGE(TIME_MODULE_SERVICE, "Set timezone failed :%{public}s", timeZoneId.c_str());
721 return E_TIME_DEAL_FAILED;
722 }
723 int64_t currentTime = 0;
724 GetBootTimeMs(currentTime);
725 TimeServiceNotify::GetInstance().PublishTimeZoneChangeEvents(currentTime);
726 return ERR_OK;
727 }
728
GetTimeZone(std::string &timeZoneId)729 int32_t TimeSystemAbility::GetTimeZone(std::string &timeZoneId)
730 {
731 if (!TimeZoneInfo::GetInstance().GetTimezone(timeZoneId)) {
732 TIME_HILOGE(TIME_MODULE_SERVICE, "get timezone failed");
733 return E_TIME_DEAL_FAILED;
734 }
735 TIME_HILOGD(TIME_MODULE_SERVICE, "Current timezone : %{public}s", timeZoneId.c_str());
736 return ERR_OK;
737 }
738
GetWallTimeMs(int64_t &time)739 int32_t TimeSystemAbility::GetWallTimeMs(int64_t &time)
740 {
741 struct timespec tv {};
742 if (GetTimeByClockId(CLOCK_REALTIME, tv)) {
743 time = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
744 return ERR_OK;
745 }
746 return E_TIME_DEAL_FAILED;
747 }
748
GetBootTimeMs(int64_t &time)749 int32_t TimeSystemAbility::GetBootTimeMs(int64_t &time)
750 {
751 struct timespec tv {};
752 if (GetTimeByClockId(CLOCK_BOOTTIME, tv)) {
753 time = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
754 return ERR_OK;
755 }
756 return E_TIME_DEAL_FAILED;
757 }
758
GetBootTimeNs(int64_t &time)759 int32_t TimeSystemAbility::GetBootTimeNs(int64_t &time)
760 {
761 struct timespec tv {};
762 if (GetTimeByClockId(CLOCK_BOOTTIME, tv)) {
763 time = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
764 return ERR_OK;
765 }
766 return E_TIME_DEAL_FAILED;
767 }
768
GetThreadTimeMs(int64_t &time)769 int32_t TimeSystemAbility::GetThreadTimeMs(int64_t &time)
770 {
771 struct timespec tv {};
772 clockid_t cid;
773 int ret = pthread_getcpuclockid(pthread_self(), &cid);
774 if (ret != E_TIME_OK) {
775 return E_TIME_PARAMETERS_INVALID;
776 }
777 if (GetTimeByClockId(cid, tv)) {
778 time = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
779 return ERR_OK;
780 }
781 return E_TIME_DEAL_FAILED;
782 }
783
GetThreadTimeNs(int64_t &time)784 int32_t TimeSystemAbility::GetThreadTimeNs(int64_t &time)
785 {
786 struct timespec tv {};
787 clockid_t cid;
788 int ret = pthread_getcpuclockid(pthread_self(), &cid);
789 if (ret != E_TIME_OK) {
790 return E_TIME_PARAMETERS_INVALID;
791 }
792 if (GetTimeByClockId(cid, tv)) {
793 time = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
794 return ERR_OK;
795 }
796 return E_TIME_DEAL_FAILED;
797 }
798
GetTimeByClockId(clockid_t clockId, struct timespec &tv)799 bool TimeSystemAbility::GetTimeByClockId(clockid_t clockId, struct timespec &tv)
800 {
801 if (clock_gettime(clockId, &tv) < 0) {
802 TIME_HILOGE(TIME_MODULE_SERVICE, "Failed clock_gettime.");
803 return false;
804 }
805 return true;
806 }
807
ProxyTimer(int32_t uid, bool isProxy, bool needRetrigger)808 bool TimeSystemAbility::ProxyTimer(int32_t uid, bool isProxy, bool needRetrigger)
809 {
810 if (!TimePermission::CheckProxyCallingPermission()) {
811 TIME_HILOGE(TIME_MODULE_SERVICE, "ProxyTimer permission check failed");
812 return E_TIME_NO_PERMISSION;
813 }
814 TIME_HILOGD(TIME_MODULE_SERVICE, "ProxyTimer service start uid: %{public}d, isProxy: %{public}d", uid, isProxy);
815 auto timerManager = TimerManager::GetInstance();
816 if (timerManager == nullptr) {
817 return false;
818 }
819 return timerManager->ProxyTimer(uid, isProxy, needRetrigger);
820 }
821
AdjustTimer(bool isAdjust, uint32_t interval)822 int32_t TimeSystemAbility::AdjustTimer(bool isAdjust, uint32_t interval)
823 {
824 auto timerManager = TimerManager::GetInstance();
825 if (timerManager == nullptr) {
826 return E_TIME_NULLPTR;
827 }
828 if (!timerManager->AdjustTimer(isAdjust, interval)) {
829 return E_TIME_NO_TIMER_ADJUST;
830 }
831 return E_TIME_OK;
832 }
833
ProxyTimer(std::set<int> pidList, bool isProxy, bool needRetrigger)834 bool TimeSystemAbility::ProxyTimer(std::set<int> pidList, bool isProxy, bool needRetrigger)
835 {
836 if (!TimePermission::CheckProxyCallingPermission()) {
837 TIME_HILOGE(TIME_MODULE_SERVICE, "ProxyTimer permission check failed");
838 return E_TIME_NO_PERMISSION;
839 }
840 auto timerManager = TimerManager::GetInstance();
841 if (timerManager == nullptr) {
842 return false;
843 }
844 return timerManager->ProxyTimer(pidList, isProxy, needRetrigger);
845 }
846
SetTimerExemption(const std::unordered_set<std::string> &nameArr, bool isExemption)847 int32_t TimeSystemAbility::SetTimerExemption(const std::unordered_set<std::string> &nameArr, bool isExemption)
848 {
849 auto timerManager = TimerManager::GetInstance();
850 if (timerManager == nullptr) {
851 return E_TIME_NULLPTR;
852 }
853 timerManager->SetTimerExemption(nameArr, isExemption);
854 return E_TIME_OK;
855 }
856
ResetAllProxy()857 bool TimeSystemAbility::ResetAllProxy()
858 {
859 if (!TimePermission::CheckProxyCallingPermission()) {
860 TIME_HILOGE(TIME_MODULE_SERVICE, "ResetAllProxy permission check failed");
861 return E_TIME_NO_PERMISSION;
862 }
863 TIME_HILOGD(TIME_MODULE_SERVICE, "ResetAllProxy service");
864 auto timerManager = TimerManager::GetInstance();
865 if (timerManager == nullptr) {
866 return false;
867 }
868 return timerManager->ResetAllProxy();
869 }
870
GetNtpTimeMs(int64_t &time)871 int32_t TimeSystemAbility::GetNtpTimeMs(int64_t &time)
872 {
873 auto ret = NtpUpdateTime::GetInstance().GetNtpTime(time);
874 if (!ret) {
875 TIME_HILOGE(TIME_MODULE_SERVICE, "GetNtpTimeMs failed");
876 return E_TIME_NTP_UPDATE_FAILED;
877 }
878 return E_TIME_OK;
879 }
880
GetRealTimeMs(int64_t &time)881 int32_t TimeSystemAbility::GetRealTimeMs(int64_t &time)
882 {
883 auto ret = NtpUpdateTime::GetInstance().GetRealTime(time);
884 if (!ret) {
885 TIME_HILOGE(TIME_MODULE_SERVICE, "GetRealTimeMs failed");
886 return E_TIME_NTP_NOT_UPDATE;
887 }
888 return E_TIME_OK;
889 }
890
OnRemoteDied(const wptr<IRemoteObject> &object)891 void TimeSystemAbility::RSSSaDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &object)
892 {
893 auto timerManager = TimerManager::GetInstance();
894 if (timerManager == nullptr) {
895 return;
896 }
897 timerManager->HandleRSSDeath();
898 }
899
RegisterRSSDeathCallback()900 void TimeSystemAbility::RegisterRSSDeathCallback()
901 {
902 TIME_HILOGD(TIME_MODULE_SERVICE, "register rss death callback");
903 auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
904 if (systemAbilityManager == nullptr) {
905 TIME_HILOGE(TIME_MODULE_CLIENT, "Getting SystemAbilityManager failed.");
906 return;
907 }
908
909 auto systemAbility = systemAbilityManager->GetSystemAbility(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
910 if (systemAbility == nullptr) {
911 TIME_HILOGE(TIME_MODULE_CLIENT, "Get SystemAbility failed.");
912 return;
913 }
914
915 if (deathRecipient_ == nullptr) {
916 deathRecipient_ = new RSSSaDeathRecipient();
917 }
918
919 systemAbility->AddDeathRecipient(deathRecipient_);
920 }
921
OnSyncShutdown()922 void TimeSystemAbility::TimePowerStateListener::OnSyncShutdown()
923 {
924 // Clears `drop_on_reboot` table.
925 TIME_HILOGI(TIME_MODULE_SERVICE, "OnSyncShutdown");
926 TimeSystemAbility::GetInstance()->SetAutoReboot();
927 TimeDatabase::GetInstance().ClearDropOnReboot();
928 }
929
RegisterPowerStateListener()930 void TimeSystemAbility::RegisterPowerStateListener()
931 {
932 TIME_HILOGI(TIME_MODULE_CLIENT, "RegisterPowerStateListener");
933 auto& powerManagerClient = OHOS::PowerMgr::ShutdownClient::GetInstance();
934 sptr<OHOS::PowerMgr::ISyncShutdownCallback> syncShutdownCallback = new TimePowerStateListener();
935 if (!syncShutdownCallback) {
936 TIME_HILOGE(TIME_MODULE_SERVICE, "Get TimePowerStateListener failed.");
937 return;
938 }
939 powerManagerClient.RegisterShutdownCallback(syncShutdownCallback, PowerMgr::ShutdownPriority::HIGH);
940 TIME_HILOGI(TIME_MODULE_CLIENT, "RegisterPowerStateListener end");
941 }
942
RecoverTimer()943 bool TimeSystemAbility::RecoverTimer()
944 {
945 auto database = TimeDatabase::GetInstance();
946 OHOS::NativeRdb::RdbPredicates holdRdbPredicates(HOLD_ON_REBOOT);
947 auto holdResultSet = database.Query(holdRdbPredicates, ALL_DATA);
948 if (holdResultSet == nullptr || holdResultSet->GoToFirstRow() != OHOS::NativeRdb::E_OK) {
949 TIME_HILOGI(TIME_MODULE_SERVICE, "hold result set is nullptr or go to first row failed");
950 } else {
951 int count;
952 holdResultSet->GetRowCount(count);
953 TIME_HILOGI(TIME_MODULE_SERVICE, "hold result rows count: %{public}d", count);
954 RecoverTimerInner(holdResultSet);
955 }
956 if (holdResultSet != nullptr) {
957 holdResultSet->Close();
958 }
959
960 OHOS::NativeRdb::RdbPredicates dropRdbPredicates(DROP_ON_REBOOT);
961 auto dropResultSet = database.Query(dropRdbPredicates, ALL_DATA);
962 if (dropResultSet == nullptr || dropResultSet->GoToFirstRow() != OHOS::NativeRdb::E_OK) {
963 TIME_HILOGI(TIME_MODULE_SERVICE, "drop result set is nullptr or go to first row failed");
964 } else {
965 int count;
966 dropResultSet->GetRowCount(count);
967 TIME_HILOGI(TIME_MODULE_SERVICE, "drop result rows count: %{public}d", count);
968 RecoverTimerInner(dropResultSet);
969 }
970 if (dropResultSet != nullptr) {
971 dropResultSet->Close();
972 }
973 return true;
974 }
975
RecoverTimerInner(std::shared_ptr<OHOS::NativeRdb::ResultSet> resultSet)976 void TimeSystemAbility::RecoverTimerInner(std::shared_ptr<OHOS::NativeRdb::ResultSet> resultSet)
977 {
978 auto timerManager = TimerManager::GetInstance();
979 if (timerManager == nullptr) {
980 return;
981 }
982 do {
983 auto timerId = static_cast<uint64_t>(GetLong(resultSet, 0));
984 auto timerInfo = std::make_shared<TimerEntry>(TimerEntry {
985 // Line 0 is 'timerId'
986 timerId,
987 // Line 1 is 'type'
988 GetInt(resultSet, 1),
989 // Line 3 is 'windowLength'
990 static_cast<uint64_t>(GetLong(resultSet, 3)),
991 // Line 4 is 'interval'
992 static_cast<uint64_t>(GetLong(resultSet, 4)),
993 // Line 2 is 'flag'
994 GetInt(resultSet, 2),
995 // Callback can't recover.
996 nullptr,
997 // Line 7 is 'wantAgent'
998 OHOS::AbilityRuntime::WantAgent::WantAgentHelper::FromString(GetString(resultSet, 7)),
999 // Line 5 is 'uid'
1000 GetInt(resultSet, 5),
1001 // Line 10 is 'pid'
1002 GetInt(resultSet, 10),
1003 // Line 6 is 'bundleName'
1004 GetString(resultSet, 6)
1005 });
1006 if (timerInfo->wantAgent == nullptr) {
1007 TIME_HILOGE(TIME_MODULE_SERVICE, "wantAgent is nullptr, uid=%{public}d, id=%{public}" PRId64 "",
1008 timerInfo->uid, timerInfo->id);
1009 continue;
1010 }
1011 timerManager->ReCreateTimer(timerId, timerInfo);
1012 // Line 8 is 'state'
1013 auto state = static_cast<uint8_t>(GetInt(resultSet, 8));
1014 if (state == 1) {
1015 // Line 9 is 'triggerTime'
1016 auto triggerTime = static_cast<uint64_t>(GetLong(resultSet, 9));
1017 timerManager->StartTimer(timerId, triggerTime);
1018 }
1019 } while (resultSet->GoToNextRow() == OHOS::NativeRdb::E_OK);
1020 }
1021
SetAutoReboot()1022 void TimeSystemAbility::SetAutoReboot()
1023 {
1024 auto database = TimeDatabase::GetInstance();
1025 OHOS::NativeRdb::RdbPredicates holdRdbPredicates(HOLD_ON_REBOOT);
1026 holdRdbPredicates.EqualTo("state", 1)->OrderByAsc("triggerTime");
1027 auto resultSet = database.Query(holdRdbPredicates, { "bundleName", "triggerTime" });
1028 if (resultSet == nullptr) {
1029 TIME_HILOGI(TIME_MODULE_SERVICE, "no need to set RTC");
1030 return;
1031 }
1032 int64_t currentTime = 0;
1033 TimeSystemAbility::GetInstance()->GetWallTimeMs(currentTime);
1034 auto bundleList = TimeFileUtils::GetBundleList();
1035 do {
1036 auto bundleName = GetString(resultSet, 0);
1037 uint64_t triggerTime = static_cast<uint64_t>(GetLong(resultSet, 1));
1038 if (triggerTime < static_cast<uint64_t>(currentTime)) {
1039 TIME_HILOGI(TIME_MODULE_SERVICE,
1040 "triggerTime: %{public}" PRIu64" currentTime: %{public}" PRId64"", triggerTime, currentTime);
1041 continue;
1042 }
1043 if (bundleName == (bundleList.empty() ? "" : bundleList[0])) {
1044 int tmfd = timerfd_create(CLOCK_POWEROFF_ALARM, TFD_NONBLOCK);
1045 if (tmfd < 0) {
1046 TIME_HILOGE(TIME_MODULE_SERVICE, "timerfd_create error: %{public}s", strerror(errno));
1047 resultSet->Close();
1048 return;
1049 }
1050 if (static_cast<uint64_t>(currentTime) + TWO_MINUTES_TO_MILLI > triggerTime) {
1051 TIME_HILOGI(TIME_MODULE_SERVICE, "interval less than 2min");
1052 triggerTime = static_cast<uint64_t>(currentTime) + TWO_MINUTES_TO_MILLI;
1053 }
1054 struct itimerspec new_value;
1055 std::chrono::nanoseconds nsec(triggerTime * MILLISECOND_TO_NANO);
1056 auto second = std::chrono::duration_cast<std::chrono::seconds>(nsec);
1057 new_value.it_value.tv_sec = second.count();
1058 new_value.it_value.tv_nsec = (nsec - second).count();
1059 TIME_HILOGI(TIME_MODULE_SERVICE, "currentTime:%{public}" PRId64 ", second:%{public}" PRId64 ","
1060 "nanosecond:%{public}" PRId64"", currentTime, static_cast<int64_t>(new_value.it_value.tv_sec),
1061 static_cast<int64_t>(new_value.it_value.tv_nsec));
1062 int ret = timerfd_settime(tmfd, TFD_TIMER_ABSTIME, &new_value, nullptr);
1063 if (ret < 0) {
1064 TIME_HILOGE(TIME_MODULE_SERVICE, "timerfd_settime error: %{public}s", strerror(errno));
1065 close(tmfd);
1066 }
1067 resultSet->Close();
1068 return;
1069 }
1070 } while (resultSet->GoToNextRow() == OHOS::NativeRdb::E_OK);
1071 resultSet->Close();
1072 }
1073 } // namespace MiscServices
1074 } // namespace OHOS