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 int FaultLoggerFdManager::faultLoggerFd_ = -1;
27
CloseFd()28 void FaultLoggerFdManager::CloseFd()
29 {
30 if (faultLoggerFd_ >= 0) {
31 close(faultLoggerFd_);
32 faultLoggerFd_ = -1;
33 }
34 }
35
InitFaultLoggerFd()36 int FaultLoggerFdManager::InitFaultLoggerFd()
37 {
38 if (faultLoggerFd_ == -1) {
39 faultLoggerFd_ = RequestFileDescriptor(FaultLoggerType::FFRT_CRASH_LOG);
40 }
41 return faultLoggerFd_;
42 }
43
GetFaultLoggerFd()44 int FaultLoggerFdManager::GetFaultLoggerFd()
45 {
46 return faultLoggerFd_;
47 }
48
WriteFaultLogger(const char * format,...)49 void FaultLoggerFdManager::WriteFaultLogger(const char* format, ...)
50 {
51 int fd = GetFaultLoggerFd();
52 if (fd < 0) {
53 return;
54 }
55
56 char errLog[g_logBufferSize] = {0};
57 va_list args;
58 va_start(args, format);
59 std::string formatStr(format);
60 formatStr = formatStr + "\n";
61 int ret = vsnprintf_s(errLog, sizeof(errLog), sizeof(errLog) - 1, formatStr.c_str(), args);
62 va_end(args);
63 if (ret < 0) {
64 return;
65 }
66
67 std::string msg = errLog;
68 int n = write(fd, msg.data(), msg.size());
69 if (n < 0) {
70 CloseFd();
71 }
72 }