1 /*
2 * Copyright (c) 2025 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 "kernel_snapshot_printer.h"
17
18 #include "dfx_log.h"
19 #include "string_util.h"
20
21 #include "kernel_snapshot_content_builder.h"
22 namespace OHOS {
23 namespace HiviewDFX {
24 namespace {
25 constexpr const char * const KBOX_SNAPSHOT_DUMP_PATH = "/data/log/faultlog/temp/";
26 }
27
OutputToFile(const std::string & filePath,CrashMap & output)28 void KernelSnapshotPrinter::OutputToFile(const std::string& filePath, CrashMap& output)
29 {
30 std::unique_ptr<FILE, decltype(&fclose)> file(fopen(filePath.c_str(), "w"), fclose);
31 if (!file) {
32 DFXLOGE("open file failed %{public}s errno %{public}d", filePath.c_str(), errno);
33 return;
34 }
35
36 std::string outputCont = KernelSnapshotContentBuilder(output, true).GenerateSummary();
37 if (fwrite(outputCont.c_str(), sizeof(char), outputCont.length(), file.get()) != outputCont.length()) {
38 DFXLOGE("write file failed %{public}s errno %{public}d", filePath.c_str(), errno);
39 }
40 }
41
SaveSnapshot(CrashMap & output)42 void KernelSnapshotPrinter::SaveSnapshot(CrashMap& output)
43 {
44 if (output[CrashSection::PID].empty()) {
45 DFXLOGE("pid is empty, not save snapshot");
46 return;
47 }
48
49 std::string filePath = std::string(KBOX_SNAPSHOT_DUMP_PATH) + "cppcrash-" +
50 output[CrashSection::PID] + "-" +
51 output[CrashSection::TIME_STAMP];
52 OutputToFile(filePath, output);
53 }
54
SaveSnapshots(std::vector<CrashMap> & outputs)55 void KernelSnapshotPrinter::SaveSnapshots(std::vector<CrashMap>& outputs)
56 {
57 for (auto& output : outputs) {
58 SaveSnapshot(output);
59 }
60 }
61 } // namespace HiviewDFX
62 } // namespace OHOS
63