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