Use fmtlib to print log (#1854)

(release zip size + ~50k)
This commit is contained in:
双草酸酯 2022-04-16 18:20:11 +08:00 committed by GitHub
parent 8a74235b92
commit 7b937c3347
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 65 additions and 53 deletions

3
.gitmodules vendored
View File

@ -10,3 +10,6 @@
[submodule "external/dobby"]
path = external/dobby
url = https://github.com/LSPosed/Dobby.git
[submodule "external/fmt"]
path = external/fmt
url = https://github.com/fmtlib/fmt.git

View File

@ -13,5 +13,5 @@ add_library(${PROJECT_NAME} STATIC ${SRC_LIST} ${CMAKE_CURRENT_BINARY_DIR}/src/c
target_include_directories(${PROJECT_NAME} PUBLIC include)
target_include_directories(${PROJECT_NAME} PRIVATE src)
target_link_libraries(${PROJECT_NAME} PUBLIC dobby lsplant_static log)
target_link_libraries(${PROJECT_NAME} PUBLIC dobby lsplant_static log fmt-header-only)
target_link_libraries(${PROJECT_NAME} PRIVATE dex_builder_static)

View File

@ -48,7 +48,7 @@ namespace art {
RETRIEVE_FIELD_SYMBOL(instance, "_ZN3art7Runtime9instance_E");
RETRIEVE_MEM_FUNC_SYMBOL(SetJavaDebuggable, "_ZN3art7Runtime17SetJavaDebuggableEb");
void *thiz = *instance;
LOGD("_ZN3art7Runtime9instance_E = %p", thiz);
LOGD("_ZN3art7Runtime9instance_E = {}", thiz);
instance_ = reinterpret_cast<Runtime*>(thiz);
}
};

View File

@ -104,14 +104,14 @@ namespace lspd {
inline void FindAndCall(JNIEnv *env, std::string_view method_name, std::string_view method_sig,
Args &&... args) const {
if (!entry_class_) [[unlikely]] {
LOGE("cannot call method %s, entry class is null", method_name.data());
LOGE("cannot call method {}, entry class is null", method_name);
return;
}
jmethodID mid = lsplant::JNI_GetStaticMethodID(env, entry_class_, method_name, method_sig);
if (mid) [[likely]] {
lsplant::JNI_CallStaticVoidMethod(env, entry_class_, mid, std::forward<Args>(args)...);
} else {
LOGE("method %s id is null", method_name.data());
LOGE("method {} id is null", method_name);
}
}

View File

@ -22,6 +22,8 @@
#define _LOGGING_H
#include <android/log.h>
#include <fmt/format.h>
#include <array>
#ifndef LOG_TAG
#define LOG_TAG "LSPosed"
@ -34,18 +36,25 @@
#define LOGW(...)
#define LOGE(...)
#else
template <typename... T>
constexpr inline void LOG(int prio, const char* tag, fmt::format_string<T...> fmt, T&&... args) {
std::array<char, 1024> buf{};
auto s = fmt::format_to_n(buf.data(), buf.size(), fmt, std::forward<T>(args)...).size;
buf[s] = '\0';
__android_log_write(prio, tag, buf.data());
}
#ifndef NDEBUG
#define LOGD(fmt, ...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, "%s:%d#%s" ": " fmt, __FILE_NAME__, __LINE__, __PRETTY_FUNCTION__ __VA_OPT__(,) __VA_ARGS__)
#define LOGV(fmt, ...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, "%s:%d#%s" ": " fmt, __FILE_NAME__, __LINE__, __PRETTY_FUNCTION__ __VA_OPT__(,) __VA_ARGS__)
#define LOGD(fmt, ...) LOG(ANDROID_LOG_DEBUG, LOG_TAG, "{}:{}#{}" ": " fmt, __FILE_NAME__, __LINE__, __PRETTY_FUNCTION__ __VA_OPT__(,) __VA_ARGS__)
#define LOGV(fmt, ...) LOG(ANDROID_LOG_VERBOSE, LOG_TAG, "{}:{}#{}" ": " fmt, __FILE_NAME__, __LINE__, __PRETTY_FUNCTION__ __VA_OPT__(,) __VA_ARGS__)
#else
#define LOGD(...)
#define LOGV(...)
#endif
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL, LOG_TAG, __VA_ARGS__)
#define PLOGE(fmt, args...) LOGE(fmt " failed with %d: %s", ##args, errno, strerror(errno))
#define LOGI(...) LOG(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGW(...) LOG(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#define LOGE(...) LOG(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGF(...) LOG(ANDROID_LOG_FATAL, LOG_TAG, __VA_ARGS__)
#define PLOGE(fmt, args...) LOGE(fmt " failed with {}: {}", ##args, errno, strerror(errno))
#endif
#endif // _LOGGING_H

View File

@ -53,7 +53,7 @@ inline bool RegisterNativeMethodsInternal(JNIEnv *env,
auto clazz = Context::GetInstance()->FindClassFromCurrentLoader(env, class_name);
if (clazz.get() == nullptr) {
LOGF("Couldn't find class: %s", class_name);
LOGF("Couldn't find class: {}", class_name);
return false;
}
return JNI_RegisterNatives(env, clazz, methods, method_count);
@ -90,7 +90,7 @@ inline int HookFunction(void *original, void *replace, void **backup) {
if constexpr (isDebug) {
Dl_info info;
if (dladdr(original, &info))
LOGD("Hooking %s (%p) from %s (%p)",
LOGD("Hooking {} ({}) from {} ({})",
info.dli_sname ? info.dli_sname : "(unknown symbol)", info.dli_saddr,
info.dli_fname ? info.dli_fname : "(unknown file)", info.dli_fbase);
}
@ -101,7 +101,7 @@ inline int UnhookFunction(void *original) {
if constexpr (isDebug) {
Dl_info info;
if (dladdr(original, &info))
LOGD("Unhooking %s (%p) from %s (%p)",
LOGD("Unhooking {} ({}) from {} ({})",
info.dli_sname ? info.dli_sname : "(unknown symbol)", info.dli_saddr,
info.dli_fname ? info.dli_fname : "(unknown file)", info.dli_fbase);
}

View File

@ -33,7 +33,7 @@ using namespace lsplant;
namespace lspd {
Context::PreloadedDex::PreloadedDex(int fd, std::size_t size) {
LOGD("Context::PreloadedDex::PreloadedDex: fd=%d, size=%zu", fd, size);
LOGD("Context::PreloadedDex::PreloadedDex: fd={}, size={}", fd, size);
auto *addr = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0);
if (addr != MAP_FAILED) {
@ -79,7 +79,7 @@ namespace lspd {
} else {
LOGE("No loadClass/findClass method found");
}
LOGE("Class %s not found", class_name.data());
LOGE("Class {} not found", class_name);
return {env, nullptr};
}
} // namespace lspd

View File

@ -44,13 +44,13 @@ ElfImg::ElfImg(std::string_view base_name) : elf(base_name) {
//load elf
int fd = open(elf.data(), O_RDONLY);
if (fd < 0) {
LOGE("failed to open %s", elf.data());
LOGE("failed to open {}", elf);
return;
}
size = lseek(fd, 0, SEEK_END);
if (size <= 0) {
LOGE("lseek() failed for %s", elf.data());
LOGE("lseek() failed for {}", elf);
}
header = reinterpret_cast<decltype(header)>(mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0));
@ -203,16 +203,13 @@ ElfImg::~ElfImg() {
ElfW(Addr)
ElfImg::getSymbOffset(std::string_view name, uint32_t gnu_hash, uint32_t elf_hash) const {
if (auto offset = GnuLookup(name, gnu_hash); offset > 0) {
LOGD("found %s %p in %s in dynsym by gnuhash", name.data(),
reinterpret_cast<void *>(offset), elf.data());
LOGD("found {} {:#x} in {} in dynsym by gnuhash", name, offset, elf);
return offset;
} else if (offset = ElfLookup(name, elf_hash); offset > 0) {
LOGD("found %s %p in %s in dynsym by elfhash", name.data(),
reinterpret_cast<void *>(offset), elf.data());
LOGD("found {} {:#x} in {} in dynsym by elfhash", name, offset, elf);
return offset;
} else if (offset = LinearLookup(name); offset > 0) {
LOGD("found %s %p in %s in symtab by linear lookup", name.data(),
reinterpret_cast<void *>(offset), elf.data());
LOGD("found {} {:#x} in {} in symtab by linear lookup", name, offset, elf);
return offset;
} else {
return 0;
@ -237,33 +234,33 @@ bool ElfImg::findModuleBase() {
std::string_view line{buff, static_cast<size_t>(nread)};
if ((contains(line, "r-xp") || contains(line, "r--p")) && contains(line, elf)) {
LOGD("found: %*s", static_cast<int>(line.size()), line.data());
LOGD("found: {}", line);
if (auto begin = line.find_last_of(' '); begin != std::string_view::npos &&
line[++begin] == '/') {
found = true;
elf = line.substr(begin);
if (elf.back() == '\n') elf.pop_back();
LOGD("update path: %s", elf.data());
LOGD("update path: {}", elf);
break;
}
}
}
if (!found) {
if (buff) free(buff);
LOGE("failed to read load address for %s", elf.data());
LOGE("failed to read load address for {}", elf);
fclose(maps);
return false;
}
if (char *next = buff; load_addr = strtoul(buff, &next, 16), next == buff) {
LOGE("failed to read load address for %s", elf.data());
LOGE("failed to read load address for {}", elf);
}
if (buff) free(buff);
fclose(maps);
LOGD("get module base %s: %lx", elf.data(), load_addr);
LOGD("get module base {}: {:#x}", elf, load_addr);
base = reinterpret_cast<void *>(load_addr);
return true;

View File

@ -52,7 +52,7 @@ LSP_DEF_NATIVE_METHOD(jboolean, HookBridge, hookMethod, jobject hookMethod,
~finally() {
auto finish = std::chrono::steady_clock::now();
if (newHook) {
LOGV("New hook took %lldus",
LOGV("New hook took {}us",
std::chrono::duration_cast<std::chrono::microseconds>(finish - start).count());
}
}

View File

@ -76,7 +76,7 @@ namespace lspd {
kXResourcesClassName)) {
classXResources = JNI_NewGlobalRef(env, classXResources_);
} else {
LOGE("Error while loading XResources class '%s':", kXResourcesClassName);
LOGE("Error while loading XResources class '{}':", kXResourcesClassName);
return JNI_FALSE;
}
methodXResourcesTranslateResId = JNI_GetStaticMethodID(

View File

@ -78,7 +78,7 @@ namespace lspd {
});
}();
if (!initialized) [[unlikely]] return;
LOGD("native_api: Registered %s", library_name.c_str());
LOGD("native_api: Registered {}", library_name);
moduleNativeLibs.push_back(library_name);
}
@ -101,18 +101,18 @@ namespace lspd {
} else {
ns = "NULL";
}
LOGD("native_api: do_dlopen(%s)", name);
LOGD("native_api: do_dlopen({})", name);
if (handle == nullptr) {
return nullptr;
}
for (std::string_view module_lib: moduleNativeLibs) {
// the so is a module so
if (hasEnding(ns, module_lib)) [[unlikely]] {
LOGD("Loading module native library %s", module_lib.data());
LOGD("Loading module native library {}", module_lib);
void *native_init_sym = dlsym(handle, "native_init");
if (native_init_sym == nullptr) [[unlikely]] {
LOGD("Failed to get symbol \"native_init\" from library %s",
module_lib.data());
LOGD("Failed to get symbol \"native_init\" from library {}",
module_lib);
break;
}
auto native_init = reinterpret_cast<NativeInit>(native_init_sym);
@ -133,7 +133,7 @@ namespace lspd {
});
bool InstallNativeAPI(const lsplant::HookHandler & handler) {
LOGD("InstallNativeAPI: %p", symbol_cache->do_dlopen);
LOGD("InstallNativeAPI: {}", symbol_cache->do_dlopen);
if (symbol_cache->do_dlopen) [[likely]] {
HookSymNoHandle(handler, symbol_cache->do_dlopen, do_dlopen);
return true;

View File

@ -102,3 +102,5 @@ link_libraries(cxx)
add_subdirectory(lsplant/lsplant/src/main/jni)
add_subdirectory(dobby)
add_subdirectory(fmt)
target_compile_definitions(fmt-header-only INTERFACE FMT_STATIC_THOUSANDS_SEPARATOR=1 FMT_USE_FLOAT=0 FMT_USE_DOUBLE=0 FMT_USE_LONG_DOUBLE=0)

1
external/fmt vendored Submodule

@ -0,0 +1 @@
Subproject commit 96930161f918d08a689076f500f128522a237a75

View File

@ -39,7 +39,7 @@ namespace lspd {
void onModuleLoaded() {
LOGI("onModuleLoaded: welcome to LSPosed!");
LOGI("onModuleLoaded: version v%s (%d)", versionName, versionCode);
LOGI("onModuleLoaded: version v{} ({})", versionName, versionCode);
InitSymbolCache(nullptr);
MagiskLoader::Init();
}
@ -120,8 +120,8 @@ namespace lspd {
}
RIRU_EXPORT RiruVersionedModuleInfo *init(Riru *riru) {
LOGD("using riru %d", riru->riruApiVersion);
LOGD("module path: %s", riru->magiskModulePath);
LOGD("using riru {}", riru->riruApiVersion);
LOGD("module path: {}", riru->magiskModulePath);
lspd::magiskPath = riru->magiskModulePath;
if (!lspd::isDebug && lspd::magiskPath.find(lspd::moduleName) == std::string::npos) {
LOGE("who am i");

View File

@ -61,7 +61,7 @@ namespace lspd {
read_sz += ret;
} while (read_sz != count && ret != 0);
if (read_sz != count) {
PLOGE("read (%zu != %zu)", count, read_sz);
PLOGE("read ({} != {})", count, read_sz);
}
return read_sz;
}
@ -81,7 +81,7 @@ namespace lspd {
write_sz += ret;
} while (write_sz != count && ret != 0);
if (write_sz != count) {
PLOGE("write (%zu != %zu)", count, write_sz);
PLOGE("write ({} != {})", count, write_sz);
}
return write_sz;
}
@ -339,7 +339,7 @@ namespace lspd {
SharedMem InitCompanion() {
LOGI("ZygiskCompanion: welcome to LSPosed!");
LOGI("ZygiskCompanion: version v%s (%d)", versionName, versionCode);
LOGI("ZygiskCompanion: version v{} ({})", versionName, versionCode);
SharedMem symbol{"symbol", sizeof(lspd::SymbolCache)};
@ -357,7 +357,7 @@ namespace lspd {
void CompanionEntry(int client) {
using namespace std::string_literals;
static auto symbol = InitCompanion();
LOGD("Got cache with fd=%d size=%d", symbol.get(), (int) symbol.size());
LOGD("Got cache with fd={} size={}", symbol.get(), symbol.size());
if (symbol.ok()) {
write_int(client, symbol.size());
send_fd(client, symbol.get());

View File

@ -157,12 +157,12 @@ namespace lspd {
JUTFString process_name(env, nice_name);
skip_ = !symbol_cache->initialized.test(std::memory_order_acquire);
if (!skip_ && !app_data_dir) {
LOGD("skip injecting into %s because it has no data dir", process_name.get());
LOGD("skip injecting into {} because it has no data dir", process_name.get());
skip_ = true;
}
if (!skip_ && is_child_zygote) {
skip_ = true;
LOGD("skip injecting into %s because it's a child zygote", process_name.get());
LOGD("skip injecting into {} because it's a child zygote", process_name.get());
}
if (!skip_ && ((app_id >= FIRST_ISOLATED_UID && app_id <= LAST_ISOLATED_UID) ||
@ -170,7 +170,7 @@ namespace lspd {
app_id <= LAST_APP_ZYGOTE_ISOLATED_UID) ||
app_id == SHARED_RELRO_UID)) {
skip_ = true;
LOGI("skip injecting into %s because it's isolated", process_name.get());
LOGI("skip injecting into {} because it's isolated", process_name.get());
}
setAllowUnload(skip_);
}
@ -204,14 +204,14 @@ namespace lspd {
FindAndCall(env, "forkCommon",
"(ZLjava/lang/String;Landroid/os/IBinder;)V",
JNI_FALSE, nice_name, binder);
LOGD("injected xposed into %s", process_name.get());
LOGD("injected xposed into {}", process_name.get());
setAllowUnload(false);
GetArt(true);
} else {
auto context = Context::ReleaseInstance();
auto service = Service::ReleaseInstance();
GetArt(true);
LOGD("skipped %s", process_name.get());
LOGD("skipped {}", process_name.get());
setAllowUnload(true);
}
}

View File

@ -221,7 +221,7 @@ namespace lspd {
auto bridge_service = JNI_CallStaticObjectMethod(env, service_manager_class_,
get_service_method_, bridge_service_name);
if (!bridge_service) {
LOGD("can't get %s", BRIDGE_SERVICE_NAME.data());
LOGD("can't get {}", BRIDGE_SERVICE_NAME);
return {env, nullptr};
}
@ -307,7 +307,7 @@ namespace lspd {
if (app_binder) {
JNI_NewGlobalRef(env, heart_beat_binder);
}
LOGD("Service::RequestSystemServerBinder app_binder: %p", app_binder.get());
LOGD("Service::RequestSystemServerBinder app_binder: {}", static_cast<void*>(app_binder.get()));
return app_binder;
}
@ -328,7 +328,7 @@ namespace lspd {
JNI_CallVoidMethod(env, data, recycleMethod_);
JNI_CallVoidMethod(env, reply, recycleMethod_);
LOGD("Service::RequestLSPDex fd=%d, size=%zu", fd, size);
LOGD("Service::RequestLSPDex fd={}, size={}", fd, size);
return {fd, size};
}
} // namespace lspd