1 /* 2 * Copyright (c) 2025 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 16 #include "mock_timer.h" 17 #include "cstdio" 18 #include "unistd.h" 19 #include <cstdlib> 20 #include <cstring> 21 #include <ctime> 22 #include <dlfcn.h> 23 24 static struct tm g_defaultTmLocalTime; 25 static struct tm g_defaultGmtime; 26 bool g_enableMock = false; 27 GetDefaultTmLocalTime()28tm *GetDefaultTmLocalTime() 29 { 30 return &g_defaultTmLocalTime; 31 } 32 GetDefaultGmtime()33tm *GetDefaultGmtime() 34 { 35 return &g_defaultGmtime; 36 } 37 SetEnableMock(bool mock)38void SetEnableMock(bool mock) 39 { 40 g_enableMock = mock; 41 } 42 InitDefaultTime()43void InitDefaultTime() 44 { 45 static struct tm *(*realLocaltime)(const time_t *) = nullptr; 46 if (!realLocaltime) { 47 realLocaltime = reinterpret_cast<struct tm *(*)(const time_t *)>(dlsym(RTLD_NEXT, "localtime")); 48 } 49 time_t rawtime; 50 struct tm *timeinfo; 51 if (time(&rawtime) == static_cast<time_t>(-1)) { 52 perror("time function failed \n"); 53 } 54 timeinfo = realLocaltime(&rawtime); 55 if (timeinfo == nullptr) { 56 perror("localtime function failed"); 57 } 58 g_defaultTmLocalTime = *timeinfo; 59 static struct tm *(*realGmtime)(const time_t *) = nullptr; 60 if (!realGmtime) { 61 realGmtime = reinterpret_cast<struct tm *(*)(const time_t *)>(dlsym(RTLD_NEXT, "gmtime")); 62 } 63 time_t rawtimeGmt; 64 struct tm *timeinfoGmt; 65 if (time(&rawtimeGmt) == static_cast<time_t>(-1)) { 66 perror("time function failed \n"); 67 } 68 timeinfoGmt = realGmtime(&rawtimeGmt); 69 g_defaultGmtime = *timeinfoGmt; 70 } 71 localtime(const time_t * timep)72struct tm *localtime(const time_t *timep) 73 { 74 static struct tm *(*realLocaltime)(const time_t *) = nullptr; 75 if (!realLocaltime) { 76 realLocaltime = reinterpret_cast<struct tm *(*)(const time_t *)>(dlsym(RTLD_NEXT, "localtime")); 77 } 78 if (!g_enableMock) { 79 return realLocaltime(timep); 80 } else { 81 return &g_defaultTmLocalTime; 82 } 83 } 84 gmtime(const time_t * timep)85struct tm *gmtime(const time_t *timep) 86 { 87 static struct tm *(*realGmtime)(const time_t *) = nullptr; 88 if (!realGmtime) { 89 realGmtime = reinterpret_cast<struct tm *(*)(const time_t *)>(dlsym(RTLD_NEXT, "gmtime")); 90 } 91 if (!g_enableMock) { 92 return realGmtime(timep); 93 } else { 94 return &g_defaultGmtime; 95 } 96 } 97 EnableTimeMock()98void EnableTimeMock() 99 { 100 InitDefaultTime(); 101 g_enableMock = true; 102 } 103