1 /*
2 * Copyright (c) 2021-2022 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 "klog.h"
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <sys/wait.h>
19 #include <unistd.h>
20 #include <fcntl.h>
21 #include <cstdio>
22 #include <cstring>
23 #include <cstdlib>
24 #include <pthread.h>
25 #include <cstdarg>
26 #include <ctime>
27 #include <cerrno>
28 #include "securec.h"
29 #include "hilog/log.h"
30
31 namespace OHOS {
32 namespace MMI {
33 // dmesg
34 #define UNUSED(x) \
35 do { \
36 (void)(x) \
37 } while (0)
38
39 #define UNLIKELY(x) __builtin_expect(!!(x), 0)
40
41 static int g_fd_klog = -1;
42
43 constexpr int32_t MAX_LOG_SIZE = 1024;
44
KLogOpenLogDevice(void)45 void KLogOpenLogDevice(void)
46 {
47 #ifdef _CLOEXEC_
48 int fd = open("/dev/kmsg", O_WRONLY | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IRGRP);
49 #else
50 int fd = open("/dev/kmsg", O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IRGRP);
51 #endif
52 if (fd >= 0) {
53 g_fd_klog = fd;
54 }
55 return;
56 }
57
kMsgLog(const char * fileName,int line,const char * kLevel,const char * fmt,...)58 void kMsgLog(const char* fileName, int line, const char* kLevel,
59 const char* fmt, ...)
60 {
61 if (UNLIKELY(g_fd_klog < 0)) {
62 KLogOpenLogDevice();
63 if (g_fd_klog < 0) {
64 return;
65 }
66 }
67 va_list vargs;
68 va_start(vargs, fmt);
69 char tmpFmt[MAX_LOG_SIZE];
70 if (vsnprintf_s(tmpFmt, MAX_LOG_SIZE, MAX_LOG_SIZE - 1, fmt, vargs) == -1) {
71 va_end(vargs);
72 close(g_fd_klog);
73 g_fd_klog = -1;
74 return;
75 }
76
77 char logInfo[MAX_LOG_SIZE];
78 if (snprintf_s(logInfo, MAX_LOG_SIZE, MAX_LOG_SIZE - 1,
79 "%s[dm=%08X][pid=%d][%s:%d][%s][%s] %s",
80 kLevel, 0x0D002800, getpid(), fileName, line, "klog", "info", tmpFmt) == -1) {
81 va_end(vargs);
82 close(g_fd_klog);
83 g_fd_klog = -1;
84 return;
85 }
86 va_end(vargs);
87
88 if (write(g_fd_klog, logInfo, strlen(logInfo)) < 0) {
89 close(g_fd_klog);
90 g_fd_klog = -1;
91 }
92 return;
93 }
94 } // namespace MMI
95 } // namespace OHOS
96