1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15#ifndef FAULTLOGGERD_CRASH_VALIDATOR_H
16#define FAULTLOGGERD_CRASH_VALIDATOR_H
17#ifdef HISYSEVENT_ENABLE
18#include <memory>
19#include <mutex>
20#include <vector>
21#include <thread>
22
23#include "hisysevent_listener.h"
24
25namespace OHOS {
26namespace HiviewDFX {
27class CrashEvent {
28public:
29    uint64_t time {0};
30    int64_t pid {0};
31    int64_t uid {0};
32    std::string path {""};
33    std::string name {""};
34    bool isCppCrash {false};
35};
36// every CPP_CRASH should have corresponding PROCESS_EXIT event and
37// every PROCESS_EXIT event that triggered by crash signal should have corresponding CPP_CRASH events
38// check the existence of these event to judge whether we have loss some crash log
39class CrashValidator : public OHOS::HiviewDFX::HiSysEventListener,
40    public std::enable_shared_from_this<CrashValidator> {
41public:
42    CrashValidator();
43    ~CrashValidator();
44
45    void OnEvent(std::shared_ptr<HiviewDFX::HiSysEventRecord> sysEvent) override;
46    void OnServiceDied() override;
47
48    bool InitSysEventListener();
49    void RemoveSysEventListener();
50
51    void Dump(int fd);
52
53private:
54    bool ValidateLogContent(const CrashEvent& event);
55    bool RemoveSimilarEvent(const CrashEvent& event);
56    void HandleCppCrashEvent(std::shared_ptr<HiviewDFX::HiSysEventRecord> sysEvent);
57    void HandleProcessExitEvent(std::shared_ptr<HiviewDFX::HiSysEventRecord> sysEvent);
58    void PrintEvents(int fd, const std::vector<CrashEvent>& events, bool isMatched);
59    void ReadServiceCrashStatus();
60    void CheckOutOfDateEvents();
61    bool stopReadKmsg_;
62    uint32_t totalEventCount_;
63    uint32_t normalEventCount_;
64    std::unique_ptr<std::thread> kmsgReaderThread_;
65    std::vector<CrashEvent> pendingEvents_;
66    std::vector<CrashEvent> noLogEvents_;
67    std::vector<CrashEvent> matchedEvents_;
68    std::mutex lock_;
69};
70} // namespace HiviewDFX
71} // namespace OHOS
72#endif // FAULTLOGGERD_CRASH_VALIDATOR_H
73#endif
74