1 /*
2 * Copyright (c) 2021-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 #include <cstddef>
16 #include <cstdint>
17 #include <string>
18 #include <vector>
19
20 #include <fcntl.h>
21 #include <fstream>
22 #include <gtest/gtest.h>
23 #include <regex>
24 #include "sys_event.h"
25 #include <sys/stat.h>
26 #include <sys/syscall.h>
27 #include <sys/types.h>
28 #include <sys/inotify.h>
29 #include <sys/ioctl.h>
30 #include <unistd.h>
31 #include <iostream>
32 #include <cctype>
33 #include <cstring>
34
35 #include "bundle_mgr_client.h"
36 #include "event.h"
37 #include "faultlog_util.h"
38 #include "faultlog_database.h"
39 #include "faultlogger.h"
40 #include "faultevent_listener.h"
41 #include "faultlog_formatter.h"
42 #include "faultlog_info_ohos.h"
43 #include "faultlog_query_result_ohos.h"
44 #include "faultlogger_service_ohos.h"
45 #include "file_util.h"
46 #include "hisysevent_manager.h"
47 #include "hiview_global.h"
48 #include "hiview_logger.h"
49 #include "hiview_platform.h"
50 #include "ipc_skeleton.h"
51 #include "json/json.h"
52 #include "log_analyzer.h"
53 #include "sys_event.h"
54 #include "sys_event_dao.h"
55 #include "faultlog_bundle_util.h"
56 #include "faultlog_sanitizer.h"
57 #include "faultlog_freeze.h"
58 #include "faultlog_processor_base.h"
59 #include "faultlog_events_processor.h"
60 #include "faultlog_processor_factory.h"
61 #include "faultlog_bootscan.h"
62 #include "faultlog_manager_service.h"
63 #include "faultlog_hilog_helper.h"
64 #include "faultlog_event_factory.h"
65 #include "faultlog_cppcrash.h"
66 #include "faultlog_jserror.h"
67 #include "faultlog_cjerror.h"
68 #include "page_history_manager.h"
69
70 using namespace testing::ext;
71 using namespace OHOS::HiviewDFX;
72 using namespace OHOS::HiviewDFX::FaultlogHilogHelper;
73 namespace OHOS {
74 namespace HiviewDFX {
75 DEFINE_LOG_LABEL(0xD002D11, "FaultloggerUT");
76 static std::shared_ptr<FaultEventListener> faultEventListener = nullptr;
77 static std::map<int, std::string> fileNames_ = {};
78
InitHiviewContext()79 static HiviewContext& InitHiviewContext()
80 {
81 OHOS::HiviewDFX::HiviewPlatform &platform = HiviewPlatform::GetInstance();
82 bool result = platform.InitEnvironment("/data/test/test_faultlogger_data/hiview_platform_config");
83 printf("InitHiviewContext result:%d\n", result);
84 return platform;
85 }
86
GetHiviewContext()87 static HiviewContext& GetHiviewContext()
88 {
89 static HiviewContext& hiviewContext = InitHiviewContext();
90 return hiviewContext;
91 }
92
StartHisyseventListen(std::string domain,std::string eventName)93 static void StartHisyseventListen(std::string domain, std::string eventName)
94 {
95 faultEventListener = std::make_shared<FaultEventListener>();
96 ListenerRule tagRule(domain, eventName, RuleType::WHOLE_WORD);
97 std::vector<ListenerRule> sysRules = {tagRule};
98 HiSysEventManager::AddListener(faultEventListener, sysRules);
99 }
100
InitFaultloggerInstance()101 static std::shared_ptr<Faultlogger> InitFaultloggerInstance()
102 {
103 auto plugin = std::make_shared<Faultlogger>();
104 plugin->SetName("Faultlogger");
105 plugin->SetHandle(nullptr);
106 plugin->SetHiviewContext(&GetHiviewContext());
107 plugin->OnLoad();
108 return plugin;
109 }
110
GetFaultloggerInstance()111 static std::shared_ptr<Faultlogger> GetFaultloggerInstance()
112 {
113 static std::shared_ptr<Faultlogger> faultloggerInstance = InitFaultloggerInstance();
114 return faultloggerInstance;
115 }
116
117 namespace {
__anonc0da2f8b0202(int32_t *ptr) 118 auto g_fdDeleter = [] (int32_t *ptr) {
119 if (*ptr > 0) {
120 close(*ptr);
121 }
122 delete ptr;
123 };
124 }
125
126 class FaultloggerUnittest : public testing::Test {
127 public:
SetUp()128 void SetUp()
129 {
130 sleep(1);
131 GetHiviewContext();
132 };
TearDown()133 void TearDown() {};
134
CheckSumarryParseResult(std::string & info,int & matchCount)135 static void CheckSumarryParseResult(std::string& info, int& matchCount)
136 {
137 Json::Reader reader;
138 Json::Value appEvent;
139 if (!(reader.parse(info, appEvent))) {
140 matchCount--;
141 }
142 auto exception = appEvent["exception"];
143 if (exception["name"] == "" || exception["name"] == "none") {
144 matchCount--;
145 }
146 if (exception["message"] == "" || exception["message"] == "none") {
147 matchCount--;
148 }
149 if (exception["stack"] == "" || exception["stack"] == "none") {
150 matchCount--;
151 }
152 }
153
CheckKeyWordsInFile(const std::string & filePath,std::string * keywords,int length,bool isJsError)154 static int CheckKeyWordsInFile(const std::string& filePath, std::string *keywords, int length, bool isJsError)
155 {
156 std::ifstream file;
157 file.open(filePath.c_str(), std::ios::in);
158 std::ostringstream infoStream;
159 infoStream << file.rdbuf();
160 std::string info = infoStream.str();
161 if (info.length() == 0) {
162 std::cout << "file is empty, file:" << filePath << std::endl;
163 return 0;
164 }
165 int matchCount = 0;
166 for (int index = 0; index < length; index++) {
167 if (info.find(keywords[index]) != std::string::npos) {
168 matchCount++;
169 } else {
170 std::cout << "can not find keyword:" << keywords[index] << std::endl;
171 }
172 }
173 if (isJsError) {
174 CheckSumarryParseResult(info, matchCount);
175 }
176 file.close();
177 return matchCount;
178 }
179
ConstructJsErrorAppEvent(std::string summmay,std::shared_ptr<Faultlogger> plugin)180 static void ConstructJsErrorAppEvent(std::string summmay, std::shared_ptr<Faultlogger> plugin)
181 {
182 SysEventCreator sysEventCreator("AAFWK", "JSERROR", SysEventCreator::FAULT);
183 sysEventCreator.SetKeyValue("SUMMARY", summmay);
184 sysEventCreator.SetKeyValue("name_", "JS_ERROR");
185 sysEventCreator.SetKeyValue("happenTime_", 1670248360359); // 1670248360359 : Simulate happenTime_ value
186 sysEventCreator.SetKeyValue("REASON", "TypeError");
187 sysEventCreator.SetKeyValue("tz_", "+0800");
188 sysEventCreator.SetKeyValue("pid_", 2413); // 2413 : Simulate pid_ value
189 sysEventCreator.SetKeyValue("tid_", 2413); // 2413 : Simulate tid_ value
190 sysEventCreator.SetKeyValue("what_", 3); // 3 : Simulate what_ value
191 sysEventCreator.SetKeyValue("PACKAGE_NAME", "com.ohos.systemui");
192 sysEventCreator.SetKeyValue("VERSION", "1.0.0");
193 sysEventCreator.SetKeyValue("TYPE", 3); // 3 : Simulate TYPE value
194 sysEventCreator.SetKeyValue("VERSION", "1.0.0");
195
196 auto sysEvent = std::make_shared<SysEvent>("test", nullptr, sysEventCreator);
197 std::shared_ptr<Event> event = std::dynamic_pointer_cast<Event>(sysEvent);
198 bool result = plugin->OnEvent(event);
199 ASSERT_EQ(result, true);
200 }
201
ConstructJsErrorAppEventWithNoValue(std::string summmay,std::shared_ptr<Faultlogger> plugin)202 static void ConstructJsErrorAppEventWithNoValue(std::string summmay, std::shared_ptr<Faultlogger> plugin)
203 {
204 SysEventCreator sysEventCreator("AAFWK", "JSERROR", SysEventCreator::FAULT);
205 sysEventCreator.SetKeyValue("SUMMARY", summmay);
206 sysEventCreator.SetKeyValue("name_", "JS_ERROR");
207 sysEventCreator.SetKeyValue("happenTime_", 1670248360359); // 1670248360359 : Simulate happenTime_ value
208 sysEventCreator.SetKeyValue("TYPE", 3); // 3 : Simulate TYPE value
209 sysEventCreator.SetKeyValue("VERSION", "1.0.0");
210
211 auto sysEvent = std::make_shared<SysEvent>("test", nullptr, sysEventCreator);
212 std::shared_ptr<Event> event = std::dynamic_pointer_cast<Event>(sysEvent);
213 bool result = plugin->OnEvent(event);
214 ASSERT_EQ(result, true);
215 }
216
CheckKeyWordsInJsErrorAppEventFile(std::string name)217 static void CheckKeyWordsInJsErrorAppEventFile(std::string name)
218 {
219 std::string keywords[] = {
220 "\"bundle_name\":", "\"bundle_version\":", "\"crash_type\":", "\"exception\":",
221 "\"foreground\":", "\"hilog\":", "\"pid\":", "\"time\":", "\"uid\":", "\"uuid\":",
222 "\"name\":", "\"message\":", "\"stack\":"
223 };
224 int length = sizeof(keywords) / sizeof(keywords[0]);
225 std::string oldFileName = "/data/test_jsError_info";
226 int count = CheckKeyWordsInFile(oldFileName, keywords, length, true);
227 ASSERT_EQ(count, length) << "ReportJsErrorToAppEventTest001-" + name + " check keywords failed";
228 if (FileUtil::FileExists(oldFileName)) {
229 std::string newFileName = oldFileName + "_" + name;
230 rename(oldFileName.c_str(), newFileName.c_str());
231 }
232 auto ret = remove("/data/test_jsError_info");
233 if (ret == 0) {
234 GTEST_LOG_(INFO) << "remove /data/test_jsError_info failed";
235 }
236 }
237
ConstructCjErrorAppEvent(std::string summmay,std::shared_ptr<Faultlogger> plugin)238 static void ConstructCjErrorAppEvent(std::string summmay, std::shared_ptr<Faultlogger> plugin)
239 {
240 SysEventCreator sysEventCreator("CJ_RUNTIME", "CJERROR", SysEventCreator::FAULT);
241 sysEventCreator.SetKeyValue("SUMMARY", summmay);
242 sysEventCreator.SetKeyValue("name_", "CJ_ERROR");
243 sysEventCreator.SetKeyValue("happenTime_", 1670248360359); // 1670248360359 : Simulate happenTime_ value
244 sysEventCreator.SetKeyValue("REASON", "std.core:Exception");
245 sysEventCreator.SetKeyValue("tz_", "+0800");
246 sysEventCreator.SetKeyValue("pid_", 2413); // 2413 : Simulate pid_ value
247 sysEventCreator.SetKeyValue("tid_", 2413); // 2413 : Simulate tid_ value
248 sysEventCreator.SetKeyValue("what_", 3); // 3 : Simulate what_ value
249 sysEventCreator.SetKeyValue("PACKAGE_NAME", "com.ohos.systemui");
250 sysEventCreator.SetKeyValue("VERSION", "1.0.0");
251 sysEventCreator.SetKeyValue("TYPE", 3); // 3 : Simulate TYPE value
252 sysEventCreator.SetKeyValue("VERSION", "1.0.0");
253
254 auto sysEvent = std::make_shared<SysEvent>("test", nullptr, sysEventCreator);
255 std::shared_ptr<Event> event = std::dynamic_pointer_cast<Event>(sysEvent);
256 bool result = plugin->OnEvent(event);
257 ASSERT_EQ(result, true);
258 }
259
CheckKeyWordsInCjErrorAppEventFile(std::string name)260 static void CheckKeyWordsInCjErrorAppEventFile(std::string name)
261 {
262 std::string keywords[] = {
263 "\"bundle_name\":", "\"bundle_version\":", "\"crash_type\":", "\"exception\":",
264 "\"foreground\":", "\"hilog\":", "\"pid\":", "\"time\":", "\"uid\":", "\"uuid\":",
265 "\"name\":", "\"message\":", "\"stack\":"
266 };
267 int length = sizeof(keywords) / sizeof(keywords[0]);
268 std::cout << "length:" << length << std::endl;
269 std::string oldFileName = "/data/test_cjError_info";
270 int count = CheckKeyWordsInFile(oldFileName, keywords, length, false);
271 std::cout << "count:" << count << std::endl;
272 ASSERT_EQ(count, length) << "ReportCjErrorToAppEventTest001-" + name + " check keywords failed";
273 if (FileUtil::FileExists(oldFileName)) {
274 std::string newFileName = oldFileName + "_" + name;
275 rename(oldFileName.c_str(), newFileName.c_str());
276 }
277 auto ret = remove("/data/test_cjError_info");
278 if (ret == 0) {
279 GTEST_LOG_(INFO) << "remove /data/test_cjError_info failed";
280 }
281 }
282
CheckDeleteStackErrorMessage(std::string name)283 static void CheckDeleteStackErrorMessage(std::string name)
284 {
285 std::string keywords[] = {"\"Cannot get SourceMap info, dump raw stack:"};
286 int length = sizeof(keywords) / sizeof(keywords[0]);
287 std::string oldFileName = "/data/test_jsError_info";
288 int count = CheckKeyWordsInFile(oldFileName, keywords, length, true);
289 ASSERT_NE(count, length) << "check delete stack error message failed";
290 }
291 };
292
293 static const std::string APPFREEZE_FAULT_FILE = "/data/test/test_data/SmartParser/test_faultlogger_data/";
294
295 /**
296 * @tc.name: dumpFileListTest001
297 * @tc.desc: dump with cmds, check the result
298 * @tc.type: FUNC
299 */
300 HWTEST_F(FaultloggerUnittest, dumpFileListTest001, testing::ext::TestSize.Level3)
301 {
302 /**
303 * @tc.steps: step1. add multiple cmds to faultlogger
304 * @tc.expected: check the content size of the dump function
305 */
306 auto plugin = GetFaultloggerInstance();
307 FaultLogManagerService faultlogManagerService(plugin->GetWorkLoop(), plugin->faultLogManager_);
308 int fd = TEMP_FAILURE_RETRY(open("/data/test/testFile", O_CREAT | O_WRONLY | O_TRUNC, 770));
309 bool isSuccess = fd >= 0;
310 if (!isSuccess) {
311 ASSERT_FALSE(isSuccess);
312 printf("Fail to create test result file.\n");
313 } else {
314 std::vector<std::string> cmds;
315 faultlogManagerService.Dump(fd, cmds);
316 cmds.push_back("Faultlogger");
317 faultlogManagerService.Dump(fd, cmds);
318 cmds.push_back("-l");
319 faultlogManagerService.Dump(fd, cmds);
320 cmds.push_back("-f");
321 faultlogManagerService.Dump(fd, cmds);
322 cmds.push_back("cppcrash-ModuleName-10-20201209103823");
323 faultlogManagerService.Dump(fd, cmds);
324 cmds.push_back("-d");
325 faultlogManagerService.Dump(fd, cmds);
326 cmds.push_back("-t");
327 faultlogManagerService.Dump(fd, cmds);
328 cmds.push_back("20201209103823");
329 faultlogManagerService.Dump(fd, cmds);
330 cmds.push_back("-m");
331 faultlogManagerService.Dump(fd, cmds);
332 cmds.push_back("FAULTLOGGER");
333 close(fd);
334 fd = -1;
335
336 std::string result;
337 if (FileUtil::LoadStringFromFile("/data/test/testFile", result)) {
338 ASSERT_GT(result.length(), 0uL);
339 } else {
340 FAIL();
341 }
342 }
343 }
344
345 /**
346 * @tc.name: DumpTest002
347 * @tc.desc: dump with cmds, check the result
348 * @tc.type: FUNC
349 */
350 HWTEST_F(FaultloggerUnittest, DumpTest002, testing::ext::TestSize.Level3)
351 {
352 /**
353 * @tc.steps: step1. add multiple cmds to faultlogger
354 * @tc.expected: check the content size of the dump function
355 */
356 auto plugin = GetFaultloggerInstance();
357 int fd = TEMP_FAILURE_RETRY(open("/data/test/testFile", O_CREAT | O_WRONLY | O_TRUNC, 770));
358 bool isSuccess = fd >= 0;
359 if (!isSuccess) {
360 ASSERT_FALSE(isSuccess);
361 printf("Fail to create test result file.\n");
362 } else {
363 std::vector<std::vector<std::string>> cmds = {
364 {"-f", "1cppcrash-10-20201209103823"},
365 {"-f", "1cppcrash-ModuleName-10-20201209103823"},
366 {"-f", "cppcrash--10-20201209103823"},
367 {"-f", "cppcrash-ModuleName-a10-20201209103823"}
368 };
369
370 for (auto& cmd : cmds) {
371 plugin->Dump(fd, cmd);
372 }
373
374 close(fd);
375 fd = -1;
376
377 std::string result;
378 if (FileUtil::LoadStringFromFile("/data/test/testFile", result)) {
379 ASSERT_GT(result.length(), 0uL);
380 } else {
381 FAIL();
382 }
383 }
384 }
385
386 /**
387 * @tc.name: DumpTest003
388 * @tc.desc: dump with cmds, check the result
389 * @tc.type: FUNC
390 */
391 HWTEST_F(FaultloggerUnittest, DumpTest003, testing::ext::TestSize.Level3)
392 {
393 /**
394 * @tc.steps: step1. add multiple cmds to faultlogger
395 * @tc.expected: check the content size of the dump function
396 */
397 auto plugin = GetFaultloggerInstance();
398 FaultLogManagerService faultlogManagerService(plugin->GetWorkLoop(), plugin->faultLogManager_);
399 int fd = TEMP_FAILURE_RETRY(open("/data/test/testFile", O_CREAT | O_WRONLY | O_TRUNC, 770));
400 bool isSuccess = fd >= 0;
401 if (!isSuccess) {
402 ASSERT_FALSE(isSuccess);
403 printf("Fail to create test result file.\n");
404 } else {
405 std::vector<std::vector<std::string>> cmds = {
406 {"-t", "cppcrash--10-20201209103823"},
407 {"-m", ""},
408 {"-l", ""},
409 {"-xx"}
410 };
411
412 for (auto& cmd : cmds) {
413 faultlogManagerService.Dump(fd, cmd);
414 }
415
416 close(fd);
417 fd = -1;
418
419 std::string result;
420 if (FileUtil::LoadStringFromFile("/data/test/testFile", result)) {
421 ASSERT_GT(result.length(), 0uL);
422 } else {
423 FAIL();
424 }
425 }
426 }
427
428 /**
429 * @tc.name: DumpTest004
430 * @tc.desc: dump with cmds, check the result
431 * @tc.type: FUNC
432 */
433 HWTEST_F(FaultloggerUnittest, DumpTest004, testing::ext::TestSize.Level3)
434 {
435 /**
436 * @tc.steps: step1. add multiple cmds to faultlogger
437 * @tc.expected: check the content size of the dump function
438 */
439
440 auto plugin = GetFaultloggerInstance();
441 FaultLogInfo info;
442 info.time = 1607161163; // 1607161163 : analog value of time
443 info.id = 10001;
444 info.pid = 7496; // 7496 : analog value of pid
445 info.faultLogType = 2; // 2 : CPP_CRASH
446 info.module = "com.example.myapplication";
447 FaultLogManagerService faultlogManagerService(plugin->GetWorkLoop(), plugin->faultLogManager_);
448 faultlogManagerService.AddFaultLog(info);
449 std::string timeStr = GetFormatedTimeWithMillsec(info.time);
450 std::string appName = GetApplicationNameById(info.id);
451 if (appName.size() == 0) {
452 appName = info.module;
453 }
454 std::string fileName = "cppcrash-" + appName + "-" + std::to_string(info.id) + "-" + timeStr + ".log";
455 auto path = "/data/log/faultlog/faultlogger/" + fileName;
456 ASSERT_EQ(FileUtil::FileExists(path), true);
457
458 int fd = TEMP_FAILURE_RETRY(open("/data/test/testFile", O_CREAT | O_WRONLY | O_TRUNC, 770));
459 bool isSuccess = fd >= 0;
460 if (!isSuccess) {
461 ASSERT_FALSE(isSuccess);
462 printf("Fail to create test result file.\n");
463 } else {
464 std::vector<std::vector<std::string>> cmds = {
465 {"-LogSuffixWithMs", ""},
466 {"-f", fileName}
467 };
468
469 for (auto& cmd : cmds) {
470 faultlogManagerService.Dump(fd, cmd);
471 }
472
473 close(fd);
474 fd = -1;
475 std::string keywords[] = { "Device info", "Build info", "Fingerprint", "Module name" };
476 int length = sizeof(keywords) / sizeof(keywords[0]);
477 ASSERT_EQ(CheckKeyWordsInFile("/data/test/testFile", keywords, length, false), length);
478 }
479 }
480
GenCppCrashLogTestCommon(int32_t uid,bool ifFileExist)481 static void GenCppCrashLogTestCommon(int32_t uid, bool ifFileExist)
482 {
483 int pipeFd[2] = {-1, -1};
484 ASSERT_EQ(pipe(pipeFd), 0) << "create pipe failed";
485 auto plugin = GetFaultloggerInstance();
486 FaultLogInfo info;
487 info.time = 1607161163; // 1607161163 : analog value of time
488 info.id = uid;
489 info.pid = 7496; // 7496 : analog value of pid
490 info.faultLogType = 2; // 2 : CPP_CRASH
491 info.module = "com.example.myapplication";
492 info.sectionMap["APPVERSION"] = "1.0";
493 info.sectionMap["FAULT_MESSAGE"] = "Nullpointer";
494 info.sectionMap["TRACEID"] = "0x1646145645646";
495 info.sectionMap["KEY_THREAD_INFO"] = "Test Thread Info";
496 info.sectionMap["REASON"] = "TestReason";
497 info.sectionMap["STACKTRACE"] = "#01 xxxxxx\n#02 xxxxxx\n";
498 info.pipeFd.reset(new int32_t(pipeFd[0]), g_fdDeleter);
499 std::string jsonInfo = R"~({"crash_type":"NativeCrash", "exception":{"frames":
500 [{"buildId":"", "file":"/system/lib/ld-musl-arm.so.1", "offset":28, "pc":"000ac0a4", "symbol":"test_abc"},
501 {"buildId":"12345abcde", "file":"/system/lib/chipset-pub-sdk/libeventhandler.z.so", "offset":278,
502 "pc":"0000bef3", "symbol":"OHOS::AppExecFwk::EpollIoWaiter::WaitFor(std::__h::unique_lock<std::__h::mutex>&,
503 long long)"}], "message":"", "signal":{"code":0, "signo":6}, "thread_name":"e.myapplication", "tid":1605},
504 "pid":1605, "threads":[{"frames":[{"buildId":"", "file":"/system/lib/ld-musl-arm.so.1", "offset":72, "pc":
505 "000c80b4", "symbol":"ioctl"}, {"buildId":"2349d05884359058d3009e1fe27b15fa", "file":
506 "/system/lib/platformsdk/libipc_core.z.so", "offset":26, "pc":"0002cad7",
507 "symbol":"OHOS::BinderConnector::WriteBinder(unsigned long, void*)"}], "thread_name":"OS_IPC_0_1607",
508 "tid":1607}, {"frames":[{"buildId":"", "file":"/system/lib/ld-musl-arm.so.1", "offset":0, "pc":"000fdf4c",
509 "symbol":""}, {"buildId":"", "file":"/system/lib/ld-musl-arm.so.1", "offset":628, "pc":"000ff7f4",
510 "symbol":"__pthread_cond_timedwait_time64"}], "thread_name":"OS_SignalHandle", "tid":1608}],
511 "time":1701863741296, "uid":20010043, "uuid":""})~";
512 TEMP_FAILURE_RETRY(write(pipeFd[1], jsonInfo.c_str(), jsonInfo.size()));
513 close(pipeFd[1]);
514 FaultLogManagerService faultlogManagerService(plugin->GetWorkLoop(), plugin->faultLogManager_);
515 faultlogManagerService.AddFaultLog(info);
516 std::string timeStr = GetFormatedTimeWithMillsec(info.time);
517 std::string appName = GetApplicationNameById(info.id);
518 if (appName.size() == 0) {
519 appName = info.module;
520 }
521 std::string fileName = "/data/log/faultlog/faultlogger/cppcrash-" + appName + "-" +
522 std::to_string(info.id) + "-" + timeStr + ".log";
523 ASSERT_EQ(FileUtil::FileExists(fileName), true);
524 ASSERT_GT(FileUtil::GetFileSize(fileName), 0ul);
525 // check appevent json info
526 ASSERT_EQ(FileUtil::FileExists("/data/test_cppcrash_info_7496"), ifFileExist);
527 }
528
529 /**
530 * @tc.name: genCppCrashLogTest001
531 * @tc.desc: create cpp crash event and send it to faultlogger
532 * check info which send to appevent
533 * @tc.type: FUNC
534 */
535 HWTEST_F(FaultloggerUnittest, GenCppCrashLogTest001, testing::ext::TestSize.Level3)
536 {
537 GenCppCrashLogTestCommon(10001, true); // 10001 : analog value of user uid
538 string keywords[] = { "\"time\":", "\"pid\":", "\"exception\":", "\"threads\":", "\"thread_name\":", "\"tid\":" };
539 int length = sizeof(keywords) / sizeof(keywords[0]);
540 ASSERT_EQ(CheckKeyWordsInFile("/data/test_cppcrash_info_7496", keywords, length, false), length);
541 auto ret = remove("/data/test_cppcrash_info_7496");
542 if (ret != 0) {
543 GTEST_LOG_(INFO) << "remove /data/test_jsError_info failed. errno " << errno;
544 }
545 }
546
547 /**
548 * @tc.name: genCppCrashLogTest002
549 * @tc.desc: create cpp crash event and send it to faultlogger
550 * check info which send to appevent
551 * @tc.type: FUNC
552 */
553 HWTEST_F(FaultloggerUnittest, GenCppCrashLogTest002, testing::ext::TestSize.Level3)
554 {
555 GenCppCrashLogTestCommon(0, false); // 0 : analog value of system uid
556 }
557
558 /**
559 * @tc.name: AddFaultLogTest001
560 * @tc.desc: create cpp crash event and send it to faultlogger
561 * check info which send to appevent
562 * @tc.type: FUNC
563 */
564 HWTEST_F(FaultloggerUnittest, AddFaultLogTest001, testing::ext::TestSize.Level0)
565 {
566 auto plugin = GetFaultloggerInstance();
567 FaultLogManagerService faultlogManagerService(plugin->GetWorkLoop(), plugin->faultLogManager_);
568
569 FaultLogInfo info;
570 plugin->hasInit_ = false;
571 faultlogManagerService.AddFaultLog(info);
572
573 plugin->hasInit_ = true;
574 info.faultLogType = -1;
575 faultlogManagerService.AddFaultLog(info);
576
577 info.faultLogType = 8; // 8 : 8 is bigger than FaultLogType::ADDR_SANITIZER
578 faultlogManagerService.AddFaultLog(info);
579
580 info.faultLogType = FaultLogType::CPP_CRASH;
581 info.id = 1;
582 info.module = "com.example.myapplication";
583 info.time = 1607161163;
584 info.pid = 7496;
585 faultlogManagerService.AddFaultLog(info);
586 std::string timeStr = GetFormatedTimeWithMillsec(info.time);
587 std::string fileName = "/data/log/faultlog/faultlogger/cppcrash-com.example.myapplication-1-" + timeStr + ".log";
588 ASSERT_EQ(FileUtil::FileExists(fileName), true);
589 }
590
591 /**
592 * @tc.name: AddPublicInfoTest001
593 * @tc.desc: create cpp crash event and send it to faultlogger
594 * check info which send to appevent
595 * @tc.type: FUNC
596 */
597 HWTEST_F(FaultloggerUnittest, AddPublicInfoTest001, testing::ext::TestSize.Level3)
598 {
599 FaultLogInfo info;
600 info.time = 1607161163;
601 info.id = 0;
602 info.pid = 7496;
603 info.faultLogType = 1;
604 info.module = "com.example.myapplication";
605 info.sectionMap["APPVERSION"] = "1.0";
606 info.sectionMap["FAULT_MESSAGE"] = "Nullpointer";
607 info.sectionMap["TRACEID"] = "0x1646145645646";
608 info.sectionMap["KEY_THREAD_INFO"] = "Test Thread Info";
609 info.sectionMap["REASON"] = "TestReason";
610 info.sectionMap["STACKTRACE"] = "#01 xxxxxx\n#02 xxxxxx\n";
611 FaultLogEventsProcessor faultAddFault;
612 faultAddFault.AddCommonInfo(info);
613 std::string timeStr = GetFormatedTimeWithMillsec(info.time);
614 std::string fileName = "/data/log/faultlog/faultlogger/cppcrash-com.example.myapplication-0-" + timeStr + ".log";
615 ASSERT_EQ(FileUtil::FileExists(fileName), true);
616 }
617
618 /**
619 * @tc.name: GetFreezeJsonCollectorTest001
620 * @tc.desc: test GetFreezeJsonCollector
621 * @tc.type: FUNC
622 */
623 HWTEST_F(FaultloggerUnittest, GetFreezeJsonCollectorTest001, testing::ext::TestSize.Level3)
624 {
625 FaultLogInfo info;
626 info.time = 20170805172159;
627 info.id = 10006;
628 info.pid = 1;
629 info.faultLogType = 1;
630 info.module = "com.example.myapplication";
631 info.sectionMap["APPVERSION"] = "1.0";
632 info.sectionMap["FAULT_MESSAGE"] = "Nullpointer";
633 info.sectionMap["TRACEID"] = "0x1646145645646";
634 info.sectionMap["KEY_THREAD_INFO"] = "Test Thread Info";
635 info.sectionMap["REASON"] = "TestReason";
636 info.sectionMap["STACKTRACE"] = "#01 xxxxxx\n#02 xxxxxx\n";
637 FaultLogFreeze faultLogAppFreeze;
638 FreezeJsonUtil::FreezeJsonCollector collector = faultLogAppFreeze.GetFreezeJsonCollector(info);
639 ASSERT_EQ(collector.exception, "{}");
640 }
641
642 /**
643 * @tc.name: genCppCrashtoAnalysisFaultlog
644 * @tc.desc: create cpp crash event and check AnalysisFaultlog
645 * @tc.type: FUNC
646 */
647 HWTEST_F(FaultloggerUnittest, genCppCrashtoAnalysisFaultlog001, testing::ext::TestSize.Level3)
648 {
649 /**
650 * @tc.steps: step1. create a cpp crash event and pass it to faultlogger
651 * @tc.expected: AnalysisFaultlog return expected result
652 */
653 FaultLogInfo info;
654 info.time = 1607161163;
655 info.id = 0;
656 info.pid = 7497;
657 info.faultLogType = 2;
658 info.module = "com.example.testapplication";
659 info.reason = "TestReason";
660 std::map<std::string, std::string> eventInfos;
661 ASSERT_EQ(AnalysisFaultlog(info, eventInfos), false);
662 ASSERT_EQ(!eventInfos["FINGERPRINT"].empty(), true);
663 }
664
665 /**
666 * @tc.name: genJsCrashtoAnalysisFaultlog001
667 * @tc.desc: create Js crash FaultLogInfo and check AnalysisFaultlog
668 * @tc.type: FUNC
669 */
670 HWTEST_F(FaultloggerUnittest, genJsCrashtoAnalysisFaultlog001, testing::ext::TestSize.Level3)
671 {
672 /**
673 * @tc.steps: step1. create Js crash FaultLogInfo
674 * @tc.expected: AnalysisFaultlog return expected result
675 */
676 FaultLogInfo info;
677 info.time = 1607161163;
678 info.id = 0;
679 info.pid = 7497;
680 info.faultLogType = 3;
681 info.module = "com.example.testapplication";
682 info.reason = "TestReason";
683 std::map<std::string, std::string> eventInfos;
684 ASSERT_EQ(AnalysisFaultlog(info, eventInfos), false);
685 ASSERT_EQ(!eventInfos["FINGERPRINT"].empty(), true);
686 }
687
688 /**
689 * @tc.name: genjserrorLogTest002
690 * @tc.desc: create JS ERROR event and send it to faultlogger
691 * @tc.type: FUNC
692 */
693 HWTEST_F(FaultloggerUnittest, genjserrorLogTest002, testing::ext::TestSize.Level3)
694 {
695 /**
696 * @tc.steps: step1. create a jss_error event and pass it to faultlogger
697 * @tc.expected: the calling is success and the file has been created
698 */
699 SysEventCreator sysEventCreator("AAFWK", "JSERROR", SysEventCreator::FAULT);
700 sysEventCreator.SetKeyValue("SUMMARY", "Error message:is not callable\nStacktrace:");
701 sysEventCreator.SetKeyValue("name_", "JS_ERROR");
702 sysEventCreator.SetKeyValue("happenTime_", 1670248360359);
703 sysEventCreator.SetKeyValue("REASON", "TypeError");
704 sysEventCreator.SetKeyValue("tz_", "+0800");
705 sysEventCreator.SetKeyValue("pid_", 2413);
706 sysEventCreator.SetKeyValue("tid_", 2413);
707 sysEventCreator.SetKeyValue("what_", 3);
708 sysEventCreator.SetKeyValue("PACKAGE_NAME", "com.ohos.systemui");
709 sysEventCreator.SetKeyValue("VERSION", "1.0.0");
710 sysEventCreator.SetKeyValue("TYPE", 3);
711 sysEventCreator.SetKeyValue("VERSION", "1.0.0");
712
713 auto sysEvent = std::make_shared<SysEvent>("test", nullptr, sysEventCreator);
714 auto testPlugin = GetFaultloggerInstance();
715 std::shared_ptr<Event> event = std::dynamic_pointer_cast<Event>(sysEvent);
716 bool result = testPlugin->OnEvent(event);
717 ASSERT_EQ(result, true);
718 auto ret = remove("/data/test_jsError_info");
719 if (ret < 0) {
720 GTEST_LOG_(INFO) << "remove /data/test_jsError_info failed";
721 }
722 }
723
724 /**
725 * @tc.name: IsInterestedPipelineEvent
726 * @tc.desc: Test calling IsInterestedPipelineEvent Func
727 * @tc.type: FUNC
728 */
729 HWTEST_F(FaultloggerUnittest, IsInterestedPipelineEvent, testing::ext::TestSize.Level3)
730 {
731 auto testPlugin = GetFaultloggerInstance();
732 std::shared_ptr<Event> event = std::make_shared<Event>("test");
733 event->SetEventName("PROCESS_EXIT");
734 EXPECT_TRUE(testPlugin->IsInterestedPipelineEvent(event));
735 event->SetEventName("JS_ERROR");
736 EXPECT_TRUE(testPlugin->IsInterestedPipelineEvent(event));
737 event->SetEventName("RUST_PANIC");
738 EXPECT_TRUE(testPlugin->IsInterestedPipelineEvent(event));
739 event->SetEventName("ADDR_SANITIZER");
740 EXPECT_TRUE(testPlugin->IsInterestedPipelineEvent(event));
741 event->SetEventName("OTHERS");
742 EXPECT_FALSE(testPlugin->IsInterestedPipelineEvent(event));
743 };
744
745 /**
746 * @tc.name: CanProcessEvent
747 * @tc.desc: Test calling CanProcessEvent Func
748 * @tc.type: FUNC
749 */
750 HWTEST_F(FaultloggerUnittest, CanProcessEvent, testing::ext::TestSize.Level3)
751 {
752 auto testPlugin = GetFaultloggerInstance();
753 std::shared_ptr<Event> event = std::make_shared<Event>("test");
754 ASSERT_TRUE(testPlugin->CanProcessEvent(event));
755 };
756
757 /**
758 * @tc.name: ReadyToLoad
759 * @tc.desc: Test calling ReadyToLoad Func
760 * @tc.type: FUNC
761 */
762 HWTEST_F(FaultloggerUnittest, ReadyToLoad, testing::ext::TestSize.Level3)
763 {
764 auto testPlugin = GetFaultloggerInstance();
765 ASSERT_TRUE(testPlugin->ReadyToLoad());
766 };
767
768 /**
769 * @tc.name: SaveFaultLogInfoTest001
770 * @tc.desc: Test calling SaveFaultLogInfo Func
771 * @tc.type: FUNC
772 */
773 HWTEST_F(FaultloggerUnittest, SaveFaultLogInfoTest001, testing::ext::TestSize.Level3)
774 {
775 StartHisyseventListen("RELIABILITY", "CPP_CRASH");
776 time_t now = std::time(nullptr);
777 std::vector<std::string> keyWords = { std::to_string(now) };
778 faultEventListener->SetKeyWords(keyWords);
779 FaultLogDatabase *faultLogDb = new FaultLogDatabase(GetHiviewContext().GetSharedWorkLoop());
780 FaultLogInfo info;
781 info.time = now;
782 info.pid = getpid();
783 info.id = 0;
784 info.faultLogType = 2;
785 info.logPath = "/data/log/faultlog/faultlogger/cppcrash-SaveFaultLogInfoTest001-20020100-20250501090923033.log";
786 info.module = "FaultloggerUnittest";
787 info.reason = "unittest for SaveFaultLogInfo";
788 info.summary = "summary for SaveFaultLogInfo";
789 info.sectionMap["APPVERSION"] = "1.0";
790 info.sectionMap["FAULT_MESSAGE"] = "abort";
791 info.sectionMap["TRACEID"] = "0x1646145645646";
792 info.sectionMap["KEY_THREAD_INFO"] = "Test Thread Info";
793 info.sectionMap["REASON"] = "TestReason";
794 info.sectionMap["STACKTRACE"] = "#01 xxxxxx\n#02 xxxxxx\n";
795 faultLogDb->SaveFaultLogInfo(info);
796 ASSERT_TRUE(faultEventListener->CheckKeyWords());
797 }
798
799 /**
800 * @tc.name: GetFaultInfoListTest001
801 * @tc.desc: Test calling GetFaultInfoList Func
802 * @tc.type: FUNC
803 */
804 HWTEST_F(FaultloggerUnittest, GetFaultInfoListTest001, testing::ext::TestSize.Level3)
805 {
806 std::string jsonStr = R"~({"domain_":"RELIABILITY", "name_":"CPP_CRASH", "type_":1, "time_":1501973701070, "tz_":
807 "+0800", "pid_":1854, "tid_":1854, "uid_":0, "FAULT_TYPE":"2", "PID":1854, "UID":0, "MODULE":"FaultloggerUnittest",
808 "REASON":"unittest for SaveFaultLogInfo", "SUMMARY":"summary for SaveFaultLogInfo", "LOG_PATH":"", "VERSION":"",
809 "HAPPEN_TIME":"1501973701", "PNAME":"/", "FIRST_FRAME":"/", "SECOND_FRAME":"/", "LAST_FRAME":"/", "FINGERPRINT":
810 "04c0d6f03c73da531f00eb112479a8a2f19f59fafba6a474dcbe455a13288f4d", "level_":"CRITICAL", "tag_":"STABILITY", "id_":
811 "17165544771317691984", "info_":""})~";
812 auto sysEvent = std::make_shared<SysEvent>("SysEventSource", nullptr, jsonStr);
813 sysEvent->SetLevel("MINOR");
814 sysEvent->SetEventSeq(447); // 447: test seq
815 EventStore::SysEventDao::Insert(sysEvent);
816 FaultLogDatabase *faultLogDb = new FaultLogDatabase(GetHiviewContext().GetSharedWorkLoop());
817 std::list<FaultLogInfo> infoList = faultLogDb->GetFaultInfoList("FaultloggerUnittest", 0, 2, 10);
818 ASSERT_GT(infoList.size(), 0);
819
820 FaultLogInfo info;
821 bool ret = faultLogDb->ParseFaultLogInfoFromJson(nullptr, info);
822 ASSERT_EQ(ret, false);
823 }
824
825 /**
826 * @tc.name: FaultLogManager::CreateTempFaultLogFile
827 * @tc.desc: Test calling CreateTempFaultLogFile Func
828 * @tc.type: FUNC
829 */
830 HWTEST_F(FaultloggerUnittest, FaultlogManager001, testing::ext::TestSize.Level3)
831 {
832 std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
833 faultLogManager->Init();
834 int fd = faultLogManager->CreateTempFaultLogFile(1607161345, 0, 2, "FaultloggerUnittest");
835 ASSERT_GT(fd, 0);
836 std::string content = "testContent";
837 TEMP_FAILURE_RETRY(write(fd, content.data(), content.length()));
838 close(fd);
839 }
840
841 /**
842 * @tc.name: FaultLogManager::FaultlogManager
843 * @tc.desc: Test calling FaultlogManager Func
844 * @tc.type: FUNC
845 */
846 HWTEST_F(FaultloggerUnittest, FaultlogManager002, testing::ext::TestSize.Level3)
847 {
848 std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
849 std::list<std::string> infoVec = {"1", "2", "3", "4", "5"};
850 faultLogManager->ReduceLogFileListSize(infoVec, 1);
851 ASSERT_EQ(infoVec.size(), 1);
852 }
853
854 /**
855 * @tc.name: FaultLogManager::GetFaultLogFileList
856 * @tc.desc: Test calling GetFaultLogFileList Func
857 * @tc.type: FUNC
858 */
859 HWTEST_F(FaultloggerUnittest, GetFaultLogFileList001, testing::ext::TestSize.Level3)
860 {
861 std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
862 faultLogManager->Init();
863 std::list<std::string> fileList = faultLogManager->GetFaultLogFileList("FaultloggerUnittest", 1607161344, 0, 2, 1);
864 ASSERT_EQ(fileList.size(), 1);
865 }
866
867 /**
868 * @tc.name: FaultLogManager::WriteFaultLogToFile
869 * @tc.desc: Test calling WriteFaultLogToFile Func
870 * @tc.type: FUNC
871 */
872 HWTEST_F(FaultloggerUnittest, WriteFaultLogToFile001, testing::ext::TestSize.Level3)
873 {
874 std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
875 faultLogManager->Init();
876 FaultLogInfo info {
877 .time = 1607161345,
878 .id = 0,
879 .faultLogType = 2,
880 .module = ""
881 };
882 info.faultLogType = FaultLogType::JS_CRASH;
883 FaultLogger::WriteFaultLogToFile(0, info.faultLogType, info.sectionMap);
884 info.faultLogType = FaultLogType::SYS_FREEZE;
885 FaultLogger::WriteFaultLogToFile(0, info.faultLogType, info.sectionMap);
886 info.faultLogType = FaultLogType::SYS_WARNING;
887 FaultLogger::WriteFaultLogToFile(0, info.faultLogType, info.sectionMap);
888 info.faultLogType = FaultLogType::RUST_PANIC;
889 FaultLogger::WriteFaultLogToFile(0, info.faultLogType, info.sectionMap);
890 info.faultLogType = FaultLogType::ADDR_SANITIZER;
891 FaultLogger::WriteFaultLogToFile(0, info.faultLogType, info.sectionMap);
892 info.faultLogType = FaultLogType::ADDR_SANITIZER;
893 FaultLogger::WriteFaultLogToFile(0, info.faultLogType, info.sectionMap);
894 info.faultLogType = FaultLogType::ALL;
895 FaultLogger::WriteFaultLogToFile(0, info.faultLogType, info.sectionMap);
896 ASSERT_EQ(info.pid, 0);
897 }
898
899 /**
900 * @tc.name: FaultLogManager::GetFaultLogContent
901 * @tc.desc: Test calling GetFaultLogContent Func
902 * @tc.type: FUNC
903 */
904 HWTEST_F(FaultloggerUnittest, GetFaultLogContent001, testing::ext::TestSize.Level3)
905 {
906 std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
907 faultLogManager->Init();
908 FaultLogInfo info {
909 .time = 1607161345,
910 .id = 0,
911 .faultLogType = 2,
912 .module = "FaultloggerUnittest"
913 };
914 std::string fileName = GetFaultLogName(info);
915 std::string content;
916 ASSERT_TRUE(faultLogManager->GetFaultLogContent(fileName, content));
917 ASSERT_EQ(content, "testContent");
918 }
919
920 /**
921 * @tc.name: FaultLogManager::GetFaultLogName
922 * @tc.desc: Test calling GetFaultLogName Func
923 * @tc.type: FUNC
924 */
925 HWTEST_F(FaultloggerUnittest, GetFaultLogContent002, testing::ext::TestSize.Level3)
926 {
927 std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
928 faultLogManager->Init();
929 FaultLogInfo info {
930 .time = 1607161345,
931 .id = 0,
932 .faultLogType = FaultLogType::ADDR_SANITIZER,
933 .module = "FaultloggerUnittest"
934 };
935 info.sanitizerType = "ASAN";
936 std::string fileName = GetFaultLogName(info);
937 ASSERT_EQ(fileName, "asan-FaultloggerUnittest-0-20201205174225345.log");
938 info.sanitizerType = "HWASAN";
939 fileName = GetFaultLogName(info);
940 ASSERT_EQ(fileName, "hwasan-FaultloggerUnittest-0-20201205174225345.log");
941 string type = "sanitizer";
942 ASSERT_EQ(GetLogTypeByName(type), FaultLogType::ADDR_SANITIZER);
943 type = "cjerror";
944 ASSERT_EQ(GetLogTypeByName(type), FaultLogType::CJ_ERROR);
945 }
946
947 /**
948 * @tc.name: FaultLogManager::GetDebugSignalTempLogName
949 * @tc.desc: Test calling GetDebugSignalTempLogName Func
950 * @tc.type: FUNC
951 */
952 HWTEST_F(FaultloggerUnittest, GetDebugSignalTempLogName001, testing::ext::TestSize.Level3)
953 {
954 std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
955 faultLogManager->Init();
956 FaultLogInfo info {
957 .time = 1607161345,
958 .id = 0,
959 .faultLogType = FaultLogType::ADDR_SANITIZER,
960 .module = "FaultloggerUnittest"
961 };
962 string fileName = GetDebugSignalTempLogName(info);
963 ASSERT_EQ(fileName, "/data/log/faultlog/temp/stacktrace-0-1607161345");
964 fileName = GetSanitizerTempLogName(info.pid, std::to_string(info.time));
965 ASSERT_EQ(fileName, "/data/log/faultlog/temp/sanitizer-0-1607161345");
966 string str;
967 ASSERT_EQ(GetThreadStack(str, 0), "");
968 }
969
970 /**
971 * @tc.name: FaultLogManager::SaveFaultInfoToRawDb
972 * @tc.desc: Test calling SaveFaultInfoToRawDb Func
973 * @tc.type: FUNC
974 */
975 HWTEST_F(FaultloggerUnittest, FaultLogManagerTest001, testing::ext::TestSize.Level0)
976 {
977 StartHisyseventListen("RELIABILITY", "CPP_CRASH");
978 time_t now = std::time(nullptr);
979 std::vector<std::string> keyWords = { std::to_string(now) };
980 faultEventListener->SetKeyWords(keyWords);
981 FaultLogInfo info;
982 info.time = now;
983 info.pid = getpid();
984 info.id = 0;
985 info.faultLogType = 2;
986 info.logPath = "/data/log/faultlog/faultlogger/cppcrash-FaultLogManagerTest001-20020100-20250501090923033.log";
987 info.module = "FaultloggerUnittest1111";
988 info.reason = "unittest for SaveFaultLogInfo";
989 info.summary = "summary for SaveFaultLogInfo";
990 info.sectionMap["APPVERSION"] = "1.0";
991 info.sectionMap["FAULT_MESSAGE"] = "abort";
992 info.sectionMap["TRACEID"] = "0x1646145645646";
993 info.sectionMap["KEY_THREAD_INFO"] = "Test Thread Info";
994 info.sectionMap["REASON"] = "TestReason";
995 info.sectionMap["STACKTRACE"] = "#01 xxxxxx\n#02 xxxxxx\n";
996 std::unique_ptr<FaultLogManager> faultLogManager =
997 std::make_unique<FaultLogManager>(GetHiviewContext().GetSharedWorkLoop());
998 faultLogManager->Init();
999 faultLogManager->SaveFaultInfoToRawDb(info);
1000 ASSERT_TRUE(faultEventListener->CheckKeyWords());
1001 }
1002
GetTargetFileName(int32_t faultLogType,int64_t time)1003 std::string GetTargetFileName(int32_t faultLogType, int64_t time)
1004 {
1005 fileNames_.clear();
1006 fileNames_ = {
1007 {1, "Unknown"},
1008 {2, "cppcrash"}, // 2 : faultLogType to cppcrash
1009 {3, "jscrash"}, // 3 : faultLogType to jscrash
1010 {4, "appfreeze"}, // 4 : faultLogType to appfreeze
1011 {5, "sysfreeze"}, // 5 : faultLogType to sysfreeze
1012 {6, "syswarning"}, // 6 : faultLogType to syswarning
1013 {7, "rustpanic"}, // 7 : faultLogType to rustpanic
1014 {8, "sanitizer"}, // 8 : faultLogType to sanitizer
1015 };
1016 std::string fileName = fileNames_[faultLogType];
1017 return fileName + "-FaultloggerUnittest1111-0-" + GetFormatedTimeWithMillsec(time) + ".log";
1018 }
1019
1020 /**
1021 * @tc.name: FaultLogManager::SaveFaultLogToFile
1022 * @tc.desc: Test calling SaveFaultLogToFile Func
1023 * @tc.type: FUNC
1024 */
1025 HWTEST_F(FaultloggerUnittest, FaultLogManagerTest003, testing::ext::TestSize.Level3)
1026 {
1027 FaultLogInfo info;
1028 std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
1029 faultLogManager->Init();
1030 for (int i = 1; i <= fileNames_.size(); i++) {
1031 info.time = std::time(nullptr);
1032 info.pid = getpid();
1033 info.id = 0;
1034 info.faultLogType = i;
1035 info.module = "FaultloggerUnittest1111";
1036 info.reason = "unittest for SaveFaultLogInfo";
1037 info.summary = "summary for SaveFaultLogInfo";
1038 info.sectionMap["APPVERSION"] = "1.0";
1039 info.sectionMap["FAULT_MESSAGE"] = "abort";
1040 info.sectionMap["TRACEID"] = "0x1646145645646";
1041 info.sectionMap["KEY_THREAD_INFO"] = "Test Thread Info";
1042 info.sectionMap["REASON"] = "TestReason";
1043 info.sectionMap["STACKTRACE"] = "#01 xxxxxx\n#02 xxxxxx\n";
1044
1045 std::string fileName = faultLogManager->SaveFaultLogToFile(info);
1046 if (fileName.find("FaultloggerUnittest1111") == std::string::npos) {
1047 FAIL();
1048 }
1049 std::string targetFileName = GetTargetFileName(i, info.time);
1050 ASSERT_EQ(fileName, targetFileName);
1051 }
1052 }
1053
1054 /**
1055 * @tc.name: faultLogManager GetFaultInfoListTest001
1056 * @tc.desc: Test calling faultLogManager.GetFaultInfoList Func
1057 * @tc.type: FUNC
1058 */
1059 HWTEST_F(FaultloggerUnittest, FaultLogManagerTest002, testing::ext::TestSize.Level3)
1060 {
1061 std::string jsonStr = R"~({"domain_":"RELIABILITY", "name_":"CPP_CRASH", "type_":1, "time_":1501973701070,
1062 "tz_":"+0800", "pid_":1854, "tid_":1854, "uid_":0, "FAULT_TYPE":"2", "PID":1854, "UID":0,
1063 "MODULE":"FaultloggerUnittest", "REASON":"unittest for SaveFaultLogInfo",
1064 "SUMMARY":"summary for SaveFaultLogInfo", "LOG_PATH":"", "VERSION":"", "HAPPEN_TIME":"1501973701",
1065 "PNAME":"/", "FIRST_FRAME":"/", "SECOND_FRAME":"/", "LAST_FRAME":"/",
1066 "FINGERPRINT":"04c0d6f03c73da531f00eb112479a8a2f19f59fafba6a474dcbe455a13288f4d",
1067 "level_":"CRITICAL", "tag_":"STABILITY", "id_":"17165544771317691984", "info_":""})~";
1068 auto sysEvent = std::make_shared<SysEvent>("SysEventSource", nullptr, jsonStr);
1069 sysEvent->SetLevel("MINOR");
1070 sysEvent->SetEventSeq(448); // 448: test seq
1071 EventStore::SysEventDao::Insert(sysEvent);
1072
1073 std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
1074 auto isProcessedFault1 = faultLogManager->IsProcessedFault(1854, 0, 2);
1075 ASSERT_EQ(isProcessedFault1, false);
1076
1077 faultLogManager->Init();
1078
1079 auto list = faultLogManager->GetFaultInfoList("FaultloggerUnittest", 0, 2, 10);
1080 ASSERT_GT(list.size(), 0);
1081
1082 auto isProcessedFault2 = faultLogManager->IsProcessedFault(1854, 0, 2);
1083 ASSERT_EQ(isProcessedFault2, true);
1084
1085 auto isProcessedFault3 = faultLogManager->IsProcessedFault(1855, 0, 2);
1086 ASSERT_EQ(isProcessedFault3, false);
1087
1088 auto isProcessedFault4 = faultLogManager->IsProcessedFault(1855, 5, 2);
1089 ASSERT_EQ(isProcessedFault4, false);
1090 }
1091
1092 /**
1093 * @tc.name: FaultLogManager::GetFaultLogFilePathTest001
1094 * @tc.desc: Test calling GetFaultLogFilePath Func
1095 * @tc.type: FUNC
1096 */
1097 HWTEST_F(FaultloggerUnittest, GetFaultLogFilePathTest001, testing::ext::TestSize.Level3)
1098 {
1099 std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
1100 faultLogManager->Init();
1101 std::string fileName = "com.freeze.test001-202506023.log";
1102
1103 std::string faultLogFilePath = faultLogManager->GetFaultLogFilePath(FaultLogType::APP_FREEZE, fileName);
1104 ASSERT_EQ(faultLogFilePath, "/data/log/faultlog/faultlogger/com.freeze.test001-202506023.log");
1105
1106 faultLogFilePath = faultLogManager->GetFaultLogFilePath(FaultLogType::SYS_WARNING, fileName);
1107 ASSERT_EQ(faultLogFilePath, "/data/log/warninglog/com.freeze.test001-202506023.log");
1108 }
1109
1110 /**
1111 * @tc.name: FaultLogManager::GetFaultLogFileFdTest001
1112 * @tc.desc: Test calling GetFaultLogFileFd Func
1113 * @tc.type: FUNC
1114 */
1115 HWTEST_F(FaultloggerUnittest, GetFaultLogFileFdTest001, testing::ext::TestSize.Level3)
1116 {
1117 std::unique_ptr<FaultLogManager> faultLogManager = std::make_unique<FaultLogManager>(nullptr);
1118 int faultLogFileFd = -1;
1119 faultLogManager->Init();
1120 std::string fileName = "com.freeze.test001-202506023.log";
1121
1122 faultLogFileFd = faultLogManager->GetFaultLogFileFd(FaultLogType::APP_FREEZE, fileName);
1123 ASSERT_TRUE(faultLogFileFd > 0);
1124 close(faultLogFileFd);
1125
1126 faultLogFileFd = faultLogManager->GetFaultLogFileFd(FaultLogType::SYS_WARNING, fileName);
1127 ASSERT_TRUE(faultLogFileFd > 0);
1128 close(faultLogFileFd);
1129 }
1130
1131 /**
1132 * @tc.name: FaultLogUtilTest001
1133 * @tc.desc: check ExtractInfoFromFileName Func
1134 * @tc.type: FUNC
1135 */
1136 HWTEST_F(FaultloggerUnittest, FaultLogUtilTest001, testing::ext::TestSize.Level3)
1137 {
1138 std::string filename = "appfreeze-com.ohos.systemui-10006-20170805172159";
1139 auto info = ExtractInfoFromFileName(filename);
1140 ASSERT_EQ(info.pid, 0);
1141 ASSERT_EQ(info.faultLogType, FaultLogType::APP_FREEZE); // 4 : APP_FREEZE
1142 ASSERT_EQ(info.module, "com.ohos.systemui");
1143 ASSERT_EQ(info.id, 10006); // 10006 : test uid
1144 }
1145
1146 /**
1147 * @tc.name: FaultLogUtilTest002
1148 * @tc.desc: check ExtractInfoFromTempFile Func
1149 * @tc.type: FUNC
1150 */
1151 HWTEST_F(FaultloggerUnittest, FaultLogUtilTest002, testing::ext::TestSize.Level3)
1152 {
1153 std::string filename = "appfreeze-10006-20170805172159";
1154 auto info = ExtractInfoFromTempFile(filename);
1155 ASSERT_EQ(info.faultLogType, FaultLogType::APP_FREEZE); // 4 : APP_FREEZE
1156 ASSERT_EQ(info.pid, 10006); // 10006 : test uid
1157
1158 std::string filename3 = "jscrash-10006-20170805172159";
1159 auto info3 = ExtractInfoFromTempFile(filename3);
1160 ASSERT_EQ(info3.faultLogType, FaultLogType::JS_CRASH); // 3 : JS_CRASH
1161 ASSERT_EQ(info3.pid, 10006); // 10006 : test uid
1162
1163 std::string filename4 = "cppcrash-10006-20170805172159";
1164 auto info4 = ExtractInfoFromTempFile(filename4);
1165 ASSERT_EQ(info4.faultLogType, FaultLogType::CPP_CRASH); // 2 : CPP_CRASH
1166 ASSERT_EQ(info4.pid, 10006); // 10006 : test uid
1167
1168 std::string filename5 = "all-10006-20170805172159";
1169 auto info5 = ExtractInfoFromTempFile(filename5);
1170 ASSERT_EQ(info5.faultLogType, FaultLogType::ALL); // 0 : ALL
1171 ASSERT_EQ(info5.pid, 10006); // 10006 : test uid
1172
1173 std::string filename6 = "other-10006-20170805172159";
1174 auto info6 = ExtractInfoFromTempFile(filename6);
1175 ASSERT_EQ(info6.faultLogType, -1); // -1 : other
1176 ASSERT_EQ(info6.pid, 10006); // 10006 : test uid
1177 }
1178
1179 /**
1180 * @tc.name: FaultLogUtilTest003
1181 * @tc.desc: check ExtractInfoFromFileName Func
1182 * @tc.type: FUNC
1183 */
1184 HWTEST_F(FaultloggerUnittest, FaultLogUtilTest003, testing::ext::TestSize.Level3)
1185 {
1186 std::string filename = "appfreeze";
1187 auto info = ExtractInfoFromFileName(filename);
1188 ASSERT_EQ(info.pid, 0);
1189 ASSERT_EQ(info.time, 0);
1190 }
1191
1192 /**
1193 * @tc.name: FaultLogUtilTest004
1194 * @tc.desc: test GetThreadStack
1195 * @tc.type: FUNC
1196 */
1197 HWTEST_F(FaultloggerUnittest, FaultLogUtilTest004, testing::ext::TestSize.Level3)
1198 {
1199 std::string path;
1200 auto stack = GetThreadStack(path, 0);
1201 ASSERT_TRUE(stack.empty());
1202
1203 path = "/data/log/faultlog/faultlogger/appfreeze-com.example.jsinject-20010039-19700326211815.tmp";
1204 const int thread1 = 3443;
1205 stack = GetThreadStack(path, thread1);
1206 ASSERT_FALSE(stack.empty());
1207
1208 const int thread2 = 3444;
1209 stack = GetThreadStack(path, thread2);
1210 ASSERT_FALSE(stack.empty());
1211 }
1212
1213 /**
1214 * @tc.name: FaultLogUtilTest005
1215 * @tc.desc: test GetFaultNameByType
1216 * @tc.type: FUNC
1217 */
1218 HWTEST_F(FaultloggerUnittest, FaultLogUtilTest005, testing::ext::TestSize.Level3)
1219 {
1220 ASSERT_EQ(GetFaultNameByType(FaultLogType::JS_CRASH, true), "jscrash");
1221 ASSERT_EQ(GetFaultNameByType(FaultLogType::JS_CRASH, false), "JS_ERROR");
1222
1223 ASSERT_EQ(GetFaultNameByType(FaultLogType::CPP_CRASH, true), "cppcrash");
1224 ASSERT_EQ(GetFaultNameByType(FaultLogType::CPP_CRASH, false), "CPP_CRASH");
1225
1226 ASSERT_EQ(GetFaultNameByType(FaultLogType::APP_FREEZE, true), "appfreeze");
1227 ASSERT_EQ(GetFaultNameByType(FaultLogType::APP_FREEZE, false), "APP_FREEZE");
1228
1229 ASSERT_EQ(GetFaultNameByType(FaultLogType::SYS_FREEZE, true), "sysfreeze");
1230 ASSERT_EQ(GetFaultNameByType(FaultLogType::SYS_FREEZE, false), "SYS_FREEZE");
1231
1232 ASSERT_EQ(GetFaultNameByType(FaultLogType::SYS_WARNING, true), "syswarning");
1233 ASSERT_EQ(GetFaultNameByType(FaultLogType::SYS_WARNING, false), "SYS_WARNING");
1234
1235 ASSERT_EQ(GetFaultNameByType(FaultLogType::RUST_PANIC, true), "rustpanic");
1236 ASSERT_EQ(GetFaultNameByType(FaultLogType::RUST_PANIC, false), "RUST_PANIC");
1237
1238 ASSERT_EQ(GetFaultNameByType(FaultLogType::ADDR_SANITIZER, true), "sanitizer");
1239 ASSERT_EQ(GetFaultNameByType(FaultLogType::ADDR_SANITIZER, false), "ADDR_SANITIZER");
1240
1241 ASSERT_EQ(GetFaultNameByType(FaultLogType::CJ_ERROR, true), "cjerror");
1242 ASSERT_EQ(GetFaultNameByType(FaultLogType::CJ_ERROR, false), "CJ_ERROR");
1243
1244 ASSERT_EQ(GetFaultNameByType(FaultLogType::ALL, true), "Unknown");
1245 ASSERT_EQ(GetFaultNameByType(FaultLogType::ALL, false), "Unknown");
1246 }
1247
1248 /**
1249 * @tc.name: FaultLogUtilTest006
1250 * @tc.desc: test GetLogTypeByName
1251 * @tc.type: FUNC
1252 */
1253 HWTEST_F(FaultloggerUnittest, FaultLogUtilTest006, testing::ext::TestSize.Level3)
1254 {
1255 ASSERT_EQ(GetLogTypeByName("jscrash"), FaultLogType::JS_CRASH);
1256 ASSERT_EQ(GetLogTypeByName("cppcrash"), FaultLogType::CPP_CRASH);
1257 ASSERT_EQ(GetLogTypeByName("appfreeze"), FaultLogType::APP_FREEZE);
1258 ASSERT_EQ(GetLogTypeByName("sysfreeze"), FaultLogType::SYS_FREEZE);
1259 ASSERT_EQ(GetLogTypeByName("syswarning"), FaultLogType::SYS_WARNING);
1260 ASSERT_EQ(GetLogTypeByName("sanitizer"), FaultLogType::ADDR_SANITIZER);
1261 ASSERT_EQ(GetLogTypeByName("cjerror"), FaultLogType::CJ_ERROR);
1262 ASSERT_EQ(GetLogTypeByName("all"), FaultLogType::ALL);
1263 ASSERT_EQ(GetLogTypeByName("ALL"), FaultLogType::ALL);
1264 ASSERT_EQ(GetLogTypeByName("Unknown"), -1);
1265 }
1266
1267 /**
1268 * @tc.name: FaultLogUtilTest007
1269 * @tc.desc: test GetDebugSignalTempLogName
1270 * @tc.type: FUNC
1271 */
1272 HWTEST_F(FaultloggerUnittest, FaultLogUtilTest007, testing::ext::TestSize.Level3)
1273 {
1274 FaultLogInfo info;
1275 info.pid = 123;
1276 info.time = 123456789;
1277 auto fileName = GetDebugSignalTempLogName(info);
1278 ASSERT_EQ(fileName, "/data/log/faultlog/temp/stacktrace-123-123456789");
1279 }
1280
1281 /**
1282 * @tc.name: FaultloggerAdapter.StartService
1283 * @tc.desc: Test calling FaultloggerAdapter.StartService Func
1284 * @tc.type: FUNC
1285 */
1286 HWTEST_F(FaultloggerUnittest, FaultloggerAdapterTest001, testing::ext::TestSize.Level3)
1287 {
1288 FaultloggerServiceOhos servicOhos;
1289 std::vector<std::u16string> args;
1290 args.emplace_back(u"-c _test.c");
1291 auto ret = servicOhos.Dump(0, args);
1292 ASSERT_EQ(ret, -1);
1293
1294 args.emplace_back(u",");
1295 servicOhos.Dump(0, args);
1296 ASSERT_EQ(ret, -1);
1297
1298 FaultLogInfoOhos info;
1299 // Cover GetOrSetFaultlogger return nullptr
1300 servicOhos.AddFaultLog(info);
1301
1302 const int32_t faultType = 2;
1303 const int32_t maxNum = 10;
1304 ASSERT_EQ(servicOhos.QuerySelfFaultLog(faultType, maxNum), nullptr);
1305 servicOhos.Destroy();
1306 }
1307
1308 /**
1309 * @tc.name: FaultloggerServiceOhos.StartService
1310 * @tc.desc: Test calling FaultloggerServiceOhos.StartService Func
1311 * @tc.type: FUNC
1312 */
1313 HWTEST_F(FaultloggerUnittest, FaultloggerServiceOhosTest001, testing::ext::TestSize.Level3)
1314 {
1315 auto plugin = GetFaultloggerInstance();
1316 auto faultManagerService = std::make_shared<FaultLogManagerService>(plugin->GetWorkLoop(),
1317 plugin->faultLogManager_);
1318 FaultloggerServiceOhos serviceOhos;
1319 FaultloggerServiceOhos::StartService(faultManagerService);
1320 ASSERT_EQ(FaultloggerServiceOhos::GetOrSetFaultlogger(nullptr), faultManagerService);
1321 FaultLogInfoOhos info;
1322 info.time = std::time(nullptr);
1323 info.pid = getpid();
1324 info.uid = 0;
1325 info.faultLogType = 2;
1326 int fds[2] = {-1, -1}; // 2: one read pipe, one write pipe
1327 ASSERT_EQ(pipe(fds), 0) << "create pipe failed";
1328 info.pipeFd = fds[0];
1329 info.module = "FaultloggerUnittest333";
1330 info.reason = "unittest for SaveFaultLogInfo";
1331 serviceOhos.AddFaultLog(info);
1332 close(fds[1]);
1333 auto list = serviceOhos.QuerySelfFaultLog(2, 10);
1334 ASSERT_NE(list, nullptr);
1335 info.time = std::time(nullptr);
1336 info.pid = getpid();
1337 info.uid = 10;
1338 info.faultLogType = 2;
1339 info.pipeFd = 0;
1340 info.module = "FaultloggerUnittest333";
1341 info.reason = "unittest for SaveFaultLogInfo";
1342 serviceOhos.AddFaultLog(info);
1343 list = serviceOhos.QuerySelfFaultLog(2, 10);
1344 ASSERT_EQ(list, nullptr);
1345 info.time = std::time(nullptr);
1346 info.pid = getpid();
1347 info.uid = 0;
1348 info.faultLogType = 2;
1349 info.module = "FaultloggerUnittest333";
1350 info.reason = "unittest for SaveFaultLogInfo";
1351 serviceOhos.AddFaultLog(info);
1352 list = serviceOhos.QuerySelfFaultLog(8, 10);
1353 ASSERT_EQ(list, nullptr);
1354 serviceOhos.EnableGwpAsanGrayscale(false, 1000, 2000, 5);
1355 serviceOhos.DisableGwpAsanGrayscale();
1356 ASSERT_TRUE(serviceOhos.GetGwpAsanGrayscaleState() >= 0);
1357 serviceOhos.Destroy();
1358 }
1359
1360 /**
1361 * @tc.name: FaultloggerServiceOhos.Dump
1362 * @tc.desc: Test calling FaultloggerServiceOhos.Dump Func
1363 * @tc.type: FUNC
1364 */
1365 HWTEST_F(FaultloggerUnittest, FaultloggerServiceOhosTest002, testing::ext::TestSize.Level3)
1366 {
1367 auto plugin = GetFaultloggerInstance();
1368 auto faultManagerService = std::make_shared<FaultLogManagerService>(plugin->GetWorkLoop(),
1369 plugin->faultLogManager_);
1370 FaultloggerServiceOhos serviceOhos;
1371 FaultloggerServiceOhos::StartService(faultManagerService);
1372 ASSERT_EQ(FaultloggerServiceOhos::GetOrSetFaultlogger(nullptr), faultManagerService);
1373 auto fd = TEMP_FAILURE_RETRY(open("/data/test/testFile2", O_CREAT | O_WRONLY | O_TRUNC, 770));
1374 bool isSuccess = fd >= 0;
1375 if (!isSuccess) {
1376 ASSERT_FALSE(isSuccess);
1377 printf("Fail to create test result file.\n");
1378 } else {
1379 std::vector<std::u16string>args;
1380 args.push_back(u"Faultlogger");
1381 args.push_back(u"-l");
1382 serviceOhos.Dump(fd, args);
1383 args.push_back(u"&@#");
1384 ASSERT_EQ(serviceOhos.Dump(fd, args), -1);
1385 close(fd);
1386 fd = -1;
1387 std::string result;
1388 if (FileUtil::LoadStringFromFile("/data/test/testFile2", result)) {
1389 ASSERT_GT(result.length(), 0uL);
1390 } else {
1391 FAIL();
1392 }
1393 serviceOhos.Destroy();
1394 }
1395 }
1396
1397 /**
1398 * @tc.name: FaultLogQueryResultOhosTest001
1399 * @tc.desc: test HasNext and GetNext
1400 * @tc.type: FUNC
1401 */
1402 HWTEST_F(FaultloggerUnittest, FaultLogQueryResultOhosTest001, testing::ext::TestSize.Level3)
1403 {
1404 auto plugin = GetFaultloggerInstance();
1405 auto faultManagerService = std::make_shared<FaultLogManagerService>(plugin->GetWorkLoop(),
1406 plugin->faultLogManager_);
1407 FaultloggerServiceOhos serviceOhos;
1408 FaultloggerServiceOhos::StartService(faultManagerService);
1409 bool isSuccess = FaultloggerServiceOhos::GetOrSetFaultlogger(nullptr) == faultManagerService;
1410 if (!isSuccess) {
1411 ASSERT_FALSE(isSuccess);
1412 printf("FaultloggerServiceOhos start service error.\n");
1413 } else {
1414 auto remoteObject = serviceOhos.QuerySelfFaultLog(FaultLogType::CPP_CRASH, 10); // 10 : maxNum
1415 auto result = iface_cast<FaultLogQueryResultOhos>(remoteObject);
1416 ASSERT_NE(result, nullptr);
1417 if (result != nullptr) {
1418 while (result->HasNext()) {
1419 result->GetNext();
1420 }
1421 }
1422 auto getNextRes = result->GetNext();
1423 ASSERT_NE(result, nullptr);
1424
1425 result->result_ = nullptr;
1426 bool hasNext = result->HasNext();
1427 ASSERT_FALSE(hasNext);
1428 getNextRes = result->GetNext();
1429 ASSERT_NE(result, nullptr);
1430 }
1431 }
1432
1433 class TestFaultLogQueryResultStub : public FaultLogQueryResultStub {
1434 public:
TestFaultLogQueryResultStub()1435 TestFaultLogQueryResultStub() {}
~TestFaultLogQueryResultStub()1436 virtual ~TestFaultLogQueryResultStub() {}
1437
HasNext()1438 bool HasNext()
1439 {
1440 return false;
1441 }
1442
GetNext()1443 sptr<FaultLogInfoOhos> GetNext()
1444 {
1445 return nullptr;
1446 }
1447
1448 public:
1449 enum Code {
1450 DEFAULT = -1,
1451 HASNEXT = 0,
1452 GETNEXT,
1453 };
1454 };
1455
1456 /**
1457 * @tc.name: FaultLogQueryResultStubTest001
1458 * @tc.desc: test OnRemoteRequest
1459 * @tc.type: FUNC
1460 */
1461 HWTEST_F(FaultloggerUnittest, FaultLogQueryResultStubTest001, testing::ext::TestSize.Level3)
1462 {
1463 TestFaultLogQueryResultStub faultLogQueryResultStub;
1464 MessageParcel data;
1465 MessageParcel reply;
1466 MessageOption option;
1467 int ret = faultLogQueryResultStub.OnRemoteRequest(TestFaultLogQueryResultStub::Code::HASNEXT, data, reply, option);
1468 ASSERT_EQ(ret, -1);
1469 data.WriteInterfaceToken(FaultLogQueryResultStub::GetDescriptor());
1470 ret = faultLogQueryResultStub.OnRemoteRequest(TestFaultLogQueryResultStub::Code::HASNEXT, data, reply, option);
1471 ASSERT_EQ(ret, 0);
1472 data.WriteInterfaceToken(FaultLogQueryResultStub::GetDescriptor());
1473 ret = faultLogQueryResultStub.OnRemoteRequest(TestFaultLogQueryResultStub::Code::GETNEXT, data, reply, option);
1474 ASSERT_EQ(ret, -1);
1475 data.WriteInterfaceToken(FaultLogQueryResultStub::GetDescriptor());
1476 ret = faultLogQueryResultStub.OnRemoteRequest(TestFaultLogQueryResultStub::Code::DEFAULT, data, reply, option);
1477 ASSERT_EQ(ret, 305); // 305 : method not exist
1478 }
1479
1480 class TestFaultLoggerServiceStub : public FaultLoggerServiceStub {
1481 public:
TestFaultLoggerServiceStub()1482 TestFaultLoggerServiceStub() {}
~TestFaultLoggerServiceStub()1483 virtual ~TestFaultLoggerServiceStub() {}
1484
AddFaultLog(const FaultLogInfoOhos & info)1485 void AddFaultLog(const FaultLogInfoOhos& info)
1486 {
1487 }
1488
QuerySelfFaultLog(int32_t faultType,int32_t maxNum)1489 sptr<IRemoteObject> QuerySelfFaultLog(int32_t faultType, int32_t maxNum)
1490 {
1491 return nullptr;
1492 }
1493
EnableGwpAsanGrayscale(bool alwaysEnabled,double sampleRate,double maxSimutaneousAllocations,int32_t duration)1494 bool EnableGwpAsanGrayscale(bool alwaysEnabled, double sampleRate,
1495 double maxSimutaneousAllocations, int32_t duration)
1496 {
1497 return false;
1498 }
1499
DisableGwpAsanGrayscale()1500 void DisableGwpAsanGrayscale()
1501 {
1502 }
1503
GetGwpAsanGrayscaleState()1504 uint32_t GetGwpAsanGrayscaleState()
1505 {
1506 return 0;
1507 }
1508
Destroy()1509 void Destroy()
1510 {
1511 }
1512
1513 public:
1514 enum Code {
1515 DEFAULT = -1,
1516 ADD_FAULTLOG = 0,
1517 QUERY_SELF_FAULTLOG,
1518 ENABLE_GWP_ASAN_GRAYSALE,
1519 DISABLE_GWP_ASAN_GRAYSALE,
1520 GET_GWP_ASAN_GRAYSALE,
1521 DESTROY,
1522 };
1523 };
1524
1525 /**
1526 * @tc.name: FaultLoggerServiceStubTest001
1527 * @tc.desc: test OnRemoteRequest
1528 * @tc.type: FUNC
1529 */
1530 HWTEST_F(FaultloggerUnittest, FaultLoggerServiceStubTest001, testing::ext::TestSize.Level3)
1531 {
1532 TestFaultLoggerServiceStub faultLoggerServiceStub;
1533 MessageParcel data;
1534 MessageParcel reply;
1535 MessageOption option;
1536 int ret = faultLoggerServiceStub.OnRemoteRequest(TestFaultLoggerServiceStub::Code::ADD_FAULTLOG,
1537 data, reply, option);
1538 ASSERT_EQ(ret, -1);
1539 data.WriteInterfaceToken(FaultLoggerServiceStub::GetDescriptor());
1540 ret = faultLoggerServiceStub.OnRemoteRequest(TestFaultLoggerServiceStub::Code::ADD_FAULTLOG,
1541 data, reply, option);
1542 ASSERT_EQ(ret, 3); // 3 : ERR_FLATTEN_OBJECT
1543 data.WriteInterfaceToken(FaultLoggerServiceStub::GetDescriptor());
1544 ret = faultLoggerServiceStub.OnRemoteRequest(TestFaultLoggerServiceStub::Code::QUERY_SELF_FAULTLOG,
1545 data, reply, option);
1546 ASSERT_EQ(ret, -1);
1547 data.WriteInterfaceToken(FaultLoggerServiceStub::GetDescriptor());
1548 ret = faultLoggerServiceStub.OnRemoteRequest(TestFaultLoggerServiceStub::Code::DESTROY,
1549 data, reply, option);
1550 ASSERT_EQ(ret, 0);
1551 data.WriteInterfaceToken(FaultLoggerServiceStub::GetDescriptor());
1552 ret = faultLoggerServiceStub.OnRemoteRequest(TestFaultLoggerServiceStub::Code::DEFAULT,
1553 data, reply, option);
1554 ASSERT_EQ(ret, 305); // 305 : method not exist
1555 }
1556
1557 /**
1558 * @tc.name: FaultloggerTest001
1559 * @tc.desc: Test calling Faultlogger.StartBootScan Func
1560 * @tc.type: FUNC
1561 */
1562 HWTEST_F(FaultloggerUnittest, FaultloggerTest001, testing::ext::TestSize.Level3)
1563 {
1564 StartHisyseventListen("RELIABILITY", "CPP_CRASH");
1565 time_t now = time(nullptr);
1566 std::vector<std::string> keyWords = { std::to_string(now) };
1567 faultEventListener->SetKeyWords(keyWords);
1568 std::string timeStr = GetFormatedTimeWithMillsec(now);
1569 std::string content = "Pid:101\nUid:0\nProcess name:BootScanUnittest\nReason:unittest for StartBootScan\n"
1570 "Fault thread info:\nTid:101, Name:BootScanUnittest\n#00 xxxxxxx\n#01 xxxxxxx\n";
1571 ASSERT_TRUE(FileUtil::SaveStringToFile("/data/log/faultlog/temp/cppcrash-101-" + std::to_string(now), content));
1572 auto plugin = GetFaultloggerInstance();
1573 FaultLogBootScan faultloggerListener(plugin->GetWorkLoop(), plugin->faultLogManager_);
1574 faultloggerListener.StartBootScan();
1575
1576 // check faultlog file content
1577 std::string fileName = "/data/log/faultlog/faultlogger/cppcrash-BootScanUnittest-0-" + timeStr + ".log";
1578 ASSERT_TRUE(FileUtil::FileExists(fileName));
1579 ASSERT_GT(FileUtil::GetFileSize(fileName), 0ul);
1580
1581 // check event database
1582 ASSERT_TRUE(faultEventListener->CheckKeyWords());
1583 }
1584
1585 /**
1586 * @tc.name: FaultloggerTest002
1587 * @tc.desc: Test calling Faultlogger.StartBootScan Func
1588 * @tc.type: FUNC
1589 */
1590 HWTEST_F(FaultloggerUnittest, FaultloggerTest002, testing::ext::TestSize.Level3)
1591 {
1592 StartHisyseventListen("RELIABILITY", "CPP_CRASH_NO_LOG");
1593 std::vector<std::string> keyWords = { "BootScanUnittest" };
1594 faultEventListener->SetKeyWords(keyWords);
1595 time_t now = time(nullptr);
1596 std::string content = "Pid:102\nUid:0\nProcess name:BootScanUnittest\nReason:unittest for StartBootScan\n"
1597 "Fault thread info:\nTid:102, Name:BootScanUnittest\n";
1598 std::string fileName = "/data/log/faultlog/temp/cppcrash-102-" + std::to_string(now);
1599 ASSERT_TRUE(FileUtil::SaveStringToFile(fileName, content));
1600 auto plugin = GetFaultloggerInstance();
1601 FaultLogBootScan faultloggerListener(plugin->GetWorkLoop(), plugin->faultLogManager_);
1602 faultloggerListener.StartBootScan();
1603 ASSERT_FALSE(FileUtil::FileExists(fileName));
1604
1605 // check event database
1606 ASSERT_TRUE(faultEventListener->CheckKeyWords());
1607 }
1608
1609 /**
1610 * @tc.name: FaultloggerTest003
1611 * @tc.desc: Test calling Faultlogger.StartBootScan Func, for full log
1612 * @tc.type: FUNC
1613 */
1614 HWTEST_F(FaultloggerUnittest, FaultloggerTest003, testing::ext::TestSize.Level3)
1615 {
1616 StartHisyseventListen("RELIABILITY", "CPP_CRASH");
1617 time_t now = time(nullptr);
1618 std::vector<std::string> keyWords = { std::to_string(now) };
1619 faultEventListener->SetKeyWords(keyWords);
1620 std::string timeStr = GetFormatedTimeWithMillsec(now);
1621 std::string regs = "r0:00000019 r1:0097cd3c\nr4:f787fd2c\nfp:f787fd18 ip:7fffffff pc:0097c982\n";
1622 std::string otherThreadInfo =
1623 "Tid:1336, Name:BootScanUnittes\n#00 xxxxxx\nTid:1337, Name:BootScanUnittes\n#00 xx\n";
1624 std::string content = std::string("Pid:111\nUid:0\nProcess name:BootScanUnittest\n") +
1625 "Reason:unittest for StartBootScan\n" +
1626 "Fault thread info:\nTid:111, Name:BootScanUnittest\n#00 xxxxxxx\n#01 xxxxxxx\n" +
1627 "Registers:\n" + regs +
1628 "Other thread info:\n" + otherThreadInfo +
1629 "Memory near registers:\nr1(/data/xxxxx):\n 0097cd34 47886849\n 0097cd38 96059d05\n\n" +
1630 "Maps:\n96e000-978000 r--p 00000000 /data/xxxxx\n978000-9a6000 r-xp 00009000 /data/xxxx\n";
1631 ASSERT_TRUE(FileUtil::SaveStringToFile("/data/log/faultlog/temp/cppcrash-111-" + std::to_string(now), content));
1632 auto plugin = GetFaultloggerInstance();
1633 FaultLogBootScan faultloggerListener(plugin->GetWorkLoop(), plugin->faultLogManager_);
1634 faultloggerListener.StartBootScan();
1635
1636 // check faultlog file content
1637 std::string fileName = "/data/log/faultlog/faultlogger/cppcrash-BootScanUnittest-0-" + timeStr + ".log";
1638 ASSERT_TRUE(FileUtil::FileExists(fileName));
1639 ASSERT_GT(FileUtil::GetFileSize(fileName), 0ul);
1640
1641 // check regs and otherThreadInfo is ok
1642 std::string logInfo;
1643 FileUtil::LoadStringFromFile(fileName, logInfo);
1644 ASSERT_TRUE(logInfo.find(regs) != std::string::npos);
1645 ASSERT_TRUE(logInfo.find(otherThreadInfo) != std::string::npos);
1646
1647 // check event database
1648 ASSERT_TRUE(faultEventListener->CheckKeyWords());
1649 }
1650
1651 /**
1652 * @tc.name: FaultloggerTest004
1653 * @tc.desc: Test calling Faultlogger.StartBootScan Func, for full cpp crash log limit
1654 * @tc.type: FUNC
1655 */
1656 HWTEST_F(FaultloggerUnittest, FaultloggerTest004, testing::ext::TestSize.Level3)
1657 {
1658 StartHisyseventListen("RELIABILITY", "CPP_CRASH");
1659 time_t now = time(nullptr);
1660 std::vector<std::string> keyWords = { std::to_string(now) };
1661 faultEventListener->SetKeyWords(keyWords);
1662 std::string timeStr = GetFormatedTimeWithMillsec(now);
1663 std::string fillMapsContent = "96e000-978000 r--p 00000000 /data/xxxxx\n978000-9a6000 r-xp 00009000 /data/xxxx\n";
1664 std::string regs = "r0:00000019 r1:0097cd3c\nr4:f787fd2c\nfp:f787fd18 ip:7fffffff pc:0097c982\n";
1665 std::string otherThreadInfo =
1666 "Tid:1336, Name:BootScanUnittes\n#00 xxxxxx\nTid:1337, Name:BootScanUnittes\n#00 xx\n";
1667 std::string content = std::string("Pid:111\nUid:0\nProcess name:BootScanUnittest\n") +
1668 "Reason:unittest for StartBootScan\n" +
1669 "Fault thread info:\nTid:111, Name:BootScanUnittest\n#00 xxxxxxx\n#01 xxxxxxx\n" +
1670 "Registers:\n" + regs +
1671 "Other thread info:\n" + otherThreadInfo +
1672 "Memory near registers:\nr1(/data/xxxxx):\n 0097cd34 47886849\n 0097cd38 96059d05\n\n" +
1673 "Maps:\n96e000-978000 r--p 00000000 /data/xxxxx\n978000-9a6000 r-xp 00009000 /data/xxxx\n";
1674 // let content more than 512k, trigger loglimit
1675 for (int i = 0; i < 10000; i++) {
1676 content += fillMapsContent;
1677 }
1678
1679 ASSERT_TRUE(FileUtil::SaveStringToFile("/data/log/faultlog/temp/cppcrash-114-" + std::to_string(now), content));
1680 auto plugin = GetFaultloggerInstance();
1681 FaultLogBootScan faultloggerListener(plugin->GetWorkLoop(), plugin->faultLogManager_);
1682 faultloggerListener.StartBootScan();
1683 // check faultlog file content
1684 std::string fileName = "/data/log/faultlog/faultlogger/cppcrash-BootScanUnittest-0-" + timeStr + ".log";
1685 ASSERT_TRUE(FileUtil::FileExists(fileName));
1686 ASSERT_GT(FileUtil::GetFileSize(fileName), 0ul);
1687 if (FaultLogger::IsFaultLogLimit()) {
1688 ASSERT_LT(FileUtil::GetFileSize(fileName), 514 * 1024ul);
1689 } else {
1690 ASSERT_GT(FileUtil::GetFileSize(fileName), 512 * 1024ul);
1691 }
1692 // check event database
1693 ASSERT_TRUE(faultEventListener->CheckKeyWords());
1694 }
1695
1696 /**
1697 * @tc.name: ReportJsErrorToAppEventTest001
1698 * @tc.desc: create JS ERROR event and send it to hiappevent
1699 * @tc.type: FUNC
1700 */
1701 HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest001, testing::ext::TestSize.Level3)
1702 {
1703 auto plugin = GetFaultloggerInstance();
1704 // has Error name、Error message、Error code、SourceCode、Stacktrace
1705 std::string summaryHasAll = R"~(Error name:summaryHasAll TypeError
1706 Error message:Obj is not a Valid object
1707 Error code:get BLO
1708 SourceCode:CKSSvalue() {new Error("TestError");}
1709 Stacktrace:
1710 at anonymous(entry/src/main/ets/pages/index.ets:76:10)
1711 at anonymous2(entry/src/main/ets/pages/index.ets:76:10)
1712 at anonymous3(entry/src/main/ets/pages/index.ets:76:10)
1713 )~";
1714 ConstructJsErrorAppEvent(summaryHasAll, plugin);
1715 CheckKeyWordsInJsErrorAppEventFile("summaryHasAll");
1716 }
1717
1718 /**
1719 * @tc.name: ReportJsErrorToAppEventTest002
1720 * @tc.desc: create JS ERROR event and send it to hiappevent
1721 * @tc.type: FUNC
1722 */
1723 HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest002, testing::ext::TestSize.Level3)
1724 {
1725 auto plugin = GetFaultloggerInstance();
1726 // has Error name、Error message、Error code、SourceCode、Stacktrace
1727 std::string summaryNotFindSourcemap = R"~(Error name:summaryNotFindSourcemap Error
1728 Error message:BussinessError 2501000: Operation failed.
1729 Error code:2501000
1730 Stacktrace:
1731 Cannot get SourceMap info, dump raw stack:
1732 at anonymous(entry/src/main/ets/pages/index.ets:76:10)
1733 at anonymous2(entry/src/main/ets/pages/index.ets:76:10)
1734 at anonymous3(entry/src/main/ets/pages/index.ets:76:10)
1735 )~";
1736 ConstructJsErrorAppEvent(summaryNotFindSourcemap, plugin);
1737 CheckDeleteStackErrorMessage("summaryNotFindSourcemap");
1738 CheckKeyWordsInJsErrorAppEventFile("summaryNotFindSourcemap");
1739 }
1740
1741 /**
1742 * @tc.name: ReportJsErrorToAppEventTest003
1743 * @tc.desc: create JS ERROR event and send it to hiappevent
1744 * @tc.type: FUNC
1745 */
1746 HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest003, testing::ext::TestSize.Level3)
1747 {
1748 auto plugin = GetFaultloggerInstance();
1749 // has Error name、Error message、SourceCode、Stacktrace
1750 std::string summaryHasNoErrorCode = R"~(Error name:summaryHasNoErrorCode TypeError
1751 Error message:Obj is not a Valid object
1752 SourceCode:CKSSvalue() {new Error("TestError");}
1753 Stacktrace:
1754 at anonymous(entry/src/main/ets/pages/index.ets:76:10)
1755 at anonymous2(entry/src/main/ets/pages/index.ets:76:10)
1756 at anonymous3(entry/src/main/ets/pages/index.ets:76:10)
1757 )~";
1758 ConstructJsErrorAppEvent(summaryHasNoErrorCode, plugin);
1759 CheckKeyWordsInJsErrorAppEventFile("summaryHasNoErrorCode");
1760 }
1761
1762 /**
1763 * @tc.name: ReportJsErrorToAppEventTest004
1764 * @tc.desc: create JS ERROR event and send it to hiappevent
1765 * @tc.type: FUNC
1766 */
1767 HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest004, testing::ext::TestSize.Level3)
1768 {
1769 auto plugin = GetFaultloggerInstance();
1770 // has Error name、Error message、Error code、Stacktrace
1771 std::string summaryHasNoSourceCode = R"~(Error name:summaryHasNoSourceCode TypeError
1772 Error message:Obj is not a Valid object
1773 Error code:get BLO
1774 Stacktrace:
1775 at anonymous(entry/src/main/ets/pages/index.ets:76:10)
1776 at anonymous2(entry/src/main/ets/pages/index.ets:76:10)
1777 at anonymous3(entry/src/main/ets/pages/index.ets:76:10)
1778 )~";
1779 ConstructJsErrorAppEvent(summaryHasNoSourceCode, plugin);
1780 CheckKeyWordsInJsErrorAppEventFile("summaryHasNoSourceCode");
1781 }
1782
1783 /**
1784 * @tc.name: ReportJsErrorToAppEventTest005
1785 * @tc.desc: create JS ERROR event and send it to hiappevent
1786 * @tc.type: FUNC
1787 */
1788 HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest005, testing::ext::TestSize.Level3)
1789 {
1790 auto plugin = GetFaultloggerInstance();
1791 // has Error name、Error message、Stacktrace
1792 std::string summaryHasNoErrorCodeAndSourceCode = R"~(Error name:summaryHasNoErrorCodeAndSourceCode TypeError
1793 Error message:Obj is not a Valid object
1794 Stacktrace:
1795 at anonymous(entry/src/main/ets/pages/index.ets:76:10)
1796 at anonymous2(entry/src/main/ets/pages/index.ets:76:10)
1797 at anonymous3(entry/src/main/ets/pages/index.ets:76:10)
1798 )~";
1799 ConstructJsErrorAppEvent(summaryHasNoErrorCodeAndSourceCode, plugin);
1800 CheckKeyWordsInJsErrorAppEventFile("summaryHasNoErrorCodeAndSourceCode");
1801 }
1802
1803 /**
1804 * @tc.name: ReportJsErrorToAppEventTest006
1805 * @tc.desc: create JS ERROR event and send it to hiappevent
1806 * @tc.type: FUNC
1807 */
1808 HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest006, testing::ext::TestSize.Level3)
1809 {
1810 auto plugin = GetFaultloggerInstance();
1811 // has Error name、Error message、Error code、SourceCode
1812 std::string summaryHasNoStacktrace = R"~(Error name:summaryHasNoStacktrace TypeError
1813 Error message:Obj is not a Valid object
1814 Error code:get BLO
1815 SourceCode:CKSSvalue() {new Error("TestError");}
1816 Stacktrace:
1817 )~";
1818 ConstructJsErrorAppEvent(summaryHasNoStacktrace, plugin);
1819 CheckKeyWordsInJsErrorAppEventFile("summaryHasNoStacktrace");
1820 }
1821
1822 /**
1823 * @tc.name: ReportJsErrorToAppEventTest007
1824 * @tc.desc: create JS ERROR event and send it to hiappevent
1825 * @tc.type: FUNC
1826 */
1827 HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest007, testing::ext::TestSize.Level3)
1828 {
1829 auto plugin = GetFaultloggerInstance();
1830 // has Error name、Error message
1831 std::string summaryHasErrorNameAndErrorMessage = R"~(Error name:summaryHasErrorNameAndErrorMessage TypeError
1832 Error message:Obj is not a Valid object
1833 Stacktrace:
1834 )~";
1835 ConstructJsErrorAppEvent(summaryHasErrorNameAndErrorMessage, plugin);
1836 CheckKeyWordsInJsErrorAppEventFile("summaryHasErrorNameAndErrorMessage");
1837 }
1838
1839 /**
1840 * @tc.name: ReportJsErrorToAppEventTest008
1841 * @tc.desc: create JS ERROR event and send it to hiappevent
1842 * @tc.type: FUNC
1843 */
1844 HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest008, testing::ext::TestSize.Level3)
1845 {
1846 auto plugin = GetFaultloggerInstance();
1847 // has Error name、Error message
1848 std::string noKeyValue = R"~(Error name:summaryHasErrorNameAndErrorMessage TypeError
1849 Error message:Obj is not a Valid object
1850 Stacktrace:
1851 )~";
1852 ConstructJsErrorAppEventWithNoValue(noKeyValue, plugin);
1853 CheckKeyWordsInJsErrorAppEventFile("noKeyValue");
1854 }
1855
1856 /**
1857 * @tc.name: ReportJsErrorToAppEventTest009
1858 * @tc.desc: create JS ERROR event and send it to hiappevent
1859 * @tc.type: FUNC
1860 */
1861 HWTEST_F(FaultloggerUnittest, ReportJsErrorToAppEventTest009, testing::ext::TestSize.Level3)
1862 {
1863 auto plugin = GetFaultloggerInstance();
1864 ConstructJsErrorAppEventWithNoValue("", plugin);
1865 std::string oldFileName = "/data/test_jsError_info";
1866 ASSERT_TRUE(FileUtil::FileExists(oldFileName));
1867 auto ret = remove("/data/test_jsError_info");
1868 if (ret != 0) {
1869 GTEST_LOG_(INFO) << "remove /data/test_jsError_info failed";
1870 }
1871 }
1872
1873 /**
1874 * @tc.name: ReportCjErrorToAppEventTest001
1875 * @tc.desc: create CJ ERROR event and send it to hiappevent
1876 * @tc.type: FUNC
1877 */
1878 HWTEST_F(FaultloggerUnittest, ReportCjErrorToAppEventTest001, testing::ext::TestSize.Level3)
1879 {
1880 auto plugin = GetFaultloggerInstance();
1881 // has Error name、Error message、Error code、SourceCode、Stacktrace
1882 std::string summary = R"~(Uncaught exception was found.
1883 Exception info: throwing foo exception
1884 Stacktrace:
1885 at anonymous(entry/src/main/ets/pages/index.cj:20)
1886 at anonymous2(entry/src/main/ets/pages/index.cj:33)
1887 at anonymous3(entry/src/main/ets/pages/index.cj:77)
1888 )~";
1889 ConstructCjErrorAppEvent(summary, plugin);
1890 CheckKeyWordsInCjErrorAppEventFile("summary");
1891 }
1892
SendSysEvent(SysEventCreator sysEventCreator)1893 bool SendSysEvent(SysEventCreator sysEventCreator)
1894 {
1895 auto plugin = GetFaultloggerInstance();
1896 auto sysEvent = std::make_shared<SysEvent>("test", nullptr, sysEventCreator);
1897 std::shared_ptr<Event> event = std::dynamic_pointer_cast<Event>(sysEvent);
1898 return plugin->OnEvent(event);
1899 }
1900
1901 /**
1902 * @tc.name: OnEventTest001
1903 * @tc.desc: create JS ERROR event and send it to hiappevent
1904 * @tc.type: FUNC
1905 */
1906 HWTEST_F(FaultloggerUnittest, OnEventTest001, testing::ext::TestSize.Level3)
1907 {
1908 {
1909 SysEventCreator sysEventCreator("AAFWK", "JSERROR", SysEventCreator::FAULT);
1910 sysEventCreator.SetKeyValue("name_", "JS_ERRORS");
1911 auto result = SendSysEvent(sysEventCreator);
1912 ASSERT_EQ(result, true);
1913 }
1914 {
1915 SysEventCreator sysEventCreator("AAFWK", "CPPCRASH", SysEventCreator::FAULT);
1916 sysEventCreator.SetKeyValue("name_", "RUST_PANIC");
1917 auto result = SendSysEvent(sysEventCreator);
1918 ASSERT_EQ(result, true);
1919 }
1920 }
1921
1922 /**
1923 * @tc.name: AppFreezeCrashLogTest001
1924 * @tc.desc: test AddFaultLog, check F1/F2/F3
1925 * @tc.type: FUNC
1926 */
1927 HWTEST_F(FaultloggerUnittest, AppFreezeCrashLogTest001, testing::ext::TestSize.Level3)
1928 {
1929 auto plugin = GetFaultloggerInstance();
1930 FaultLogManagerService faultManagerService(plugin->GetWorkLoop(), plugin->faultLogManager_);
1931 FaultLogInfo info;
1932 info.time = 1607161163;
1933 info.id = 20010039;
1934 info.pid = 7497;
1935 info.faultLogType = FaultLogType::APP_FREEZE;
1936 info.module = "com.example.jsinject";
1937 info.logPath = APPFREEZE_FAULT_FILE + "AppFreezeCrashLogTest001/" +
1938 "appfreeze-com.example.jsinject-20010039-19700326211815.tmp";
1939 faultManagerService.AddFaultLog(info);
1940
1941 const std::string firstFrame = "/system/lib64/libeventhandler.z.so"
1942 "(OHOS::AppExecFwk::NoneIoWaiter::WaitFor(std::__1::unique_lock<std::__1::mutex>&, long)+204";
1943 ASSERT_EQ(info.sectionMap["FIRST_FRAME"], firstFrame);
1944 const std::string secondFrame = "/system/lib64/libeventhandler.z.so"
1945 "(OHOS::AppExecFwk::EventQueue::WaitUntilLocked"
1946 "(std::__1::chrono::time_point<std::__1::chrono::steady_clock, "
1947 "std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000000000l> > > const&, "
1948 "std::__1::unique_lock<std::__1::mutex>&)+96";
1949 ASSERT_EQ(info.sectionMap["SECOND_FRAME"], secondFrame);
1950 }
1951
1952 /**
1953 * @tc.name: AppFreezeCrashLogTest002
1954 * @tc.desc: test AddFaultLog, add TERMINAL_THREAD_STACK, check F1/F2/F3
1955 * @tc.type: FUNC
1956 */
1957 HWTEST_F(FaultloggerUnittest, AppFreezeCrashLogTest002, testing::ext::TestSize.Level3)
1958 {
1959 auto plugin = GetFaultloggerInstance();
1960 FaultLogManagerService faultManagerService(plugin->GetWorkLoop(), plugin->faultLogManager_);
1961 FaultLogInfo info;
1962 info.time = 1607161163;
1963 info.id = 20010039;
1964 info.pid = 7497;
1965 info.faultLogType = FaultLogType::APP_FREEZE;
1966 info.module = "com.example.jsinject";
1967 info.logPath = APPFREEZE_FAULT_FILE + "AppFreezeCrashLogTest002/" +
1968 "appfreeze-com.example.jsinject-20010039-19700326211815.tmp";
1969 std::string binderSatck = "#00 pc 000000000006ca3c /system/lib64/libc.so(syscall+28)\n"
1970 "#01 pc 0000000000070cc4 "
1971 "/system/lib64/libc.so(__futex_wait_ex(void volatile*, bool, int, bool, timespec const*)+144)\n"
1972 "#02 pc 00000000000cf228 /system/lib64/libc.so(pthread_cond_wait+64)\n"
1973 "#03 pc 000000000051b55c /system/lib64/libGLES_mali.so\n"
1974 "#04 pc 00000000000cfce0 /system/lib64/libc.so(__pthread_start(void*)+40)\n"
1975 "#05 pc 0000000000072028 /system/lib64/libc.so(__start_thread+68)";
1976 info.sectionMap["TERMINAL_THREAD_STACK"] = binderSatck;
1977 faultManagerService.AddFaultLog(info);
1978 ASSERT_EQ(info.sectionMap["FIRST_FRAME"], "/system/lib64/libGLES_mali.so");
1979 ASSERT_TRUE(info.sectionMap["SECOND_FRAME"].empty());
1980 ASSERT_TRUE(info.sectionMap["LAST_FRAME"].empty());
1981 }
1982
1983 /**
1984 * @tc.name: AppFreezeCrashLogTest003
1985 * @tc.desc: test AddFaultLog, add TERMINAL_THREAD_STACK("\n"), check F1/F2/F3
1986 * @tc.type: FUNC
1987 */
1988 HWTEST_F(FaultloggerUnittest, AppFreezeCrashLogTest003, testing::ext::TestSize.Level3)
1989 {
1990 auto plugin = GetFaultloggerInstance();
1991 FaultLogManagerService faultManagerService(plugin->GetWorkLoop(), plugin->faultLogManager_);
1992 FaultLogInfo info;
1993 info.time = 1607161163;
1994 info.id = 20010039;
1995 info.pid = 7497;
1996 info.faultLogType = FaultLogType::APP_FREEZE;
1997 info.module = "com.example.jsinject";
1998 info.logPath = APPFREEZE_FAULT_FILE + "AppFreezeCrashLogTest003/" +
1999 "appfreeze-com.example.jsinject-20010039-19700326211815.tmp";
2000 std::string binderSatck = "#00 pc 000000000006ca3c /system/lib64/libc.so(syscall+28)\\n"
2001 "#01 pc 0000000000070cc4 "
2002 "/system/lib64/libc.so(__futex_wait_ex(void volatile*, bool, int, bool, timespec const*)+144)\\n"
2003 "#02 pc 00000000000cf228 /system/lib64/libc.so(pthread_cond_wait+64)\\n"
2004 "#03 pc 000000000051b55c /system/lib64/libGLES_mali.so\\n"
2005 "#04 pc 00000000000cfce0 /system/lib64/libc.so(__pthread_start(void*)+40)\\n"
2006 "#05 pc 0000000000072028 /system/lib64/libc.so(__start_thread+68)";
2007 info.sectionMap["TERMINAL_THREAD_STACK"] = binderSatck;
2008 faultManagerService.AddFaultLog(info);
2009 ASSERT_EQ(info.sectionMap["FIRST_FRAME"], "/system/lib64/libGLES_mali.so");
2010 ASSERT_TRUE(info.sectionMap["SECOND_FRAME"].empty());
2011 ASSERT_TRUE(info.sectionMap["LAST_FRAME"].empty());
2012 }
2013
2014 /**
2015 * @tc.name: FaultloggerUnittest001
2016 * @tc.desc: test IsValidPath
2017 * @tc.type: FUNC
2018 */
2019 HWTEST_F(FaultloggerUnittest, FaultloggerUnittest001, testing::ext::TestSize.Level3)
2020 {
2021 auto plugin = GetFaultloggerInstance();
2022 ASSERT_NE(plugin, nullptr);
2023 plugin->hasInit_ = true;
2024 FaultLogInfo info;
2025 info.time = 1607161163;
2026 info.id = 20010039;
2027 info.pid = 7497;
2028 info.faultLogType = FaultLogType::APP_FREEZE;
2029 info.module = "com.example.jsinject";
2030 info.logPath = "/proc/self/status";
2031 FaultLogManagerService faultManagerService(plugin->GetWorkLoop(), plugin->faultLogManager_);
2032 faultManagerService.AddFaultLog(info);
2033 ASSERT_TRUE(info.sectionMap.empty());
2034
2035 info.logPath = "/proc/self/test";
2036 faultManagerService.AddFaultLog(info);
2037 ASSERT_TRUE(info.sectionMap.empty());
2038 }
2039
2040 /**
2041 * @tc.name: FaultloggerUnittest002
2042 * @tc.desc: test QuerySelfFaultLog and GetMemoryStrByPid
2043 * @tc.type: FUNC
2044 */
2045 HWTEST_F(FaultloggerUnittest, FaultloggerUnittest002, testing::ext::TestSize.Level3)
2046 {
2047 FaultLogFreeze faultAppFreeze;
2048 std::string procStatm;
2049 std::string str = faultAppFreeze.GetMemoryStrByPid(-1, procStatm);
2050 ASSERT_EQ(str, "");
2051 str = faultAppFreeze.GetMemoryStrByPid(1, procStatm);
2052 ASSERT_NE(str, "");
2053 str = faultAppFreeze.GetMemoryStrByPid(getpid(), procStatm);
2054 ASSERT_NE(str, "");
2055 procStatm = "12 34 56 789 200";
2056 str = faultAppFreeze.GetMemoryStrByPid(getpid(), procStatm);
2057 ASSERT_NE(str, "");
2058 }
2059
2060 /**
2061 * @tc.name: FaultlogDatabaseUnittest001
2062 * @tc.desc: test RunSanitizerd
2063 * @tc.type: FUNC
2064 */
2065 HWTEST_F(FaultloggerUnittest, FaultlogDatabaseUnittest001, testing::ext::TestSize.Level3)
2066 {
2067 FaultLogDatabase *faultLogDb = new FaultLogDatabase(GetHiviewContext().GetSharedWorkLoop());
2068 std::list<FaultLogInfo> queryResult = faultLogDb->GetFaultInfoList("com.example.myapplication", 0, -1, 10);
2069 ASSERT_EQ(queryResult.size(), 0);
2070 queryResult = faultLogDb->GetFaultInfoList("com.example.myapplication", 0, 8, 10);
2071 ASSERT_EQ(queryResult.size(), 0);
2072 queryResult = faultLogDb->GetFaultInfoList("com.example.myapplication", 1, 2, 10);
2073 ASSERT_EQ(queryResult.size(), 0);
2074 queryResult = faultLogDb->GetFaultInfoList("com.example.myapplication", 1, 0, 10);
2075 ASSERT_EQ(queryResult.size(), 0);
2076
2077 FaultLogInfo info;
2078 info.faultLogType = FaultLogType::SYS_FREEZE;
2079 faultLogDb->eventLoop_ = nullptr;
2080 faultLogDb->SaveFaultLogInfo(info);
2081
2082 bool res = faultLogDb->IsFaultExist(1, 1, -1);
2083 ASSERT_FALSE(res);
2084 res = faultLogDb->IsFaultExist(1, 1, 8);
2085 ASSERT_FALSE(res);
2086 }
2087
2088 /**
2089 * @tc.name: FaultlogUtilUnittest001
2090 * @tc.desc: test RunSanitizerd
2091 * @tc.type: FUNC
2092 */
2093 HWTEST_F(FaultloggerUnittest, FaultlogUtilUnittest001, testing::ext::TestSize.Level3)
2094 {
2095 std::string result = GetFaultNameByType(FaultLogType::ADDR_SANITIZER, false);
2096 ASSERT_EQ(result, "ADDR_SANITIZER");
2097
2098 FaultLogInfo info;
2099 info.module = "test/test";
2100 info.faultLogType = FaultLogType::ADDR_SANITIZER;
2101 info.sanitizerType = "TSAN";
2102 std::string str = GetFaultLogName(info);
2103 ASSERT_EQ(str, "tsan-test-0-19700101080000000.log");
2104 info.sanitizerType = "UBSAN";
2105 str = GetFaultLogName(info);
2106 ASSERT_EQ(str, "ubsan-test-0-19700101080000000.log");
2107 info.sanitizerType = "GWP-ASAN";
2108 str = GetFaultLogName(info);
2109 ASSERT_EQ(str, "gwpasan-test-0-19700101080000000.log");
2110 info.sanitizerType = "HWASAN";
2111 str = GetFaultLogName(info);
2112 ASSERT_EQ(str, "hwasan-test-0-19700101080000000.log");
2113 info.sanitizerType = "ASAN";
2114 str = GetFaultLogName(info);
2115 ASSERT_EQ(str, "asan-test-0-19700101080000000.log");
2116 info.sanitizerType = "GWP-ASANS";
2117 str = GetFaultLogName(info);
2118 ASSERT_EQ(str, "sanitizer-test-0-19700101080000000.log");
2119
2120 str = RegulateModuleNameIfNeed("");
2121 ASSERT_EQ(str, "");
2122 }
2123
2124 /**
2125 * @tc.name: FaultlogUtilUnittest002
2126 * @tc.desc: test GetFaultNameByType
2127 * @tc.type: FUNC
2128 */
2129 HWTEST_F(FaultloggerUnittest, FaultlogUtilUnittest002, testing::ext::TestSize.Level3)
2130 {
2131 std::string result = GetFaultNameByType(FaultLogType::SYS_FREEZE, false);
2132 ASSERT_EQ(result, "SYS_FREEZE");
2133 result = GetFaultNameByType(FaultLogType::SYS_WARNING, false);
2134 ASSERT_EQ(result, "SYS_WARNING");
2135 result = GetFaultNameByType(FaultLogType::CJ_ERROR, false);
2136 ASSERT_EQ(result, "CJ_ERROR");
2137 }
2138
2139 /**
2140 * @tc.name: FaultloggerServiceOhosUnittest001
2141 * @tc.desc: test RunSanitizerd
2142 * @tc.type: FUNC
2143 */
2144 HWTEST_F(FaultloggerUnittest, FaultloggerServiceOhosUnittest001, testing::ext::TestSize.Level3)
2145 {
2146 FaultloggerServiceOhos faultloggerServiceOhos;
2147 std::vector<std::u16string> args;
2148 args.push_back(u"*m");
2149 int32_t result = faultloggerServiceOhos.Dump(1, args);
2150 ASSERT_EQ(result, -1);
2151 faultloggerServiceOhos.Destroy();
2152 }
2153
2154 /**
2155 * @tc.name: ReadHilogUnittest001
2156 * @tc.desc: Faultlogger::ReadHilog
2157 * @tc.type: FUNC
2158 */
2159 HWTEST_F(FaultloggerUnittest, ReadHilogUnittest001, testing::ext::TestSize.Level3)
2160 {
2161 /**
2162 * @tc.steps: step1. write log to hilog.
2163 */
2164 HIVIEW_LOGI("write log to hilog");
2165
2166 /**
2167 * @tc.steps: step2. Create a pipe.
2168 */
2169 int fds[2] = {-1, -1}; // 2: one read pipe, one write pipe
2170 int ret = pipe(fds);
2171 ASSERT_EQ(ret, 0) << "Failed to create pipe for get log.";
2172
2173 /**
2174 * @tc.steps: step3. ReadHilog.
2175 */
2176 int32_t pid = getpid();
2177 int childPid = fork();
2178 ASSERT_GE(childPid, 0);
2179 if (childPid == 0) {
2180 syscall(SYS_close, fds[0]);
2181
2182 int rc = DoGetHilogProcess(pid, fds[1]);
2183 syscall(SYS_close, fds[1]);
2184 _exit(rc);
2185 } else {
2186 syscall(SYS_close, fds[1]);
2187 // read log from fds[0]
2188 HIVIEW_LOGI("read hilog start");
2189 std::string log = ReadHilogTimeout(fds[0]);
2190 syscall(SYS_close, fds[0]);
2191 ASSERT_TRUE(!log.empty());
2192 }
2193 waitpid(childPid, nullptr, 0);
2194 }
2195
2196 /**
2197 * @tc.name: ReadHilogUnittest002
2198 * @tc.desc: Faultlogger::ReadHilog
2199 * @tc.type: FUNC
2200 */
2201 HWTEST_F(FaultloggerUnittest, ReadHilogUnittest002, testing::ext::TestSize.Level3)
2202 {
2203 /**
2204 * @tc.steps: step1. write log to hilog.
2205 */
2206 HIVIEW_LOGI("write log to hilog");
2207
2208 /**
2209 * @tc.steps: step2. Create a pipe.
2210 */
2211 int fds[2] = {-1, -1}; // 2: one read pipe, one write pipe
2212 int ret = pipe(fds);
2213 ASSERT_EQ(ret, 0) << "Failed to create pipe for get log.";
2214
2215 /**
2216 * @tc.steps: step3. ReadHilog.
2217 */
2218 int32_t pid = getpid();
2219 int childPid = fork();
2220 ASSERT_GE(childPid, 0);
2221 if (childPid == 0) {
2222 syscall(SYS_close, fds[0]);
2223 sleep(7); // Delay for 7 seconds, causing the read end to timeout and exit
2224
2225 int rc = DoGetHilogProcess(pid, fds[1]);
2226 syscall(SYS_close, fds[1]);
2227 _exit(rc);
2228 } else {
2229 syscall(SYS_close, fds[1]);
2230 // read log from fds[0]
2231 HIVIEW_LOGI("read hilog start");
2232 std::string log = ReadHilogTimeout(fds[0]);
2233 syscall(SYS_close, fds[0]);
2234 ASSERT_TRUE(log.empty());
2235 }
2236 waitpid(childPid, nullptr, 0);
2237 }
2238
2239 /**
2240 * @tc.name: ReadHilogUnittest003
2241 * @tc.desc: Faultlogger::ReadHilog
2242 * @tc.type: FUNC
2243 */
2244 HWTEST_F(FaultloggerUnittest, ReadHilogUnittest003, testing::ext::TestSize.Level3)
2245 {
2246 /**
2247 * @tc.steps: step1. write log to hilog.
2248 */
2249 HIVIEW_LOGI("write log to hilog");
2250
2251 /**
2252 * @tc.steps: step2. Create a pipe.
2253 */
2254 int fds[2] = {-1, -1}; // 2: one read pipe, one write pipe
2255 int ret = pipe(fds);
2256 ASSERT_EQ(ret, 0) << "Failed to create pipe for get log.";
2257
2258 /**
2259 * @tc.steps: step3. ReadHilog.
2260 */
2261 int32_t pid = getpid();
2262 int childPid = fork();
2263 ASSERT_GE(childPid, 0);
2264 if (childPid == 0) {
2265 syscall(SYS_close, fds[0]);
2266 syscall(SYS_close, fds[1]);
2267 _exit(0);
2268 } else {
2269 syscall(SYS_close, fds[1]);
2270 // read log from fds[0]
2271 HIVIEW_LOGI("read hilog start");
2272 std::string log = ReadHilogTimeout(fds[0]);
2273 syscall(SYS_close, fds[0]);
2274 ASSERT_TRUE(log.empty());
2275 }
2276 waitpid(childPid, nullptr, 0);
2277 }
2278
2279 /**
2280 * @tc.name: FaultlogLimit001
2281 * @tc.desc: Test calling DoFaultLogLimit Func
2282 * @tc.type: FUNC
2283 */
2284 HWTEST_F(FaultloggerUnittest, FaultlogLimit001, testing::ext::TestSize.Level3)
2285 {
2286 time_t now = time(nullptr);
2287 std::vector<std::string> keyWords = { std::to_string(now) };
2288 std::string timeStr = GetFormatedTimeWithMillsec(now);
2289 std::string fillMapsContent = "96e000-978000 r--p 00000000 /data/xxxxx\n978000-9a6000 r-xp 00009000 /data/xxxx\n";
2290 std::string regs = "r0:00000019 r1:0097cd3c\nr4:f787fd2c\nfp:f787fd18 ip:7fffffff pc:0097c982\n";
2291 std::string otherThreadInfo =
2292 "Tid:1336, Name:BootScanUnittes\n#00 xxxxxx\nTid:1337, Name:BootScanUnittes\n#00 xx\n";
2293 std::string content = std::string("Pid:111\nUid:0\nProcess name:BootScanUnittest\n") +
2294 "Reason:unittest for StartBootScan\n" +
2295 "Fault thread info:\nTid:111, Name:BootScanUnittest\n#00 xxxxxxx\n#01 xxxxxxx\n" +
2296 "Registers:\n" + regs +
2297 "Other thread info:\n" + otherThreadInfo +
2298 "Memory near registers:\nr1(/data/xxxxx):\n 0097cd34 47886849\n 0097cd38 96059d05\n\n" +
2299 "Maps:\n96e000-978000 r--p 00000000 /data/xxxxx\n978000-9a6000 r-xp 00009000 /data/xxxx\n";
2300 for (int i = 0; i < 100000; i++) {
2301 content += fillMapsContent;
2302 }
2303 content += "HiLog:\n";
2304 for (int i = 0; i < 10000; i++) {
2305 content += fillMapsContent;
2306 }
2307
2308 std::string filePath = "/data/log/faultlog/temp/cppcrash-114-" + std::to_string(now);
2309 ASSERT_TRUE(FileUtil::SaveStringToFile(filePath, content));
2310 FaultLogCppCrash faultCppCrash;
2311 faultCppCrash.DoFaultLogLimit(filePath, 1);
2312
2313 filePath = "/data/log/faultlog/temp/cppcrash-115-" + std::to_string(now);
2314 content = "hello";
2315 ASSERT_TRUE(FileUtil::SaveStringToFile(filePath, content));
2316 faultCppCrash.DoFaultLogLimit(filePath, 1);
2317
2318 FaultLogInfo info;
2319 std::string stack = "adad";
2320 faultCppCrash.FillStackInfo(info, stack);
2321
2322 std::string tempCont = "adbc";
2323 faultCppCrash.RemoveHiLogSection(tempCont);
2324 faultCppCrash.TruncateLogIfExceedsLimit(tempCont);
2325 }
2326
2327 /**
2328 * @tc.name: FaultLogManagerService001
2329 * @tc.desc: Test calling querySelfFaultLog Func
2330 * @tc.type: FUNC
2331 */
2332 HWTEST_F(FaultloggerUnittest, FaultLogManagerService001, testing::ext::TestSize.Level3)
2333 {
2334 auto plugin = GetFaultloggerInstance();
2335 FaultLogManagerService faultManagerService(plugin->GetWorkLoop(), plugin->faultLogManager_);
2336 faultManagerService.QuerySelfFaultLog(100001, 0, 10, 101);
2337 faultManagerService.QuerySelfFaultLog(100001, 0, 4, 101);
2338 auto ret = faultManagerService.QuerySelfFaultLog(100001, 0, -1, 101);
2339 ASSERT_TRUE(ret == nullptr);
2340 }
2341
2342 /**
2343 * @tc.name: FaultLogManagerService002
2344 * @tc.desc: Test calling GwpAsanGrayscal Func
2345 * @tc.type: FUNC
2346 */
2347 HWTEST_F(FaultloggerUnittest, FaultLogManagerService002, testing::ext::TestSize.Level3)
2348 {
2349 auto plugin = GetFaultloggerInstance();
2350 FaultLogManagerService faultManagerService(plugin->GetWorkLoop(), plugin->faultLogManager_);
2351 faultManagerService.EnableGwpAsanGrayscale(false, 1000, 2000, 5, static_cast<int64_t>(getuid()));
2352 faultManagerService.EnableGwpAsanGrayscale(true, 2523, 2000, 5, static_cast<int64_t>(getuid()));
2353 faultManagerService.DisableGwpAsanGrayscale(static_cast<int64_t>(getuid()));
2354 ASSERT_TRUE(faultManagerService.GetGwpAsanGrayscaleState(static_cast<int64_t>(getuid())) >= 0);
2355 }
2356
2357 /**
2358 * @tc.name: FaultloggerListener001
2359 * @tc.desc: Test calling FaultloggerListener Func
2360 * @tc.type: FUNC
2361 */
2362 HWTEST_F(FaultloggerUnittest, FaultloggerListener001, testing::ext::TestSize.Level3)
2363 {
2364 auto plugin = GetFaultloggerInstance();
2365 FaultLogBootScan faultloggerListener(plugin->GetWorkLoop(), plugin->faultLogManager_);
2366 std::string fileName = "/data/log/faultlog/temp/freeze-114-";
2367
2368 bool ret = faultloggerListener.IsCrashType(fileName);
2369 ASSERT_EQ(ret, false);
2370
2371 time_t now = time(nullptr);
2372 faultloggerListener.IsInValidTime(fileName, now);
2373 ASSERT_TRUE(faultloggerListener.IsInValidTime(fileName, 0));
2374
2375 FaultLogBootScan faultloggerListenerEmpty(nullptr, plugin->faultLogManager_);
2376 faultloggerListenerEmpty.AddBootScanEvent();
2377
2378 Event msg("hello");
2379 faultloggerListenerEmpty.OnUnorderedEvent(msg);
2380 }
2381
2382 /**
2383 * @tc.name: FaultLogCjError001
2384 * @tc.desc: Test cj reportToAppEvent Func
2385 * @tc.type: FUNC
2386 */
2387 HWTEST_F(FaultloggerUnittest, FaultLogCjError001, testing::ext::TestSize.Level3)
2388 {
2389 FaultLogCjError cjError;
2390 FaultLogInfo info;
2391 info.reportToAppEvent = false;
2392 bool ret = cjError.ReportToAppEvent(nullptr, info);
2393 EXPECT_EQ(ret, false);
2394 }
2395
CheckProcessName(const std::string & dirName,const std::string & procName)2396 bool CheckProcessName(const std::string &dirName, const std::string &procName)
2397 {
2398 std::string path = "/proc/" + dirName + "/comm";
2399 std::ifstream file(path);
2400 if (!file.is_open()) {
2401 return false;
2402 }
2403
2404 std::string comm;
2405 std::getline(file, comm);
2406 file.close();
2407
2408 return comm == procName;
2409 }
2410
GetPidByProcessName(const std::string & procName)2411 pid_t GetPidByProcessName(const std::string &procName)
2412 {
2413 DIR *procDir = opendir("/proc");
2414 if (procDir == nullptr) {
2415 perror("opendir /proc");
2416 return -1;
2417 }
2418
2419 pid_t pid = -1;
2420 struct dirent *entry;
2421 while ((entry = readdir(procDir)) != nullptr) {
2422 if (entry->d_type != DT_DIR) {
2423 continue;
2424 }
2425
2426 std::string dirName(entry->d_name);
2427 if (!std::all_of(dirName.begin(), dirName.end(), ::isdigit)) {
2428 continue;
2429 }
2430
2431 if (CheckProcessName(dirName, procName)) {
2432 pid = std::stoi(dirName);
2433 break;
2434 }
2435 }
2436
2437 closedir(procDir);
2438 return pid;
2439 }
2440
2441 /**
2442 * @tc.name: FaultLogAppFreeze001
2443 * @tc.desc: Test faultAppFreeze GetFreezeHilogByPid Func
2444 * @tc.type: FUNC
2445 */
2446 HWTEST_F(FaultloggerUnittest, FaultLogAppFreeze001, testing::ext::TestSize.Level3)
2447 {
2448 FaultLogFreeze faultAppFreeze;
2449 faultAppFreeze.GetFreezeHilogByPid(1);
2450 std::string processName = "faultloggerd";
2451 auto pid = GetPidByProcessName(processName);
2452 auto hilog = faultAppFreeze.GetFreezeHilogByPid(pid);
2453 ASSERT_TRUE(!hilog.empty());
2454 }
2455 /**
2456 * @tc.name: FaultLogAppFreeze002
2457 * @tc.desc: Test faultAppFreeze ReportEventToAppEvent Func
2458 * @tc.type: FUNC
2459 */
2460 HWTEST_F(FaultloggerUnittest, FaultLogAppFreeze002, testing::ext::TestSize.Level3)
2461 {
2462 FaultLogFreeze faultAppFreeze;
2463 FaultLogInfo info;
2464 info.reportToAppEvent = false;
2465 bool ret = faultAppFreeze.ReportEventToAppEvent(info);
2466
2467 std::string logPath = "1111.txt";
2468 faultAppFreeze.DoFaultLogLimit(logPath, 2);
2469
2470 ASSERT_FALSE(ret);
2471 }
2472
2473 /**
2474 * @tc.name: FaultLogJsError001
2475 * @tc.desc: Test jsError ReportToAppEvent Func
2476 * @tc.type: FUNC
2477 */
2478 HWTEST_F(FaultloggerUnittest, FaultLogJsError001, testing::ext::TestSize.Level3)
2479 {
2480 FaultLogJsError jserror;
2481
2482 FaultLogInfo info;
2483 info.reportToAppEvent = false;
2484 bool ret = jserror.ReportToAppEvent(nullptr, info);
2485 EXPECT_EQ(ret, false);
2486 }
2487
2488 /**
2489 * @tc.name: FaultLogSanitizer001
2490 * @tc.desc: Test cjError ReportToAppEvent Func
2491 * @tc.type: FUNC
2492 */
2493 HWTEST_F(FaultloggerUnittest, FaultLogSanitizer001, testing::ext::TestSize.Level3)
2494 {
2495 std::string summmay = "adaf";
2496 SysEventCreator sysEventCreator("CJ_RUNTIME", "CJERROR", SysEventCreator::FAULT);
2497 sysEventCreator.SetKeyValue("SUMMARY", summmay);
2498 sysEventCreator.SetKeyValue("name_", "CJ_ERROR");
2499 sysEventCreator.SetKeyValue("happenTime_", 1670248360359); // 1670248360359 : Simulate happenTime_ value
2500 sysEventCreator.SetKeyValue("REASON", "std.core:Exception");
2501 sysEventCreator.SetKeyValue("tz_", "+0800");
2502 sysEventCreator.SetKeyValue("pid_", 2413); // 2413 : Simulate pid_ value
2503 sysEventCreator.SetKeyValue("tid_", 2413); // 2413 : Simulate tid_ value
2504 sysEventCreator.SetKeyValue("what_", 3); // 3 : Simulate what_ value
2505 sysEventCreator.SetKeyValue("PACKAGE_NAME", "com.ohos.systemui");
2506 sysEventCreator.SetKeyValue("VERSION", "1.0.0");
2507 sysEventCreator.SetKeyValue("TYPE", 3); // 3 : Simulate TYPE value
2508 sysEventCreator.SetKeyValue("VERSION", "1.0.0");
2509
2510 auto sysEvent = std::make_shared<SysEvent>("test", nullptr, sysEventCreator);
2511 FaultLogSanitizer san;
2512 FaultLogInfo info;
2513 info.reportToAppEvent = false;
2514 bool ret = san.ReportToAppEvent(sysEvent, info);
2515 EXPECT_EQ(ret, false);
2516
2517 sysEventCreator.SetKeyValue("LOG_PATH", "1.0.0");
2518 sysEvent = std::make_shared<SysEvent>("test", nullptr, sysEventCreator);
2519 info.reportToAppEvent = true;
2520 ret = san.ReportToAppEvent(sysEvent, info);
2521 EXPECT_EQ(ret, true);
2522 }
2523
2524 /**
2525 * @tc.name: FaultLogSanitizer002
2526 * @tc.desc: Test ParseSanitizerEasyEvent Func
2527 * @tc.type: FUNC
2528 */
2529 HWTEST_F(FaultloggerUnittest, FaultLogSanitizer002, testing::ext::TestSize.Level3)
2530 {
2531 FaultLogSanitizer sanitizer;
2532 auto runTest = [&sanitizer](const std::string& input,
__anonc0da2f8b0302(const std::string& input, const std::unordered_map<std::string, std::string>& expected) 2533 const std::unordered_map<std::string, std::string>& expected) {
2534 SysEventCreator sysEventCreator("RELIABILITY", "ADDR_SANITIZER", SysEventCreator::FAULT);
2535 sysEventCreator.SetKeyValue("DATA", input);
2536
2537 auto sysEvent = std::make_shared<SysEvent>("test", nullptr, sysEventCreator);
2538 sanitizer.ParseSanitizerEasyEvent(*sysEvent);
2539
2540 for (const auto& [key, val] : expected) {
2541 EXPECT_EQ(sysEvent->GetEventValue(key), val);
2542 }
2543 };
2544 runTest("FAULT_TYPE:8;MODULE:debugsanitizer;SUMMARY:debug text with ; and :",
2545 {{"FAULT_TYPE", "8"},
2546 {"MODULE", "debugsanitizer"},
2547 {"SUMMARY", "debug text with ; and :"}});
2548 runTest("FAULT_TYPE;MODULE:debugsanitizer:2;SUMMARY:debug text with ; and :",
2549 {{"FAULT_TYPE", ""},
2550 {"MODULE", "debugsanitizer:2"},
2551 {"SUMMARY", "debug text with ; and :"}});
2552 runTest("SUMMARY:only summary",
2553 {{"SUMMARY", "only summary"}});
2554 runTest("FAULT_TYPE:;SUMMARY:only summary",
2555 {{"FAULT_TYPE", ""},
2556 {"SUMMARY", "only summary"}});
2557 }
2558
2559 /**
2560 * @tc.name: EventHandlerStrategyFactory001
2561 * @tc.desc: Test CreateFaultLogEvent Func
2562 * @tc.type: FUNC
2563 */
2564 HWTEST_F(FaultloggerUnittest, EventHandlerStrategyFactory001, testing::ext::TestSize.Level3)
2565 {
2566 FaultLogEventFactory factory;
2567 std::string eventName = "ADDR_SANITIZER";
2568 auto fault = factory.CreateFaultLogEvent(eventName);
2569 ASSERT_NE(fault, nullptr);
2570 fault = factory.CreateFaultLogEvent("abcd");
2571 ASSERT_EQ(fault, nullptr);
2572 }
2573
2574 /**
2575 * @tc.name: GetFaultloggerInstance001
2576 * @tc.desc: Test onEvent and IsInterestedPipelineEvent
2577 * @tc.type: FUNC
2578 */
2579 HWTEST_F(FaultloggerUnittest, GetFaultloggerInstance001, testing::ext::TestSize.Level3)
2580 {
2581 auto plugin = GetFaultloggerInstance();
2582 std::shared_ptr<Event> event = nullptr;
2583 bool ret = plugin->OnEvent(event);
2584 ASSERT_EQ(ret, false);
2585 ret = plugin->IsInterestedPipelineEvent(event);
2586 ASSERT_EQ(ret, false);
2587 }
2588
2589 /**
2590 * @tc.name: ExtractSubMoudleName001
2591 * @tc.desc: Test ExtractSubMoudleName func
2592 * @tc.type: FUNC
2593 */
2594 HWTEST_F(FaultloggerUnittest, ExtractSubMoudleName001, testing::ext::TestSize.Level3)
2595 {
2596 std::string moduleName = "com.ohos.sceneboard:";
2597 ASSERT_FALSE(ExtractSubMoudleName(moduleName));
2598 std::string endName = "";
2599 ASSERT_EQ(endName, moduleName);
2600 }
2601
2602 /**
2603 * @tc.name: ExtractSubMoudleName002
2604 * @tc.desc: Test ExtractSubMoudleName func
2605 * @tc.type: FUNC
2606 */
2607 HWTEST_F(FaultloggerUnittest, ExtractSubMoudleName002, testing::ext::TestSize.Level3)
2608 {
2609 std::string moduleName = "com.ohos.sceneboard:123ExtractSubMoudleName/123ExtractSubMoudleName_321";
2610 ASSERT_TRUE(ExtractSubMoudleName(moduleName));
2611 std::string endName = "ExtractSubMoudleName_123ExtractSubMoudleName";
2612 ASSERT_EQ(endName, moduleName);
2613 }
2614
2615 /**
2616 * @tc.name: ExtractSubMoudleName003
2617 * @tc.desc: Test ExtractSubMoudleName func
2618 * @tc.type: FUNC
2619 */
2620 HWTEST_F(FaultloggerUnittest, ExtractSubMoudleName003, testing::ext::TestSize.Level3)
2621 {
2622 std::string moduleName = "com.ohos.test";
2623 ASSERT_FALSE(ExtractSubMoudleName(moduleName));
2624 std::string moduleName2 = "com.ohos.sceneboard:test:1";
2625 ASSERT_TRUE(ExtractSubMoudleName(moduleName2));
2626 std::string endName = "test";
2627 ASSERT_EQ(endName, moduleName2);
2628 }
2629
2630 /**
2631 * @tc.name: FaultLogBootScan001
2632 * @tc.desc: Test big file
2633 * @tc.type: FUNC
2634 */
2635 HWTEST_F(FaultloggerUnittest, FaultLogBootScan001, testing::ext::TestSize.Level3)
2636 {
2637 std::string path = "/data/test/test_data/FaultLogBootScan001/cppcrash-197-1502809621426";
2638 ASSERT_FALSE(FaultLogBootScan::IsCrashTempBigFile(path));
2639 }
2640
2641 /**
2642 * @tc.name: FaultLogBootScan002
2643 * @tc.desc: Test big file, file size exceeds limit
2644 * @tc.type: FUNC
2645 */
2646 HWTEST_F(FaultloggerUnittest, FaultLogBootScan002, testing::ext::TestSize.Level3)
2647 {
2648 std::string path = "/data/test/test_data/FaultLogBootScan002/cppcrash-197-1502809621426";
2649 std::ofstream file(path, std::ios::app);
2650 ASSERT_TRUE(file.is_open());
2651 file << std::setfill('0') << std::setw(1024 * 1024 * 5) << 0;
2652 file.close();
2653
2654 ASSERT_TRUE(FaultLogBootScan::IsCrashTempBigFile(path));
2655 }
2656
2657 /**
2658 * @tc.name: GetFormatedTimeHHMMSS001
2659 * @tc.desc: Test format time string
2660 * @tc.type: FUNC
2661 */
2662 HWTEST_F(FaultloggerUnittest, GetFormatedTimeHHMMSS001, testing::ext::TestSize.Level3)
2663 {
2664 uint64_t ts = 1755067031234;
2665 auto timeStr = GetFormatedTimeHHMMSS(ts, true);
2666 std::string msStr = "14:37:11.234";
2667 ASSERT_EQ(timeStr, msStr);
2668 }
2669
2670 /**
2671 * @tc.name: GetFormatedTimeHHMMSS002
2672 * @tc.desc: Test format time string
2673 * @tc.type: FUNC
2674 */
2675 HWTEST_F(FaultloggerUnittest, GetFormatedTimeHHMMSS002, testing::ext::TestSize.Level3)
2676 {
2677 uint64_t ts = 1755067031;
2678 auto timeStr = GetFormatedTimeHHMMSS(ts, false);
2679 std::string msStr = "14:37:11";
2680 ASSERT_EQ(timeStr, msStr);
2681 }
2682
2683 /**
2684 * @tc.name: GetFormatedTimeHHMMSS003
2685 * @tc.desc: Test format time string
2686 * @tc.type: FUNC
2687 */
2688 HWTEST_F(FaultloggerUnittest, GetFormatedTimeHHMMSS003, testing::ext::TestSize.Level3)
2689 {
2690 uint64_t ts = 1755067031004;
2691 auto timeStr = GetFormatedTimeHHMMSS(ts, true);
2692 std::string msStr = "14:37:11.004";
2693 ASSERT_EQ(timeStr, msStr);
2694 }
2695
2696 /**
2697 * @tc.name: PageTraceNode001
2698 * @tc.desc: Test PageTraceNode ToString
2699 * @tc.type: FUNC
2700 */
2701 HWTEST_F(FaultloggerUnittest, PageTraceNode001, testing::ext::TestSize.Level3)
2702 {
2703 PageTraceNode node1(123, 1755067031234, "/test/pageUrl", "testName");
2704 std::string timeStr1 = "14:37:11.234 /test/pageUrl:testName";
2705 ASSERT_EQ(node1.ToString(), timeStr1);
2706
2707 PageTraceNode node2(123, 1755067031234, "/test/pageUrl", "");
2708 std::string timeStr2 = "14:37:11.234 /test/pageUrl";
2709 ASSERT_EQ(node2.ToString(), timeStr2);
2710
2711 PageTraceNode node3(123, 1755067031234, "", "testName");
2712 std::string timeStr3 = "14:37:11.234 :testName";
2713 ASSERT_EQ(node3.ToString(), timeStr3);
2714 }
2715
2716 /**
2717 * @tc.name: PageTrace001
2718 * @tc.desc: Test PageTrace
2719 * @tc.type: FUNC
2720 */
2721 HWTEST_F(FaultloggerUnittest, PageTrace001, testing::ext::TestSize.Level3)
2722 {
2723 PagesTrace pageTrace;
2724 pageTrace.AddPageTrace(PageTraceNode(123, 1755067031234, "/test/pageUrl", "testName"));
2725 ASSERT_EQ(pageTrace.pages_.size(), 1);
2726 ASSERT_TRUE(pageTrace.ToString(1).empty());
2727 ASSERT_FALSE(pageTrace.ToString(123).empty());
2728 std::string timeStr = " 14:37:11.234 /test/pageUrl:testName\n";
2729 ASSERT_EQ(pageTrace.ToString(123), timeStr);
2730
2731 pageTrace.AddPageTrace(PageTraceNode(124, 1755067031234, "/test/pageUrl", "testName"));
2732 ASSERT_EQ(pageTrace.pages_.size(), 2);
2733 ASSERT_TRUE(pageTrace.ToString(1).empty());
2734 ASSERT_FALSE(pageTrace.ToString(123).empty());
2735 ASSERT_EQ(pageTrace.ToString(123), timeStr);
2736
2737 pageTrace.AddPageTrace(PageTraceNode(123, 1755067031234, "", "enters foreground"));
2738 ASSERT_EQ(pageTrace.pages_.size(), 3);
2739 ASSERT_TRUE(pageTrace.ToString(1).empty());
2740 ASSERT_FALSE(pageTrace.ToString(123).empty());
2741 timeStr = " 14:37:11.234 :enters foreground\n" + timeStr;
2742 ASSERT_EQ(pageTrace.ToString(123), timeStr);
2743
2744 pageTrace.AddPageTrace(PageTraceNode(123, 1755067031234, "", "leaves foreground"));
2745 ASSERT_EQ(pageTrace.pages_.size(), 4);
2746 ASSERT_TRUE(pageTrace.ToString(1).empty());
2747 ASSERT_FALSE(pageTrace.ToString(123).empty());
2748 timeStr = " 14:37:11.234 :leaves foreground\n" + timeStr;
2749 ASSERT_EQ(pageTrace.ToString(123), timeStr);
2750
2751 for (size_t i = 0; i < pageTrace.MAX_PAGES_NUM; i++) {
2752 pageTrace.AddPageTrace(PageTraceNode(124, 1755067031234, "/test/pageUrl", "testName"));
2753 }
2754 ASSERT_EQ(pageTrace.pages_.size(), pageTrace.MAX_PAGES_NUM);
2755 ASSERT_TRUE(pageTrace.ToString(1).empty());
2756 }
2757
2758 /**
2759 * @tc.name: PageHistoryManager001
2760 * @tc.desc: Test PageHistoryManager
2761 * @tc.type: FUNC
2762 */
2763 HWTEST_F(FaultloggerUnittest, PageHistoryManager001, testing::ext::TestSize.Level3)
2764 {
2765 auto& manager = PageHistoryManager::GetInstance();
2766 SysEventCreator sysEventCreator("AAFWK", "ABILITY_ONFOREGROUND", SysEventCreator::FAULT);
2767 sysEventCreator.SetKeyValue("BUNDLE_NAME", "process_1");
2768 sysEventCreator.SetKeyValue("name_", "ABILITY_ONFOREGROUND");
2769
2770 auto sysEvent = std::make_shared<SysEvent>("test", nullptr, sysEventCreator);
2771 sysEvent->pid_ = 1234;
2772 sysEvent->happenTime_ = 1755067031234;
2773 manager.HandleEvent(*sysEvent);
2774
2775 ASSERT_TRUE(manager.GetPageHistory("process_1", 1).empty());
2776 ASSERT_FALSE(manager.GetPageHistory("process_1", 1234).empty());
2777 std::string timeStr = " 14:37:11.234 :enters foreground\n";
2778 ASSERT_EQ(manager.GetPageHistory("process_1", 1234), timeStr);
2779
2780 sysEvent->eventName_ = "INTERACTION_COMPLETED_LATENCY";
2781 sysEvent->SetEventValue("SCENE_ID", "ABILITY_OR_PAGE_SWITCH");
2782 sysEvent->SetEventValue("PAGE_URL", "/test/testPageUrl");
2783 sysEvent->SetEventValue("PAGE_NAME", "testPageName");
2784 manager.HandleEvent(*sysEvent);
2785 ASSERT_TRUE(manager.GetPageHistory("process_1", 1).empty());
2786 ASSERT_FALSE(manager.GetPageHistory("process_1", 1234).empty());
2787 timeStr = " 14:37:11.234 /test/testPageUrl:testPageName\n" + timeStr;
2788 ASSERT_EQ(manager.GetPageHistory("process_1", 1234), timeStr);
2789
2790 sysEvent->eventName_ = "ABILITY_ONBACKGROUND";
2791 manager.HandleEvent(*sysEvent);
2792 ASSERT_TRUE(manager.GetPageHistory("process_1", 1).empty());
2793 ASSERT_FALSE(manager.GetPageHistory("process_1", 1234).empty());
2794 timeStr = " 14:37:11.234 :leaves foreground\n" + timeStr;
2795 ASSERT_EQ(manager.GetPageHistory("process_1", 1234), timeStr);
2796
2797 for (size_t i = 1; i <= manager.recorder_.MAX_RECORDED_PROCESS_NUM; i++) {
2798 std::string process = "test_process_" + std::to_string(i);
2799 sysEvent->SetEventValue("BUNDLE_NAME", process);
2800 manager.HandleEvent(*sysEvent);
2801 }
2802 ASSERT_EQ(manager.recorder_.MAX_RECORDED_PROCESS_NUM, manager.recorder_.pagesList_.size());
2803 ASSERT_EQ(manager.recorder_.MAX_RECORDED_PROCESS_NUM, manager.recorder_.lruCache_.size());
2804 }
2805 } // namespace HiviewDFX
2806 } // namespace OHOS
2807