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