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 
16 #ifndef DFX_RING_BUFFER_WRAPPER_H
17 #define DFX_RING_BUFFER_WRAPPER_H
18 
19 #include <cinttypes>
20 #include <condition_variable>
21 #include <memory>
22 #include <mutex>
23 #include <string>
24 #include "dfx_ring_buffer.h"
25 #include "nocopyable.h"
26 
27 namespace OHOS {
28 namespace HiviewDFX {
29 
30 #define BACK_TRACE_RING_BUFFER_SIZE (32 * 1024)
31 
32 typedef int (*RingBufferWriteFunc) (int32_t fd, const char *buf, const int len);
33 
34 class DfxRingBufferWrapper final {
35 public:
36     static DfxRingBufferWrapper &GetInstance();
37     ~DfxRingBufferWrapper() = default;
38 
39     void StartThread();
40     void StopThread();
41 
42     void SetWriteBufFd(int32_t fd);
43     void SetWriteFunc(RingBufferWriteFunc func);
44 
45     void AppendMsg(const std::string& msg);
46     int AppendBuf(const char *format, ...);
47 
48     void AppendBaseInfo(const std::string& info);
49     void PrintBaseInfo();
50 private:
51     static void LoopPrintRingBuffer();
52     static int DefaultWrite(int32_t fd, const char *buf, const int len);
53 
54     DfxRingBufferWrapper() = default;
55     DISALLOW_COPY_AND_MOVE(DfxRingBufferWrapper);
56 
57     RingBufferWriteFunc writeFunc_ = nullptr;
58 
59     DfxRingBuffer<BACK_TRACE_RING_BUFFER_SIZE, std::string> ringBuffer_;
60     int32_t fd_ = -1;
61     volatile bool hasFinished_ = false;
62     std::vector<std::string> crashBaseInfo_;
63 
64     static std::condition_variable printCV_;
65     static std::mutex printMutex_;
66 };
67 } // namespace HiviewDFX
68 } // namespace OHOS
69 
70 #endif  // DFX_PROCESSDUMP_H
71