1 /*
2 * Copyright (c) 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 <hilog_adapter.h>
17 #include <fcntl.h>
18 #include <dlfcn.h>
19 #include <unistd.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <pthread.h>
23
24 #include "musl_log.h"
25
26 #define PATH_MAX 256
27 #define DFX_LOG_LIB "libasan_logger.z.so"
28 #define DFX_LOG_INTERFACE "WriteGwpAsanLog"
29 static void (*g_dfxLogPtr)(char*, size_t);
30 static void* g_dfxLibHandler = NULL;
31 static pthread_mutex_t g_muslLogMutex = PTHREAD_MUTEX_INITIALIZER;
32
musl_log(const char * fmt,...)33 int musl_log(const char *fmt, ...)
34 {
35 int ret;
36 va_list ap;
37 va_start(ap, fmt);
38 ret = HiLogAdapterPrintArgs(MUSL_LOG_TYPE, LOG_INFO, MUSL_LOG_DOMAIN, MUSL_LOG_TAG, fmt, ap);
39
40 // Call dfx interface to write log
41 char buffer[PATH_MAX + 1];
42 int result = vsnprintf(buffer, PATH_MAX, fmt, ap);
43 va_end(ap);
44 if (result < 0) {
45 return result;
46 }
47 // The dfx interface requires actively adding line breaks
48 buffer[result] = '\n';
49 buffer[result + 1] = '\0';
50 if (g_dfxLogPtr != NULL) {
51 g_dfxLogPtr(buffer, strlen(buffer));
52 return 0;
53 }
54
55 pthread_mutex_lock(&g_muslLogMutex);
56 if (g_dfxLogPtr != NULL) {
57 g_dfxLogPtr(buffer, strlen(buffer));
58 pthread_mutex_unlock(&g_muslLogMutex);
59 return 0;
60 }
61 if (g_dfxLibHandler == NULL) {
62 g_dfxLibHandler = dlopen(DFX_LOG_LIB, RTLD_LAZY);
63 if (g_dfxLibHandler == NULL) {
64 MUSL_LOGE("[musl_log] dlopen %{public}s failed!\n", DFX_LOG_LIB);
65 pthread_mutex_unlock(&g_muslLogMutex);
66 return 0;
67 }
68 }
69 if (g_dfxLogPtr == NULL) {
70 *(void **)(&g_dfxLogPtr) = dlsym(g_dfxLibHandler, DFX_LOG_INTERFACE);
71 if (g_dfxLogPtr != NULL) {
72 g_dfxLogPtr(buffer, strlen(buffer));
73 } else {
74 MUSL_LOGE("[musl_log] dlsym %{public}s, failed!\n", DFX_LOG_INTERFACE);
75 }
76 }
77 pthread_mutex_unlock(&g_muslLogMutex);
78
79 return ret;
80 }
81