#include <jni.h>
#include <android/log.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <linux/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include "ElfTool.h"

#include "hookzz.h"
#define TEST_printf 1
#define TEST_send 1
#define TEST_sendto 1
#define TEST_connect 1
#define TEST_freeaddrinfo 1
#define TEST_getaddrinfo 1
#define TEST_case_001 0

typedef unsigned char byte;

 // 保存openmemory函数旧的地址
void *(*old_openmemory)(const byte *base, size_t size, const std::string &location,
                                 uint32_t location_checksum, void *mem_map,
                        void *oat_dex_file, std::string *error_msg) = NULL;

void *new_openmemory(const byte *base, size_t size, const std::string &location,
                     uint32_t location_checksum, void *mem_map,
                     void *oat_dex_file, std::string *error_msg) {

     __android_log_print(ANDROID_LOG_ERROR, TAG, "art::DexFile::OpenMemory is called …   ");

    // writeToFile(pname, (uint8_t *) base, size);

     // 调用原art::DexFile::OpenMemory函数
     return (*old_openmemory)(base, size, location, location_checksum, mem_map, oat_dex_file,
                              error_msg);
 }

extern "C"
JNIEXPORT jstring

JNICALL
Java_com_x_hookzz_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "com_x_hookzz Hello from C++";
    // const char *hook_sym = "_ZN3art7DexFile10OpenMemoryEPKhjRKNSt3__112basic_stringIcNS3_11char_traitsIcEENS3_9allocatorIcEEEEjPNS_6MemMapEPKNS_10OatDexFileEPS9_";

    return env->NewStringUTF(hello.c_str());
}extern "C"
JNIEXPORT void JNICALL
Java_com_xposedhook_dexdump_Dumpper_dump(JNIEnv *env, jclass type) {
     const char *hook_sym = "_ZN3art7DexFile10OpenMemoryEPKhjRKNSt3__112basic_stringIcNS3_11char_traitsIcEENS3_9allocatorIcEEEEjPNS_6MemMapEPKNS_10OatDexFileEPS9_";
    int sym_addr = ElfTool::findSymbolByName("/system/lib/libart.so", hook_sym);
    ZzHookReplace((void *) sym_addr, (void *) new_openmemory, (void **) &old_openmemory);
    __android_log_print(ANDROID_LOG_ERROR, TAG, "addr: %08x             Java_com_xposedhook_dexdump_Dumpper_dump called", sym_addr);
}