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 #include <cstdarg>
16 #include <cerrno>
17 #include <unistd.h>
18 #include <string>
19 #include <securec.h>
20 #include <iostream>
21 #include "dfx/log/ffrt_log_api.h"
22 #include "faultloggerd_client.h"
23 #include "dfx/bbox/fault_logger_fd_manager.h"
24
25 static const int g_logBufferSize = 2048;
26
FaultLoggerFdManager()27 FaultLoggerFdManager::FaultLoggerFdManager()
28 {
29 }
30
~FaultLoggerFdManager()31 FaultLoggerFdManager::~FaultLoggerFdManager()
32 {
33 CloseFd();
34 }
35
CloseFd()36 void FaultLoggerFdManager::CloseFd()
37 {
38 if (faultLoggerFd_ >= 0) {
39 close(faultLoggerFd_);
40 faultLoggerFd_ = -1;
41 }
42 }
43
InitFaultLoggerFd()44 int FaultLoggerFdManager::InitFaultLoggerFd()
45 {
46 if (faultLoggerFd_ == -1) {
47 faultLoggerFd_ = RequestFileDescriptor(FaultLoggerType::FFRT_CRASH_LOG);
48 if (faultLoggerFd_ < 0) {
49 FFRT_LOGW("fail to InitFaultLoggerFd");
50 }
51 }
52 return faultLoggerFd_;
53 }
54
GetFaultLoggerFd()55 int FaultLoggerFdManager::GetFaultLoggerFd()
56 {
57 return faultLoggerFd_;
58 }
59
WriteFaultLogger(const char * format,...)60 void FaultLoggerFdManager::WriteFaultLogger(const char* format, ...)
61 {
62 int fd = GetFaultLoggerFd();
63 if (fd < 0) {
64 return;
65 }
66
67 char errLog[g_logBufferSize] = {0};
68 va_list args;
69 va_start(args, format);
70 std::string formatStr(format);
71 formatStr = formatStr + "\n";
72 int ret = vsnprintf_s(errLog, sizeof(errLog), sizeof(errLog) - 1, formatStr.c_str(), args);
73 va_end(args);
74 if (ret < 0) {
75 return;
76 }
77
78 std::string msg = errLog;
79 int n = write(fd, msg.data(), msg.size());
80 if (n < 0) {
81 FFRT_LOGW("fail to write faultLogger msg:%s fd:%d, errno:%d", msg.data(), fd, errno);
82 CloseFd();
83 }
84 }