1 /*
2  * Copyright (c) 2023-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 
16 #include "dfx_json_formatter.h"
17 
18 #include <cstdlib>
19 #include <securec.h>
20 #include "dfx_kernel_stack.h"
21 #ifndef is_ohos_lite
22 #include "json/json.h"
23 #endif
24 
25 namespace OHOS {
26 namespace HiviewDFX {
27 #ifndef is_ohos_lite
28 namespace {
29 const int FRAME_BUF_LEN = 1024;
FormatJsFrame(const Json::Value& frames, const uint32_t& frameIdx, std::string& outStr)30 static bool FormatJsFrame(const Json::Value& frames, const uint32_t& frameIdx, std::string& outStr)
31 {
32     const int jsIdxLen = 10;
33     char buf[jsIdxLen] = { 0 };
34     char idxFmt[] = "#%02u at ";
35     if (snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, idxFmt, frameIdx) <= 0) {
36         return false;
37     }
38     outStr = std::string(buf, strlen(buf));
39     std::string symbol = frames[frameIdx]["symbol"].asString();
40     std::string file = frames[frameIdx]["file"].asString();
41     std::string line = frames[frameIdx]["line"].asString();
42     std::string column = frames[frameIdx]["column"].asString();
43     outStr.append(symbol + " (" + file + ":" + line + ":" + column + ")");
44     return true;
45 }
46 
FormatNativeFrame(const Json::Value& frames, const uint32_t& frameIdx, std::string& outStr)47 static bool FormatNativeFrame(const Json::Value& frames, const uint32_t& frameIdx, std::string& outStr)
48 {
49     char buf[FRAME_BUF_LEN] = {0};
50     char format[] = "#%02u pc %s %s";
51     std::string buildId = frames[frameIdx]["buildId"].asString();
52     std::string file = frames[frameIdx]["file"].asString();
53     std::string offset = frames[frameIdx]["offset"].asString();
54     std::string pc = frames[frameIdx]["pc"].asString();
55     std::string symbol = frames[frameIdx]["symbol"].asString();
56     if (snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, format, frameIdx, pc.c_str(),
57                    file.empty() ? "Unknown" : file.c_str()) <= 0) {
58         return false;
59     }
60     outStr = std::string(buf, strlen(buf));
61     if (!symbol.empty()) {
62         outStr.append("(" + symbol + "+" + offset + ")");
63     }
64     if (!buildId.empty()) {
65         outStr.append("(" + buildId + ")");
66     }
67     return true;
68 }
69 }
70 
FormatJsonStack(std::string jsonStack, std::string& outStackStr)71 bool DfxJsonFormatter::FormatJsonStack(std::string jsonStack, std::string& outStackStr)
72 {
73     Json::Reader reader;
74     Json::Value threads;
75     if (!(reader.parse(jsonStack, threads))) {
76         outStackStr.append("Failed to parse json stack info.");
77         return false;
78     }
79 
80     for (uint32_t i = 0; i < threads.size(); ++i) {
81         std::string ss;
82         Json::Value thread = threads[i];
83         if (thread["tid"].isConvertibleTo(Json::stringValue) &&
84             thread["thread_name"].isConvertibleTo(Json::stringValue)) {
85             ss += "Tid:" + thread["tid"].asString() + ", Name:" + thread["thread_name"].asString() + "\n";
86         }
87         const Json::Value frames = thread["frames"];
88         for (uint32_t j = 0; j < frames.size(); ++j) {
89             std::string frameStr = "";
90             bool formatStatus = false;
91             if (frames[j]["line"].asString().empty()) {
92                 formatStatus = FormatNativeFrame(frames, j, frameStr);
93             } else {
94                 formatStatus = FormatJsFrame(frames, j, frameStr);
95             }
96             if (formatStatus) {
97                 ss += frameStr + "\n";
98             } else {
99                 // Shall we try to print more information?
100                 outStackStr.append("Frame info is illegal.");
101                 return false;
102             }
103         }
104         outStackStr.append(ss);
105     }
106     return true;
107 }
108 
109 #ifdef __aarch64__
FormatKernelStackStr(const std::vector<DfxThreadStack>& processStack, std::string& formattedStack)110 static bool FormatKernelStackStr(const std::vector<DfxThreadStack>& processStack, std::string& formattedStack)
111 {
112     if (processStack.empty()) {
113         return false;
114     }
115     formattedStack = "";
116     for (const auto &threadStack : processStack) {
117         std::string ss = "Tid:" + std::to_string(threadStack.tid) + ", Name:" + threadStack.threadName + "\n";
118         formattedStack.append(ss);
119         for (size_t frameIdx = 0; frameIdx < threadStack.frames.size(); ++frameIdx) {
120             std::string file = threadStack.frames[frameIdx].mapName;
121             char buf[FRAME_BUF_LEN] = {0};
122             char format[] = "#%02zu pc %016" PRIx64 " %s";
123             if (snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, format, frameIdx, threadStack.frames[frameIdx].relPc,
124                 file.empty() ? "Unknown" : file.c_str()) <= 0) {
125                 continue;
126             }
127             formattedStack.append(std::string(buf, strlen(buf)) + "\n");
128         }
129     }
130     return true;
131 }
132 
FormatKernelStackJson(std::vector<DfxThreadStack> processStack, std::string& formattedStack)133 static bool FormatKernelStackJson(std::vector<DfxThreadStack> processStack, std::string& formattedStack)
134 {
135     if (processStack.empty()) {
136         return false;
137     }
138     Json::Value jsonInfo;
139     for (const auto &threadStack : processStack) {
140         Json::Value threadInfo;
141         threadInfo["thread_name"] = threadStack.threadName;
142         threadInfo["tid"] = threadStack.tid;
143         Json::Value frames(Json::arrayValue);
144         for (const auto& frame : threadStack.frames) {
145             Json::Value frameJson;
146             char buf[FRAME_BUF_LEN] = {0};
147             char format[] = "%016" PRIx64;
148             if (snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, format, frame.relPc) <= 0) {
149                 continue;
150             }
151             frameJson["pc"] = std::string(buf, strlen(buf));
152             frameJson["symbol"] = "";
153             frameJson["offset"] = 0;
154             frameJson["file"] = frame.mapName.empty() ? "Unknown" : frame.mapName;
155             frameJson["buildId"] = "";
156             frames.append(frameJson);
157         }
158         threadInfo["frames"] = frames;
159         jsonInfo.append(threadInfo);
160     }
161     formattedStack = Json::FastWriter().write(jsonInfo);
162     return true;
163 }
164 #endif
165 
FormatKernelStack(const std::string& kernelStack, std::string& formattedStack, bool jsonFormat)166 bool DfxJsonFormatter::FormatKernelStack(const std::string& kernelStack, std::string& formattedStack, bool jsonFormat)
167 {
168 #ifdef __aarch64__
169     std::vector<DfxThreadStack> processStack;
170     if (!FormatProcessKernelStack(kernelStack, processStack)) {
171         return false;
172     }
173     if (jsonFormat) {
174         return FormatKernelStackJson(processStack, formattedStack);
175     } else {
176         return FormatKernelStackStr(processStack, formattedStack);
177     }
178 #else
179     return false;
180 #endif
181 }
182 #endif
183 } // namespace HiviewDFX
184 } // namespace OHOS
185