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;
__anon9c4dc5580102() 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;
__anon9c4dc5580202() 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;
__anon9c4dc5580302() 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;
__anon9c4dc5580402() 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 devRet1 = IsDeveloperOpen();
294 bool devRet2 = IsDeveloperOpen();
295 bool betaRet1 = IsBetaVersion();
296 bool betaRet2 = IsBetaVersion();
297 EXPECT_TRUE(devRet1 == devRet2);
298 EXPECT_TRUE(betaRet1 == betaRet2);
299 int64_t ret1 = GetTimeStamp();
300 EXPECT_TRUE(ret1 > 0);
301 std::string stack = "";
302 const char* samplePath = "libthread_sampler.z.so";
303 WatchdogInner::GetInstance().threadSamplerFuncHandler_ = dlopen(samplePath, RTLD_LAZY);
304 EXPECT_TRUE(WatchdogInner::GetInstance().threadSamplerFuncHandler_ != nullptr);
305 WatchdogInner::GetInstance().InitThreadSamplerFuncs();
306 WatchdogInner::GetInstance().CollectStack(stack);
307 printf("stack:\n%s", stack.c_str());
308 WatchdogInner::GetInstance().Deinit();
309 WatchdogInner::GetInstance().ResetThreadSamplerFuncs();
310 }
311
312 /**
313 * @tc.name: WatchdogInner;
314 * @tc.desc: add testcase
315 * @tc.type: FUNC
316 */
317 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_002, TestSize.Level1)
318 {
319 int testValue = 150; // test value
320
321 int32_t ret = WatchdogInner::GetInstance().StartProfileMainThread(testValue);
322 int32_t left = 4;
323 int32_t end = time(nullptr) + left;
324 while (left > 0) {
325 left = end - time(nullptr);
326 }
327 EXPECT_EQ(ret, -1);
328
329 left = 10;
330 end = time(nullptr) + left;
331 while (left > 0) {
332 left = end - time(nullptr);
333 }
334
335 ret = WatchdogInner::GetInstance().StartProfileMainThread(testValue);
336 left = 5;
337 end = time(nullptr) + left;
338 while (left > 0) {
339 left = end - time(nullptr);
340 }
341 sleep(4);
342 EXPECT_EQ(ret, 0);
343 std::string stack = "";
344 WatchdogInner::GetInstance().CollectStack(stack);
345 printf("stack:\n%s", stack.c_str());
346 WatchdogInner::GetInstance().Deinit();
347 WatchdogInner::GetInstance().ResetThreadSamplerFuncs();
348 WatchdogInner::GetInstance().CollectTrace();
349 }
350
351 /**
352 * @tc.name: WatchdogInner;
353 * @tc.desc: add testcase
354 * @tc.type: FUNC
355 */
356 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_003, TestSize.Level1)
357 {
__anon9c4dc5580502(const std::string &name, int waitState) 358 auto timeOutCallback = [](const std::string &name, int waitState) {
359 printf("timeOutCallback name is %s, waitState is %d\n", name.c_str(), waitState);
360 };
361 int result = WatchdogInner::GetInstance().AddThread("AddThread", nullptr, timeOutCallback, 10);
362 EXPECT_TRUE(result <= 0);
363 int32_t pid = getprocpid();
364 WatchdogInner::WriteStringToFile(pid, "0");
365 bool ret = WatchdogInner::GetInstance().CheckEventTimer(GetTimeStamp());
366 printf("CheckEventTimer ret=%s\n", ret ? "true" : "fasle");
367 ret = WatchdogInner::GetInstance().ReportMainThreadEvent();
368 printf("ReportMainThreadEvent ret=%s\n", ret ? "true" : "fasle");
369 int state = 1; // test value
370 WatchdogInner::GetInstance().ChangeState(state, 1);
371 int32_t interval = 150; // test value
372 WatchdogInner::GetInstance().StartTraceProfile(interval);
373 ret = IsFileNameFormat('1');
374 EXPECT_TRUE(!ret);
375 ret = IsFileNameFormat('b');
376 EXPECT_TRUE(!ret);
377 ret = IsFileNameFormat('B');
378 EXPECT_TRUE(!ret);
379 ret = IsFileNameFormat('_');
380 EXPECT_TRUE(!ret);
381 ret = IsFileNameFormat('*');
382 EXPECT_TRUE(ret);
383 std::string path = "";
384 std::string stack = "STACK";
385 ret = WriteStackToFd(getprocpid(), path, stack, "test");
386 EXPECT_TRUE(ret);
387 }
388
389 /**
390 * @tc.name: WatchdogInner Test
391 * @tc.desc: add testcase
392 * @tc.type: FUNC
393 */
394 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_004, TestSize.Level1)
395 {
396 WatchdogInner::GetInstance().buissnessThreadInfo_.insert(getproctid());
397 EXPECT_TRUE(WatchdogInner::GetInstance().buissnessThreadInfo_.size() > 0);
398 printf("ret=%d\n", WatchdogInner::GetInstance().ReportMainThreadEvent());
399 WatchdogInner::GetInstance().timeContent_.reportBegin = GetTimeStamp();
400 WatchdogInner::GetInstance().timeContent_.reportEnd = GetTimeStamp();
401 sleep(2);
402 WatchdogInner::GetInstance().timeContent_.curBegin = GetTimeStamp();
403 WatchdogInner::GetInstance().timeContent_.curEnd = GetTimeStamp();
404 EXPECT_TRUE(WatchdogInner::GetInstance().timeContent_.reportBegin !=
405 WatchdogInner::GetInstance().timeContent_.curBegin);
406 int state = 1; // test value
407 TimePoint currenTime = std::chrono::steady_clock::now();
408 TimePoint lastEndTime = std::chrono::steady_clock::now();
409 WatchdogInner::GetInstance().DayChecker(state, currenTime, lastEndTime, 2);
410 WatchdogInner::GetInstance().DayChecker(state, currenTime, lastEndTime, 0);
411 EXPECT_EQ(state, 0);
412 WatchdogInner::GetInstance().StartTraceProfile(150); // test value
413 FunctionOpen(nullptr, "test");
414 }
415
416 /**
417 * @tc.name: WatchdogInner GetProcessNameFromProcCmdline test;
418 * @tc.desc: add testcase
419 * @tc.type: FUNC
420 */
421 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_GetProcNameFromProcCmdline_001, TestSize.Level1)
422 {
423 std::string procName1 = GetProcessNameFromProcCmdline(getpid());
424 std::string procName2 = GetProcessNameFromProcCmdline(25221); // test value
425 EXPECT_TRUE(procName1 != procName2);
426 std::string procName3 = GetProcessNameFromProcCmdline(getpid());
427 EXPECT_TRUE(procName1 == procName3);
428 }
429
430 /**
431 * @tc.name: WatchdogInner InitMainLooperWatcher Test
432 * @tc.desc: add testcase
433 * @tc.type: FUNC
434 */
435 HWTEST_F(WatchdogInnerTest, WatchdogInnerTest_InitMainLooperWatcher_001, TestSize.Level1)
436 {
437 WatchdogInner::GetInstance().InitMainLooperWatcher(nullptr, nullptr);
438 WatchdogInnerBeginFunc beginTest = InitBeginFuncTest;
439 WatchdogInnerEndFunc endTest = InitEndFuncTest;
440 WatchdogInner::GetInstance().stackContent_.stackState == 0;
441 WatchdogInner::GetInstance().InitMainLooperWatcher(&beginTest, &endTest);
442 int count = 0;
443 sleep(10); // test value
444 while (count < 2) {
445 beginTest("Test");
446 usleep(350 * 1000); // test value
447 endTest("Test");
448 count++;
449 }
450 sleep(5);
451 WatchdogInner::GetInstance().traceContent_.traceState == 0;
452 WatchdogInner::GetInstance().InitMainLooperWatcher(&beginTest, &endTest);
453 beginTest("Test");
454 sleep(2); // test value
455 endTest("Test");
456 ASSERT_EQ(WatchdogInner::GetInstance().stackContent_.stackState, 1);
457 WatchdogInner::GetInstance().traceContent_.traceState == 1;
458 WatchdogInner::GetInstance().stackContent_.stackState == 0;
459 beginTest("Test");
460 usleep(250 * 1000); // test value
461 endTest("Test");
462 WatchdogInner::GetInstance().traceCollector_ == nullptr;
463 WatchdogInner::GetInstance().StartTraceProfile(150);
464 }
465 } // namespace HiviewDFX
466 } // namespace OHOS
467