1 /*
2 * Copyright (c) 2023 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 <gtest/gtest.h>
17 #include <string>
18 #include <thread>
19 #include <fstream>
20 #include <fcntl.h>
21 #include <sys/prctl.h>
22 #include <unistd.h>
23 #include <dlfcn.h>
24 #include <chrono>
25 #include "watchdog_inner_test.h"
26
27 #define private public
28 #define protected public
29 #include "watchdog_inner.h"
30 #undef private
31 #undef protected
32
33 #include "xcollie_utils.h"
34 #include "directory_ex.h"
35 #include "file_ex.h"
36 #include "event_handler.h"
37 #include "ffrt_inner.h"
38
39 using namespace testing::ext;
40 using namespace OHOS::AppExecFwk;
41 namespace OHOS {
42 namespace HiviewDFX {
SetUpTestCase(void)43 void WatchdogInnerTest::SetUpTestCase(void)
44 {
45 }
46
TearDownTestCase(void)47 void WatchdogInnerTest::TearDownTestCase(void)
48 {
49 }
50
SetUp(void)51 void WatchdogInnerTest::SetUp(void)
52 {
53 }
54
TearDown(void)55 void WatchdogInnerTest::TearDown(void)
56 {
57 }
58
InitSeLinuxEnabled()59 void InitSeLinuxEnabled()
60 {
61 bool isSelinuxEnabled = false;
62 constexpr uint32_t BUF_SIZE_64 = 64;
63 char buffer[BUF_SIZE_64] = {'\0'};
64 FILE* fp = popen("getenforce", "r");
65 if (fp != nullptr) {
66 fgets(buffer, sizeof(buffer), fp);
67 std::string str = buffer;
68 printf("buffer is %s\n", str.c_str());
69 if (str.find("Enforcing") != str.npos) {
70 printf("Enforcing %s\n", str.c_str());
71 isSelinuxEnabled = true;
72 } else {
73 printf("This isn't Enforcing %s\n", str.c_str());
74 }
75 pclose(fp);
76 } else {
77 printf("fp == nullptr\n");
78 }
79 system("setenforce 0");
80
81 constexpr mode_t defaultLogDirMode = 0770;
82 std::string path = "/data/test/log";
83 if (!OHOS::FileExists(path)) {
84 OHOS::ForceCreateDirectory(path);
85 OHOS::ChangeModeDirectory(path, defaultLogDirMode);
86 }
87 }
88
InitBeginFuncTest(const char * name)89 static void InitBeginFuncTest(const char* name)
90 {
91 std::string nameStr(name);
92 }
93
InitEndFuncTest(const char * name)94 static void InitEndFuncTest(const char* name)
95 {
96 std::string nameStr(name);
97 }
98
99 /**
100 * @tc.name: WatchdogInner thread run a oneshot task
101 * @tc.desc: Verify whether the task has been executed failed
102 * @tc.type: FUNC
103 */
104 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_RunOneShotTask_001, TestSize.Level1)
105 {
106 int taskResult = 0;
__anon89ebcb200102() 107 auto taskFunc = [&taskResult]() { taskResult = 1; };
108 WatchdogInner::GetInstance().RunOneShotTask("", taskFunc, 0);
109 ASSERT_EQ(taskResult, 0);
110 }
111
112 /**
113 * @tc.name: WatchdogInner TriggerTimerCountTask Test
114 * @tc.desc: add teatcase
115 * @tc.type: FUNC
116 */
117 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_TriggerTimerCountTask_001, TestSize.Level1)
118 {
119 std::string name = "WatchdogInnerTest_RunPeriodicalTask_001";
120 WatchdogInner::GetInstance().TriggerTimerCountTask(name, true, "test");
121 ASSERT_EQ(WatchdogInner::GetInstance().checkerQueue_.size(), 0);
122 }
123
124 /**
125 * @tc.name: WatchdogInner thread run a periodical task
126 * @tc.desc: Verify whether the task has been executed failed
127 * @tc.type: FUNC
128 */
129 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_RunPeriodicalTask_001, TestSize.Level1)
130 {
131 int taskResult = 0;
__anon89ebcb200202() 132 auto taskFunc = [&taskResult]() { taskResult = 1; };
133 std::string name = "RunPeriodicalTask_001";
134 WatchdogInner::GetInstance().RunPeriodicalTask(name, taskFunc, 2000, 0);
135 ASSERT_TRUE(WatchdogInner::GetInstance().checkerQueue_.size() > 0);
136 WatchdogInner::GetInstance().TriggerTimerCountTask(name, false, "test");
137 WatchdogInner::GetInstance().TriggerTimerCountTask(name, true, "test");
138 ASSERT_EQ(taskResult, 0);
139 size_t beforeSize = WatchdogInner::GetInstance().taskNameSet_.size();
140 WatchdogInner::GetInstance().RemoveInnerTask(name);
141 size_t afterSize = WatchdogInner::GetInstance().taskNameSet_.size();
142 ASSERT_EQ(beforeSize, (afterSize + 1));
143 WatchdogInner::GetInstance().RunPeriodicalTask("", taskFunc, 2000, 0);
144 WatchdogInner::GetInstance().SetTimerCountTask("", 1, 1);
145 WatchdogInner::GetInstance().RemoveInnerTask("");
146 }
147
148 /**
149 * @tc.name: WatchdogInner fetch next task;
150 * @tc.desc: Verify whether the task acquisition failed
151 * @tc.type: FUNC
152 */
153 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_FetchNextTask_001, TestSize.Level1)
154 {
155 uint64_t now = GetCurrentTickMillseconds();
156 int taskResult = 0;
__anon89ebcb200302() 157 auto taskFunc = [&taskResult]() { taskResult = 1; };
158 const std::string name = "task1";
159 uint64_t delay = 0;
160 uint64_t interval = 0;
161 bool isOneshot = true;
162 WatchdogTask task(name, taskFunc, delay, interval, isOneshot);
163 int id = WatchdogInner::GetInstance().InsertWatchdogTaskLocked(name, WatchdogTask(name, taskFunc,
164 delay, interval, isOneshot));
165 ASSERT_GT(id, 0);
166 WatchdogInner::GetInstance().isNeedStop_.store(true);
167 ASSERT_EQ(WatchdogInner::GetInstance().FetchNextTask(now, task), 60000);
168 WatchdogInner::GetInstance().isNeedStop_.store(false);
169 WatchdogTask task1;
170 ASSERT_EQ(WatchdogInner::GetInstance().FetchNextTask(now, task1), 60000);
171 }
172
173 /**
174 * @tc.name: WatchdogInner fetch next task;
175 * @tc.desc: Verify whether the task acquisition successfully
176 * @tc.type: FUNC
177 */
178 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_FetchNextTask_002, TestSize.Level1)
179 {
180 uint64_t now = GetCurrentTickMillseconds() + 6500;
181 int taskResult = 0;
__anon89ebcb200402() 182 auto taskFunc = [&taskResult]() { taskResult = 1; };
183 const std::string name = "FetchNextTask_002";
184 uint64_t delay = 0;
185 uint64_t interval = 0;
186 bool isOneshot = true;
187 WatchdogTask task(name, taskFunc, delay, interval, isOneshot);
188 int id = WatchdogInner::GetInstance().InsertWatchdogTaskLocked(name, WatchdogTask(name, taskFunc,
189 delay, interval, isOneshot));
190 ASSERT_GT(id, 0);
191 ASSERT_EQ(WatchdogInner::GetInstance().FetchNextTask(now, task), 0);
192 }
193
194 /**
195 * @tc.name: WatchdogInner is exceedMaxTaskLocked;
196 * @tc.desc: Verify whether checkerQueue_ is over MAX_WATCH_NUM;
197 * @tc.type: FUNC
198 */
199 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_IsExceedMaxTaskLocked_001, TestSize.Level1)
200 {
201 bool ret = WatchdogInner::GetInstance().IsExceedMaxTaskLocked();
202 ASSERT_EQ(ret, false);
203 }
204
205 /**
206 * @tc.name: WatchdogInner FfrtCallback Test;
207 * @tc.desc: add teatcase
208 * @tc.type: FUNC
209 */
210 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_FfrtCallback_001, TestSize.Level1)
211 {
212 uint64_t taskId = 1;
213 const char *taskInfo = "task";
214 uint32_t delayedTaskCount = 0;
215 ASSERT_TRUE(WatchdogInner::GetInstance().taskIdCnt.empty());
216 WatchdogInner::GetInstance().FfrtCallback(taskId, taskInfo, delayedTaskCount);
217 }
218
219 /**
220 * @tc.name: WatchdogInner SendMsgToHungtask Test;
221 * @tc.desc: add teatcase
222 * @tc.type: FUNC
223 */
224 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_SendMsgToHungtask_001, TestSize.Level1)
225 {
226 bool ret =WatchdogInner::GetInstance().SendMsgToHungtask(
227 "WatchdogInnerTest_SendMsgToHungtask_001");
228 ASSERT_FALSE(ret);
229 }
230
231 /**
232 * @tc.name: WatchdogInner
233 * @tc.desc: add testcase
234 * @tc.type: FUNC
235 */
236 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_KillProcessTest, TestSize.Level1)
237 {
238 int32_t pid = 12000; // test value
239 bool ret = KillProcessByPid(pid);
240 EXPECT_EQ(ret, false);
241 ret = IsProcessDebug(pid);
242 printf("IsProcessDebug ret=%s", ret ? "true" : "false");
243 InitSeLinuxEnabled();
244 std::string path = "/data/test/log/test1.txt";
245 std::ofstream ofs(path, std::ios::trunc);
246 if (!ofs.is_open()) {
247 printf("open path failed!, path=%s\n", path.c_str());
248 FAIL();
249 }
250 ofs << "aync 1:1 to 2:2 code 9 wait:4 s test" << std::endl;
251 ofs << "12000:12000 to 12001:12001 code 9 wait:1 s test" << std::endl;
252 ofs << "22000:22000 to 12001:12001 code 9 wait:1 s test" << std::endl;
253 ofs << "12000:12000 to 12001:12001 code 9 wait:4 s test" << std::endl;
254 ofs.close();
255
256 std::ifstream fin(path);
257 if (!fin.is_open()) {
258 printf("open path failed!, path=%s\n", path.c_str());
259 FAIL();
260 }
261 int result = ParsePeerBinderPid(fin, pid);
262 fin.close();
263 EXPECT_TRUE(result > 0);
264
265 path = "/data/test/log/test2.txt";
266 ofs.open(path.c_str(), std::ios::trunc);
267 if (!ofs.is_open()) {
268 printf("open path failed!, path=%s\n", path.c_str());
269 FAIL();
270 }
271 ofs << "context" << std::endl;
272 ofs.close();
273 fin.open(path.c_str());
274 if (!fin.is_open()) {
275 printf("open path failed!, path=%s\n", path.c_str());
276 FAIL();
277 }
278 result = ParsePeerBinderPid(fin, pid);
279 fin.close();
280 EXPECT_TRUE(result < 0);
281 }
282
283 /**
284 * @tc.name: WatchdogInner;
285 * @tc.desc: add testcase
286 * @tc.type: FUNC
287 */
288 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_001, TestSize.Level1)
289 {
290 std::string result = GetFormatDate();
291 printf("GetFormatDate:%s\n", result.c_str());
292 EXPECT_TRUE(!result.empty());
293 bool ret = IsEnableVersion("test", "test");
294 printf("ret:%s\n", ret ? "true" : "false");
295 int64_t ret1 = GetTimeStamp();
296 EXPECT_TRUE(ret1 > 0);
297 std::string stack = "";
298 const char* samplePath = "libthread_sampler.z.so";
299 WatchdogInner::GetInstance().funcHandler_ = dlopen(samplePath, RTLD_LAZY);
300 EXPECT_TRUE(WatchdogInner::GetInstance().funcHandler_ != nullptr);
301 WatchdogInner::GetInstance().CollectStack(stack);
302 printf("stack:\n%s", stack.c_str());
303 WatchdogInner::GetInstance().Deinit();
304 }
305
306 /**
307 * @tc.name: WatchdogInner;
308 * @tc.desc: add testcase
309 * @tc.type: FUNC
310 */
311 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_002, TestSize.Level1)
312 {
313 int testValue = 150; // test value
314
315 int32_t ret = WatchdogInner::GetInstance().StartProfileMainThread(testValue);
316 int32_t left = 4;
317 int32_t end = time(nullptr) + left;
318 while (left > 0) {
319 left = end - time(nullptr);
320 }
321 EXPECT_EQ(ret, -1);
322
323 left = 10;
324 end = time(nullptr) + left;
325 while (left > 0) {
326 left = end - time(nullptr);
327 }
328
329 ret = WatchdogInner::GetInstance().StartProfileMainThread(testValue);
330 left = 5;
331 end = time(nullptr) + left;
332 while (left > 0) {
333 left = end - time(nullptr);
334 }
335 sleep(4);
336 EXPECT_EQ(ret, 0);
337 std::string stack = "";
338 WatchdogInner::GetInstance().CollectStack(stack);
339 printf("stack:\n%s", stack.c_str());
340 WatchdogInner::GetInstance().Deinit();
341 WatchdogInner::GetInstance().CollectTrace();
342 }
343
344 /**
345 * @tc.name: WatchdogInner;
346 * @tc.desc: add testcase
347 * @tc.type: FUNC
348 */
349 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_003, TestSize.Level1)
350 {
__anon89ebcb200502(const std::string &name, int waitState) 351 auto timeOutCallback = [](const std::string &name, int waitState) {
352 printf("timeOutCallback name is %s, waitState is %d\n", name.c_str(), waitState);
353 };
354 int result = WatchdogInner::GetInstance().AddThread("AddThread", nullptr, timeOutCallback, 10);
355 EXPECT_TRUE(result <= 0);
356 int32_t pid = getprocpid();
357 WatchdogInner::WriteStringToFile(pid, "0");
358 bool ret = WatchdogInner::GetInstance().CheckEventTimer(GetTimeStamp());
359 printf("CheckEventTimer ret=%s\n", ret ? "true" : "fasle");
360 ret = WatchdogInner::GetInstance().ReportMainThreadEvent();
361 printf("ReportMainThreadEvent ret=%s\n", ret ? "true" : "fasle");
362 int state = 1; // test value
363 WatchdogInner::GetInstance().ChangeState(state, 1);
364 int32_t interval = 150; // test value
365 WatchdogInner::GetInstance().StartTraceProfile(interval);
366 ret = IsFileNameFormat('1');
367 EXPECT_TRUE(!ret);
368 ret = IsFileNameFormat('b');
369 EXPECT_TRUE(!ret);
370 ret = IsFileNameFormat('B');
371 EXPECT_TRUE(!ret);
372 ret = IsFileNameFormat('_');
373 EXPECT_TRUE(!ret);
374 ret = IsFileNameFormat('*');
375 EXPECT_TRUE(ret);
376 std::string path = "";
377 std::string stack = "STACK";
378 ret = WriteStackToFd(getprocpid(), path, stack, "test");
379 EXPECT_TRUE(ret);
380 }
381
382 /**
383 * @tc.name: WatchdogInner Test
384 * @tc.desc: add testcase
385 * @tc.type: FUNC
386 */
387 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_004, TestSize.Level1)
388 {
389 WatchdogInner::GetInstance().buissnessThreadInfo_.insert(getproctid());
390 EXPECT_TRUE(WatchdogInner::GetInstance().buissnessThreadInfo_.size() > 0);
391 printf("ret=%d\n", WatchdogInner::GetInstance().ReportMainThreadEvent());
392 WatchdogInner::GetInstance().timeContent_.reportBegin = GetTimeStamp();
393 WatchdogInner::GetInstance().timeContent_.reportEnd = GetTimeStamp();
394 sleep(2);
395 WatchdogInner::GetInstance().timeContent_.curBegin = GetTimeStamp();
396 WatchdogInner::GetInstance().timeContent_.curEnd = GetTimeStamp();
397 EXPECT_TRUE(WatchdogInner::GetInstance().timeContent_.reportBegin !=
398 WatchdogInner::GetInstance().timeContent_.curBegin);
399 int state = 1; // test value
400 TimePoint currenTime = std::chrono::steady_clock::now();
401 TimePoint lastEndTime = std::chrono::steady_clock::now();
402 WatchdogInner::GetInstance().DayChecker(state, currenTime, lastEndTime, 2);
403 WatchdogInner::GetInstance().DayChecker(state, currenTime, lastEndTime, 0);
404 EXPECT_EQ(state, 0);
405 WatchdogInner::GetInstance().StartTraceProfile(150); // test value
406 FunctionOpen(nullptr, "test");
407 }
408
409 /**
410 * @tc.name: WatchdogInner InitMainLooperWatcher Test
411 * @tc.desc: add testcase
412 * @tc.type: FUNC
413 */
414 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_InitMainLooperWatcher_001, TestSize.Level1)
415 {
416 WatchdogInner::GetInstance().InitMainLooperWatcher(nullptr, nullptr);
417 WatchdogInnerBeginFunc beginTest = InitBeginFuncTest;
418 WatchdogInnerEndFunc endTest = InitEndFuncTest;
419 WatchdogInner::GetInstance().stackContent_.stackState == 0;
420 WatchdogInner::GetInstance().InitMainLooperWatcher(&beginTest, &endTest);
421 int count = 0;
422 sleep(10); // test value
423 while (count < 2) {
424 beginTest("Test");
425 usleep(350 * 1000); // test value
426 endTest("Test");
427 count++;
428 }
429 sleep(5);
430 WatchdogInner::GetInstance().traceContent_.traceState == 0;
431 WatchdogInner::GetInstance().InitMainLooperWatcher(&beginTest, &endTest);
432 beginTest("Test");
433 sleep(2); // test value
434 endTest("Test");
435 ASSERT_EQ(WatchdogInner::GetInstance().stackContent_.stackState, 1);
436 WatchdogInner::GetInstance().traceContent_.traceState == 1;
437 WatchdogInner::GetInstance().stackContent_.stackState == 0;
438 beginTest("Test");
439 usleep(250 * 1000); // test value
440 endTest("Test");
441 WatchdogInner::GetInstance().traceCollector_ == nullptr;
442 WatchdogInner::GetInstance().StartTraceProfile(150);
443 }
444 } // namespace HiviewDFX
445 } // namespace OHOS
446