Magisk/native/jni/base/logging.cpp

76 lines
1.9 KiB
C++
Raw Normal View History

#include <cstdio>
#include <cstdlib>
2018-09-27 03:11:10 -04:00
2022-07-05 21:13:09 -07:00
#include <android/log.h>
#include <flags.h>
2022-07-01 04:53:41 -07:00
#include <base.hpp>
2018-09-27 03:11:10 -04:00
2022-07-01 04:53:41 -07:00
// Just need to include it somewhere
#include <base-rs.cpp>
2021-08-12 03:26:54 -07:00
using namespace std;
2022-07-05 21:13:09 -07:00
static int fmt_and_log_with_rs(LogLevel level, const char *fmt, va_list ap) {
2022-07-01 04:53:41 -07:00
char buf[4096];
2022-07-05 21:13:09 -07:00
int ret = vsnprintf(buf, sizeof(buf), fmt, ap);
2022-07-06 01:16:08 -07:00
log_with_rs(level, rust::Str(buf, ret));
2022-07-05 21:13:09 -07:00
return ret;
}
2022-07-06 01:16:08 -07:00
int (*cpp_logger)(LogLevel level, const char *fmt, va_list ap) = fmt_and_log_with_rs;
2022-07-05 21:13:09 -07:00
// Used to override external C library logging
extern "C" int magisk_log_print(int prio, const char *tag, const char *fmt, ...) {
LogLevel level;
switch (prio) {
case ANDROID_LOG_DEBUG:
level = LogLevel::Debug;
break;
case ANDROID_LOG_INFO:
level = LogLevel::Info;
break;
case ANDROID_LOG_WARN:
level = LogLevel::Warn;
break;
case ANDROID_LOG_ERROR:
level = LogLevel::Error;
break;
default:
return 0;
}
char fmt_buf[4096];
auto len = strlcpy(fmt_buf, tag, sizeof(fmt_buf));
// Prevent format specifications in the tag
std::replace(fmt_buf, fmt_buf + len, '%', '_');
snprintf(fmt_buf + len, sizeof(fmt_buf) - len, ": %s", fmt);
va_list argv;
va_start(argv, fmt);
2022-07-06 01:16:08 -07:00
int ret = cpp_logger(level, fmt_buf, argv);
2022-07-05 21:13:09 -07:00
va_end(argv);
return ret;
2018-09-27 03:11:10 -04:00
}
2022-07-06 01:16:08 -07:00
#define LOG_BODY(level) { \
2021-08-12 03:26:54 -07:00
va_list argv; \
va_start(argv, fmt); \
2022-07-06 01:16:08 -07:00
cpp_logger(LogLevel::level, fmt, argv); \
2021-08-12 03:26:54 -07:00
va_end(argv); \
2018-09-27 03:11:10 -04:00
}
2021-08-12 03:26:54 -07:00
// LTO will optimize out the NOP function
#if MAGISK_DEBUG
2022-07-06 01:16:08 -07:00
void LOGD(const char *fmt, ...) { LOG_BODY(Debug) }
#else
2021-08-12 03:26:54 -07:00
void LOGD(const char *fmt, ...) {}
#endif
2022-07-06 01:16:08 -07:00
void LOGI(const char *fmt, ...) { LOG_BODY(Info) }
void LOGW(const char *fmt, ...) { LOG_BODY(Warn) }
void LOGE(const char *fmt, ...) { LOG_BODY(Error) }
2022-05-12 02:03:42 -07:00
// Export raw symbol to fortify compat
2022-07-01 04:53:41 -07:00
extern "C" void __vloge(const char* fmt, va_list ap) {
2022-07-06 01:16:08 -07:00
cpp_logger(LogLevel::Error, fmt, ap);
2022-05-12 02:03:42 -07:00
}