#include <stdio.h>
#include <stddef.h>
#include <dlfcn.h>
#include <pthread.h>
#include <stddef.h>
#include "log.h"
__attribute__ ((__constructor__))
void Main() {
LOGI(">>>>>>>>>>>>>Inject Success!!!!<<<<<<<<<<<<<<");
void (*setA_func)(int);
void* handle = dlopen("libinso.so", RTLD_NOW);
LOGI("Handle:%p",handle);
//void (*setA_func)(int) = (void (*)(int))dlsym(handle, "setA");
setA_func = (void (*)(int))dlsym(handle,"setA");
LOGI("Func:%p",setA_func);
if (setA_func) {
LOGI("setA is Executing!!!");
(*setA_func)(999);
}
dlclose(handle);
}
说明:
这段代码需要解释一下,首先来看一下:
__attribute__ ((__constructor__))
gcc为函数提供了几种类型的属性,其中包含:构造函数(constructors)和析构函数(destructors)。
程序员应当使用类似下面的方式来指定这些属性:
static void start(void) __attribute__ ((constructor));
static void stop(void) __attribute__ ((destructor));
带有"构造函数"属性的函数将在main()函数之前被执行,而声明为"析构函数"属性的函数则将在main()退出时执行。
用法举例:
#include <iostream>
void breforemain() __attribute__((constructor));
void aftermain() __attribute__((destructor));
class AAA{
public:
AAA(){std::cout << "before main function AAA" << std::endl;}
~AAA(){std::cout << "after main function AAA" << std::endl;}
};
AAA aaa;
void breforemain()
{
std::cout << "before main function" << std::endl;
}
void aftermain()
{
std::cout << "after main function" << std::endl;
}
int main(int argc,char** argv)
{
std::cout << "in main function" << std::endl;
return 0;
}
输出结果:
before main function AAA
before main function
in main function
after main function AAA
after main function