1+ //
2+ // Created by beichen on 2025/3/12.
3+ //
4+ #include < string.h>
5+
6+ #include < alog.h>
7+ #include < fake_linker.h>
8+ #include < macros.h>
9+
10+ static int (*orig_access)(const char *pathname, int mode) = nullptr;
11+
12+ C_API API_PUBLIC int access (const char *pathname, int mode) {
13+ LOGW (" static hook access function path: %s, mode: %d" , pathname, mode);
14+ if (strncmp (pathname, " /test/hook/path" , 15 ) == 0 ) {
15+ LOGW (" fake access /test/hook/path" );
16+ return 0 ;
17+ }
18+ // Does not block other calls
19+ return orig_access (pathname, mode);
20+ }
21+
22+ C_API JNIEXPORT jint JNI_OnLoad (JavaVM *vm, void *reserved) {
23+ JNIEnv *env;
24+ if (vm->GetEnv (reinterpret_cast <void **>(&env), JNI_VERSION_1_6) != JNI_OK) {
25+ LOGE (" JNI environment error" );
26+ return JNI_EVERSION;
27+ }
28+ if (init_fakelinker (env,
29+ static_cast <FakeLinkerMode>(FakeLinkerMode::kFMSoinfo | FakeLinkerMode::kFMNativeHook |
30+ FakeLinkerMode::kFMJavaRegister ),
31+ nullptr ) != 0 ) {
32+ LOGE (" fakelinker environment error" );
33+ return JNI_ERR;
34+ }
35+
36+ const FakeLinker *fake_linker = get_fakelinker ();
37+
38+ SoinfoPtr libc = fake_linker->soinfo_find (SoinfoFindType::kSTName , " libc.so" , nullptr );
39+ if (!libc) {
40+ LOGE (" fakelinker find libc soinfo failed" );
41+ return JNI_ERR;
42+ }
43+
44+ orig_access = reinterpret_cast <int (*)(const char *pathname, int mode)>(
45+ fake_linker->soinfo_get_export_symbol_address (libc, " access" , nullptr ));
46+ if (!orig_access) {
47+ LOGE (" fakelinker find libc symbol access failed" );
48+ return JNI_ERR;
49+ }
50+
51+ SoinfoPtr fake_soinfo = fake_linker->soinfo_find (SoinfoFindType::kSTAddress , nullptr , nullptr );
52+ if (fake_soinfo == nullptr ) {
53+ LOGE (" find self soinfo failed" );
54+ return JNI_ERR;
55+ }
56+
57+ // Use so itself as a global library and hook all so loaded later
58+ if (!fake_linker->soinfo_add_to_global (fake_soinfo)) {
59+ LOGE (" fakelinker add global soinfo failed" );
60+ return JNI_ERR;
61+ }
62+ const char *loaded_libs[] = {
63+ " libjavacore.so" ,
64+ };
65+ // Since libjavacore has been loaded before we load it, symbol relocation will not be triggered.
66+ // At this time, manually relocate it to make the hook take effect.
67+ if (!fake_linker->call_manual_relocation_by_names (fake_soinfo, 1 , loaded_libs)) {
68+ LOGE (" relocation libjavacore.so failed" );
69+ return JNI_ERR;
70+ }
71+ LOGW (" fakelinker static load successfully" );
72+ return JNI_VERSION_1_6;
73+ }
0 commit comments