1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <stdarg.h>
18 #include <stdint.h>
19 #include <stdio.h>
20 
21 #include <string>
22 
23 #define LOG_TAG "unwind"
24 #include <log/log.h>
25 
26 #if defined(__BIONIC__)
27 #include <async_safe/log.h>
28 #endif
29 #include <android-base/stringprintf.h>
30 
31 #include <unwindstack/Log.h>
32 
33 namespace unwindstack {
34 
35 static bool g_print_to_stdout = false;
36 
log_to_stdout(bool enable)37 void log_to_stdout(bool enable) {
38   g_print_to_stdout = enable;
39 }
40 
41 // Send the data to the log.
log(uint8_t indent,const char * format,...)42 void log(uint8_t indent, const char* format, ...) {
43   std::string real_format;
44   if (indent > 0) {
45     real_format = android::base::StringPrintf("%*s%s", 2 * indent, " ", format);
46   } else {
47     real_format = format;
48   }
49   va_list args;
50   va_start(args, format);
51   if (g_print_to_stdout) {
52     real_format += '\n';
53     vprintf(real_format.c_str(), args);
54   } else {
55     LOG_PRI_VA(ANDROID_LOG_INFO, LOG_TAG, real_format.c_str(), args);
56   }
57   va_end(args);
58 }
59 
60 #if defined(__BIONIC__)
log_async_safe(const char * format,...)61 void log_async_safe(const char* format, ...) {
62   if (g_print_to_stdout) {
63     // Printing to stdout is never async safe, so throw the message away.
64     return;
65   }
66 
67   va_list args;
68   va_start(args, format);
69   async_safe_format_log_va_list(ANDROID_LOG_ERROR, "libunwindstack", format, args);
70   va_end(args);
71 }
72 #else
log_async_safe(const char *,...)73 void log_async_safe(const char*, ...) {}
74 #endif
75 
76 }  // namespace unwindstack
77