1/*
2 * Copyright (c) 2022-2024 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 DFX_FAULT_STACK_H
16#define DFX_FAULT_STACK_H
17
18#include <memory>
19#include <vector>
20
21#include "dfx_frame.h"
22#include "dfx_regs.h"
23#include "dfx_maps.h"
24
25namespace OHOS {
26namespace HiviewDFX {
27struct MemoryBlockInfo {
28    uintptr_t startAddr;
29    uintptr_t nameAddr;
30    uintptr_t size;
31    std::vector<uintptr_t> content;
32    std::string name;
33};
34
35// Only print first three frame stack
36class FaultStack {
37public:
38    explicit FaultStack(int32_t tid) : tid_(tid) {};
39    ~FaultStack() = default;
40
41    void Print() const;
42    void PrintRegisterMemory() const;
43    bool CollectStackInfo(const std::vector<DfxFrame>& frames, bool needParseStack = false);
44    bool CreateBlockForCorruptedStack(const std::vector<DfxFrame>& frames, uintptr_t prevEndAddr, uintptr_t size);
45    void CollectRegistersBlock(std::shared_ptr<DfxRegs> regs, std::shared_ptr<DfxMaps> maps);
46    bool ParseUnwindStack(std::shared_ptr<DfxMaps> maps, std::vector<DfxFrame>& frames);
47
48private:
49    bool ReadTargetMemory(uintptr_t addr, uintptr_t &value) const;
50    uintptr_t AdjustAndCreateMemoryBlock(size_t index, uintptr_t prevSp, uintptr_t prevEndAddr, uintptr_t size);
51    uintptr_t PrintMemoryBlock(const MemoryBlockInfo& info, uintptr_t stackStartAddr) const;
52    MemoryBlockInfo CreateMemoryBlock(uintptr_t addr, uintptr_t offset, uintptr_t size, const std::string& name) const;
53
54private:
55    int32_t tid_;
56    std::vector<MemoryBlockInfo> blocks_;
57    std::vector<MemoryBlockInfo> registerBlocks_;
58    mutable int prevErrno_ = 0;
59};
60} // namespace HiviewDFX
61} // namespace OHOS
62#endif
63