[
  {
    "path": ".gitignore",
    "content": "*.swp\n*.id0\n*.id1\n*.id2\n*.idb\n*.nam\n*.til\n*.un~\nobj/\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  <signature of Ty Coon>, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n"
  },
  {
    "path": "README.md",
    "content": "# EHook\n\nA hooking framework for commercial Android emulators ([雷电模拟器](http://www.ldmnq.com/), [NOX](https://jp.bignox.com/), [BlueStacks](https://www.bluestacks.com/ja/index.html#gref)).\n\nAs you may know, these commercail emulators use x86 (kernel) and arm (user land) mixed-mode method to accelerate the emulation and this makes it difficult to hook the native arm libraries. This emulator hooking framework is intented to solve this problem.\n\n\n# Usage\n\n1. Modify the jni/realinject.c file. You can hook functions both by address or by the function's symbol name:\n\n```\n    static struct hook_t eph1;\n    static struct hook_t eph_sendto;\n    ...\n    ...\n    \n    /*On BlueStacks*/\n    //hook_by_addr(&eph1, \"arm/libc.so\", target_addr, hook_func1);\n    \n    /*Other emulators*/\n    hook_by_name(&eph_sendto, \"nb/libc.so\", \"sendto\", hook_sendto);\n```\n**Notice:** If you are hooking system libraries like \"libc.so\", please make sure you are giving the right path of the arm version binary.\n    \n2. Run `ndk-build`\n\n3. Push the following 3 binary to android /data/local/tmp directory: \n    `libs/x86/stalker` \n    `libs/x86/libinject.so`\n    `libs/armeabi/librealinject.so`\n\nOr just run `push.cmd`.\n\n4. On android, type `./stalker [pid]`.\n\n# Notice\n1. For NOX emulator, you should use the Android 5.1.1 instead of the default 4.4.2.\n2. Also see this repo: [XEHook](https://github.com/nevermoe/XEHook).\n\n# acknowledgement\n\nThanks to these 大神s' work. They made my life much easier.\nhttps://github.com/zhengmin1989/TheSevenWeapons/tree/master/LiBieGou\n\nhttps://github.com/ele7enxxh/Android-Inline-Hook\n"
  },
  {
    "path": "jni/Android.mk",
    "content": "LOCAL_PATH := $(call my-dir)\n\ninclude $(CLEAR_VARS)\nLOCAL_CFLAGS += -fPIE\nLOCAL_LDFLAGS += -fPIE -pie\nLOCAL_MODULE    := target\nLOCAL_SRC_FILES := target.c\ncmd-strip :=  \n\ninclude $(BUILD_EXECUTABLE)\n\n###########################################################\n\ninclude $(CLEAR_VARS)\nLOCAL_MODULE    := hook\n#LOCAL_SRC_FILES := hook.c.arm\nLOCAL_SRC_FILES := hook.c\n\ninclude $(BUILD_STATIC_LIBRARY)\n\n###########################################################\n\ninclude $(CLEAR_VARS)\nLOCAL_MODULE    := relocate\nLOCAL_SRC_FILES := relocate.c\n\ninclude $(BUILD_STATIC_LIBRARY)\n\n###########################################################\n\n\ninclude $(CLEAR_VARS)\nLOCAL_CFLAGS += -fPIE\nLOCAL_LDFLAGS += -fPIE -pie\n\nLOCAL_MODULE    := stalker\nLOCAL_SRC_FILES := stalker.c\nLOCAL_LDLIBS := -llog \nLOCAL_STATIC_LIBRARIES := hook\n\ninclude $(BUILD_EXECUTABLE)\n\n###########################################################\n\ninclude $(CLEAR_VARS)\nLOCAL_DISABLE_FATAL_LINKER_WARNINGS := true\nLOCAL_MODULE    := inject\nLOCAL_SRC_FILES := inject.c\nLOCAL_LDLIBS := -llog \nLOCAL_STATIC_LIBRARIES := hook relocate\n\ninclude $(BUILD_SHARED_LIBRARY)\n\n###########################################################\n\ninclude $(CLEAR_VARS)\nLOCAL_DISABLE_FATAL_LINKER_WARNINGS := true\nLOCAL_MODULE    := realinject\nLOCAL_SRC_FILES := realinject.c\nLOCAL_LDLIBS := -llog \nLOCAL_STATIC_LIBRARIES := hook relocate\n\ninclude $(BUILD_SHARED_LIBRARY)\n"
  },
  {
    "path": "jni/Application.mk",
    "content": "APP_ABI := x86 armeabi-v7a\n# APP_OPTIM := debug\n\n\n"
  },
  {
    "path": "jni/hook.c",
    "content": "#include \"hook.h\"\n#include \"relocate.h\"\n\n\nvoid get_module_range(pid_t pid, const char* module_name, uint32_t* start_addr, uint32_t* end_addr)\n{\n    FILE *fp;\n    char *pch;\n    char filename[32];\n    char line[1024];\n    *start_addr = 0;\n    if (end_addr) {\n        *end_addr = 0;\n    }\n\n    if (pid == 0) {\n        snprintf(filename, sizeof(filename), \"/proc/self/maps\");\n    } else {\n        snprintf(filename, sizeof(filename), \"/proc/%d/maps\", pid);\n    }\n\n    fp = fopen(filename, \"r\");\n\n    if (fp != NULL) {\n        while (fgets(line, sizeof(line), fp)) {\n            //LOGD(\"line: %s\", line);\n            if (strstr(line, module_name)) {\n                pch = strtok(line, \"-\");\n                *start_addr = strtoul(pch, NULL, 16);\n                //LOGD(\"pch start: %s start_addr: %x\\n\", pch, *start_addr);\n                pch = strtok(NULL, \" \");\n                if (end_addr) {\n                    *end_addr = strtoul(pch, NULL, 16);\n                    //LOGD(\"pch end: %s end_addr: %x\\n\", pch, *end_addr);\n                }\n\n                /*\n                if (*start_addr == 0x8000) {\n                    *start_addr -= 0x8000;\n\n                    if (end_addr)\n                        *end_addr -= 0x8000;\n                }\n                */\n                break;\n            }\n        }\n\n        fclose(fp) ;\n    }\n}\n\nint hook_by_name(struct hook_t *h, char* module_name, const char* func_name, void *hook_func)\n{\n    int ret = 0;\n    void *handle = dlopen(module_name, RTLD_NOW);\n    void *func_addr = dlsym(handle, func_name);\n\n    //get module range for self process\n    uint32_t module_start_addr = 0, module_end_addr = 0;\n    get_module_range(0, module_name, &module_start_addr, &module_end_addr);\n    if(module_start_addr == 0 || module_end_addr == 0) {\n        LOGD(\"HOOK_ERROR_SO_NOT_FOUND: %s\\n\", module_name);\n        return HOOK_ERROR_SO_NOT_FOUND;\n    }\n\n    //mprotect\n    ret = mprotect((void*)module_start_addr, module_end_addr - module_start_addr, \n            PROT_READ|PROT_WRITE|PROT_EXEC);\n    if (ret) {\n        LOGD(\"mprotect failed\\n\");\n        return HOOK_ERROR_MPROTECT_FAILED;\n    }\n\n    h->module_base = module_start_addr;\n\n    return _hook(h, (unsigned int)func_addr, hook_func);\n}\n\nint hook_by_addr(struct hook_t *h, char* module_name, unsigned int addr, void *hook_func)\n{\n\tint i;\n\t\n    uint32_t module_start_addr = 0, module_end_addr = 0;\n    get_module_range(0, module_name, &module_start_addr, &module_end_addr);\n    if(module_start_addr == 0 || module_end_addr == 0) {\n        LOGD(\"HOOK_ERROR_SO_NOT_FOUND: %s\\n\", module_name);\n        return HOOK_ERROR_SO_NOT_FOUND;\n    }\n    unsigned int func_addr = module_start_addr + addr;\n    \n    //mprotect\n    int ret = mprotect((void*)module_start_addr, module_end_addr - module_start_addr, \n            PROT_READ|PROT_WRITE|PROT_EXEC);\n    if (ret) {\n        LOGD(\"mprotect failed\\n\");\n        return HOOK_ERROR_MPROTECT_FAILED;\n    }\n\n    h->module_base = module_start_addr;\n\n    return _hook(h, (unsigned int)func_addr, hook_func);\n}\n\nstatic int _hook(struct hook_t *h, unsigned int addr, void *hook_func)\n{\n\t\n    LOGD(\"[%d] hooking: 0x%x\\n\", getpid(), addr - h->module_base);\n    h->new_addr = (unsigned int)hook_func;\n    h->target_addr = addr;\n\n    h->length = TEST_BIT0(h->target_addr) ? 12 : 8;\n    memcpy(h->orig_instructions, (void *) CLEAR_BIT0(h->target_addr), h->length);\n    \n    //modify function entry point\n    if (!TEST_BIT0(h->target_addr)) {\n        //ARM mode\n        LOGD(\"using ARM mode 0x%lx\\n\", (unsigned long)hook_func);\n        h->thumb = 0;\n        h->proto = h->trampoline_instructions;\n        ((uint32_t *)h->target_addr)[0] = 0xe51ff004; // LDR pc, [pc, #-4]\n        ((uint32_t *)h->target_addr)[1] = h->new_addr;\n    }\n    else {\n        //thumb mode\n        LOGD(\"using thumb mode 0x%lx\\n\", (unsigned long)hook_func);\n\n        int i = 0;\n        if (CLEAR_BIT0(h->target_addr) % 4 != 0) {\n            ((uint16_t *) CLEAR_BIT0(h->target_addr))[i++] = 0xBF00;  // NOP\n        }\n\n        h->thumb = 1;\n        h->proto = (uint32_t *)SET_BIT0((uint32_t)h->trampoline_instructions);\n        ((uint16_t *) CLEAR_BIT0(h->target_addr))[i++] = 0xF8DF;\n        ((uint16_t *) CLEAR_BIT0(h->target_addr))[i++] = 0xF000; // LDR.W PC, [PC]\n        ((uint16_t *) CLEAR_BIT0(h->target_addr))[i++] = h->new_addr & 0xFFFF;\n        ((uint16_t *) CLEAR_BIT0(h->target_addr))[i++] = h->new_addr >> 16;\n\n    }\n\n    hook_cacheflush(CLEAR_BIT0(h->target_addr), CLEAR_BIT0(h->target_addr)+h->length);\n\n    relocateInstruction(h->target_addr, h->orig_instructions, h->length, h->trampoline_instructions, h->orig_boundaries, h->trampoline_boundaries, &h->count);\n\n    //addr must align to page (4kb)\n    int ret = mprotect((void*)((int)h->trampoline_instructions & 0xFFFFF000), 0x1000, \n            PROT_READ|PROT_WRITE|PROT_EXEC);\n\n    if (ret != 0) {\n        LOGD(\"mprotect failed: %d\\ttrampoline_addr: 0x%x\\n\", ret, (uint32_t)h->trampoline_instructions);\n        ret = HOOK_ERROR_MPROTECT_FAILED;\n    }\n\n\treturn ret;\n\n}\n\n\nvoid inline hook_cacheflush(unsigned int begin, unsigned int end)\n{\t\n#if 0\n#if defined(__arm__)    \n\tconst int syscall = 0xf0002;\n\n\t__asm __volatile (\n\t\t\"mov\t r0, %0\\n\"\t\t\t\n\t\t\"mov\t r1, %1\\n\"\n\t\t\"mov\t r7, %2\\n\"\n\t\t\"mov     r2, #0x0\\n\"\n\t\t\"svc     0x00000000\\n\"\n\t\t:\n\t\t:\t\"r\" (begin), \"r\" (end), \"r\" (syscall)\n\t\t:\t\"r0\", \"r1\", \"r7\"\n\t\t);\n#endif\n#endif\n}\n\n/*\nvoid hook_unset_jump(struct hook_t *h)\n{\n    int i;\n    \n    if (h->thumb) {\n        unsigned int orig = h->orig - 1;\n        for (i = 0; i < sizeof(h->storet); i++) {\n            ((unsigned char*)orig)[i] = h->storet[i];\n        }\n    }\n    else {\n        for (i = 0; i < sizeof(h->store)/4; i++)\n            ((unsigned int*)h->orig)[i] = h->store[i];\n    }   \n    hook_cacheflush((unsigned int)h->orig, (unsigned int)h->orig+sizeof(h->jumpt));\n}\n*/\n\n/*\nvoid hook_set_jump(struct hook_t *h)\n{\n    int i;\n\n    if (h->thumb) {\n        unsigned int orig = h->orig - 1;\n        for (i = 0; i < sizeof(h->jumpt); i++)\n            ((unsigned char*)orig)[i] = h->jumpt[i];\n    }\n    else {\n        for (i = 0; i < sizeof(h->jump)/sizeof(unsigned int); i++)\n            ((int*)h->orig)[i] = h->jump[i];\n    }\n    hook_cacheflush((unsigned int)h->orig, (unsigned int)h->orig+sizeof(h->jumpt));\n}\n*/\n\n"
  },
  {
    "path": "jni/hook.h",
    "content": "#ifndef __HOOK_H__\n#define __HOOK_H__\n\n#include <stdio.h>\n#include <stdlib.h>\n//#include <asm/user.h>\n#include <sys/user.h>\n#include <asm/ptrace.h>\n#include <sys/ptrace.h>\n#include <sys/wait.h>\n#include <sys/mman.h>\n#include <dlfcn.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <string.h>\n#include <elf.h>\n#include <android/log.h>\n\n\n#if defined(__i386__)    \n#define pt_regs         user_regs_struct    \n#endif    \n\n#define LOG_TAG \"MY_HOOK\"\n#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, fmt, ##args)\n#define LOGF(...) \\\n        {FILE *fp = fopen(\"/data/local/tmp/hook.log\", \"a+\"); if (fp) {\\\n        fprintf(fp, __VA_ARGS__);\\\n        fclose(fp);}}\n\n\n#define SET_BIT0(addr)      (addr | 1)\n#define CLEAR_BIT0(addr)    (addr & 0xFFFFFFFE)\n#define TEST_BIT0(addr)     (addr & 1)\n\n#define ORIG_INS_SIZE           3\n#define TRAMPOLINE_INS_SIZE     10\n#define ORIG_BOUND_SIZE         4\n#define TRAMPOLINE_BOUND_SIZE   20\n\nstruct hook_t {\n    uint32_t target_addr;\n    uint32_t new_addr;\n    uint32_t orig_instructions[ORIG_INS_SIZE];\n    uint32_t trampoline_instructions[TRAMPOLINE_INS_SIZE];\n    int orig_boundaries[ORIG_BOUND_SIZE];\n    int trampoline_boundaries[TRAMPOLINE_BOUND_SIZE];\n    uint32_t *proto;\n    int count;\n    int length;\n    unsigned int thumb;\n    unsigned int module_base;\n};\n\nenum hook_status {\n    HOOK_OK = 0,\n    //HOOK_ERROR_NOT_EXECUTABLE,\n    HOOK_ERROR_SO_NOT_FOUND,\n    HOOK_ERROR_MPROTECT_FAILED,\n    HOOK_ERROR_UNKNOWN\n};\n\nvoid get_module_range(pid_t pid, const char* module_name, uint32_t* start_addr, uint32_t* end_addr);\n\nint hook_by_addr(struct hook_t *h, char* module_name, unsigned int addr, void *hook_func);\nint hook_by_name(struct hook_t *h, char* module_name, const char* func_name, void *hook_func);\n\nstatic int _hook(struct hook_t *h, unsigned int addr, void *hook_func);\n\nvoid inline hook_cacheflush(unsigned int begin, unsigned int end);\n\nvoid hook_unset_jump(struct hook_t *h);\nvoid hook_set_jump(struct hook_t *h);\n\n#endif\n"
  },
  {
    "path": "jni/inject.c",
    "content": "#include \"hook.h\"\n#include <android/log.h>\n\ntypedef void *native_load_library(void *handle, const char *symbol);\ntypedef void *native_bridge_get_trampoline(void *handle, const char *symbol_name, const char* shorty, uint32_t length);\n\ntypedef void* dvm2_hd_dlopen(const char* filename, int flag);\n\ntypedef int real_init_func(char * str);\n\n\nvoid load_real_lib_bluestacks()\n{\n    void* dvm2hdDlopen = 0, *librealinject = 0, *lib3btrans = 0;\n\n    lib3btrans = dlopen(\"/system/lib/lib3btrans.so\", RTLD_NOW);\n    LOGD(\"lib3btrans.so handler addr is %p\\n\", lib3btrans);\n\n    dvm2hdDlopen = dlsym(lib3btrans, \"dvm2hdDlopen\");\n    LOGD(\"dvm2hdDlopen addr is %p\\n\", dvm2hdDlopen);\n\n    librealinject = ((dvm2_hd_dlopen*)dvm2hdDlopen)(\"/data/local/tmp/librealinject.so\", RTLD_NOW);\n    LOGD(\"librealinject.so handler addr is %p\\n\", librealinject);\n\n}\n\nvoid load_real_lib_4_4_2()\n{\n    void* dvm2hdDlopen = 0, *librealinject = 0, *libhoudini = 0;\n\n    libhoudini = dlopen(\"/system/lib/libhoudini.so\", RTLD_NOW);\n    LOGD(\"libhoudini.so handler addr is %p\\n\", libhoudini);\n\n    dvm2hdDlopen = dlsym(libhoudini, \"dvm2hdDlopen\");\n    LOGD(\"dvm2hdDlopen addr is %p\\n\", dvm2hdDlopen);\n\n    librealinject = ((dvm2_hd_dlopen*)dvm2hdDlopen)(\"/data/local/tmp/librealinject.so\", RTLD_NOW);\n    LOGD(\"librealinject.so handler addr is %p\\n\", librealinject);\n}\n\nvoid load_real_lib_5_5_1()\n{\n    void* libnativebridge = 0, *NativeBridgeLoadLibrary = 0, \n        *librealinject = 0;\n    libnativebridge = dlopen(\"/system/lib/libnativebridge.so\", RTLD_NOW);\n    LOGD(\"libnativebridge.so handler addr is %p\\n\", libnativebridge);\n\n    NativeBridgeLoadLibrary = dlsym(libnativebridge, \"_ZN7android23NativeBridgeLoadLibraryEPKci\");\n    LOGD(\"NativeBridgeLoadLibrary addr is %p\\n\", NativeBridgeLoadLibrary);\n\n    librealinject = ((native_load_library*)NativeBridgeLoadLibrary)(\"/data/local/tmp/librealinject.so\", RTLD_NOW);\n    LOGD(\"librealinject.so handler addr is %p\\n\", librealinject);\n\n#if 0\n    void *NativeBridgeGetTrampoline = 0, *RealInitFunc = 0;\n    NativeBridgeGetTrampoline = dlsym(libnativebridge, \"_ZN7android25NativeBridgeGetTrampolineEPvPKcS2_j\");\n    LOGD(\"NativeBridgeGetTrampoline addr is %p\\n\", NativeBridgeGetTrampoline);\n\n  \tRealInitFunc = ((native_bridge_get_trampoline*)NativeBridgeGetTrampoline)(librealinject, \"real_init_func\", 0, 0);\n    LOGD(\"RealInitFunc addr is %p\\n\", RealInitFunc);\n\n    ((real_init_func*)RealInitFunc)(\"HelloWorld\");\n#endif\n}\n\n\nint init_func(char * str){\n    LOGD(\"%s, hook in pid = %d\\n\", str, getpid());\n\n    char* nb_file = \"/system/lib/libnativebridge.so\";\n    char* dvm_file = \"/system/lib/libdvm.so\";\n    char* btrans_file = \"/system/lib/lib3btrans.so\";\n    if( access(nb_file, F_OK) != -1 ) {\n        // native bridge exists, Android 5.5.1\n        load_real_lib_5_5_1();\n    } else if ( access(btrans_file, F_OK) != -1){\n        // BlueStacks\n        load_real_lib_bluestacks();\n    } else { //dvm_file exsits\n        //Android 4.4.2, maybe NOX\n        load_real_lib_4_4_2();\n    }\n\n\n    LOGD(\"init_func ended\");\n\n    return 0;\n}\n"
  },
  {
    "path": "jni/realinject.c",
    "content": "#include \"hook.h\"\n#include <android/log.h>\n\nstatic struct hook_t eph;\n\nint hook_battleEnd(int p1, int p2)\n{\n\tint (*orig_func)(int p1, int p2);\n\torig_func = (void*)eph.proto;\n    \n    LOGD(\"hooking: 0x%x\\n\", (unsigned int)(eph.target_addr-eph.module_base));\n\n    p2 = 1;\n\tint ret = orig_func(p1, p2);\n\n    return ret;\n}\n\nstatic void real_init_func() __attribute__((constructor));\n\nvoid real_init_func() \n{\n#if 0\n    LOGD(\"real_init_func called\\n\");\n\n    long target_addr = 0;\n\n    target_addr = 0x590f0;//sendto\n\n    /*Bluestacks*/\n    //hook_by_addr(&eph_sendto, \"arm/libc.so\", target_addr, hook_sendto);\n    //hook_by_name(&eph_recvfrom, \"arm/libc.so\", \"recvfrom\", hook_recvfrom);\n\n    /*Other emulators*/\n    hook_by_addr(&eph_sendto, \"nb/libc.so\", target_addr, hook_sendto);\n    hook_by_name(&eph_recvfrom, \"nb/libc.so\", \"recvfrom\", hook_recvfrom);\n\n    LOGD(\"real_init_func ended\\n\");\n#endif\n    LOGD(\"real_init_func called\\n\");\n\n    long target_addr = 0;\n\n    target_addr = 0x177335;\n\n    hook_by_addr(&eph, \"libcocos2dcpp.so\", target_addr, hook_battleEnd);\n\n    LOGD(\"real_init_func ended\\n\");\n}\n\n"
  },
  {
    "path": "jni/relocate.c",
    "content": "/*\nrelocate instruction\nauthor: ele7enxxh\nmail: ele7enxxh@qq.com\nwebsite: ele7enxxh.com\nmodified time: 2016-10-17\ncreated time: 2015-01-17\n*/\n\n#include \"relocate.h\"\n#include <android/log.h>\n\n#define ALIGN_PC(pc)\t(pc & 0xFFFFFFFC)\n\n#define LOG_TAG \"MY_HOOK\"\n#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, fmt, ##args)\n\nenum INSTRUCTION_TYPE {\n\t// B <label>\n\tB1_THUMB16,\n\t// B <label>\n\tB2_THUMB16,\n\t// BX PC\n\tBX_THUMB16,\n\t// ADD <Rdn>, PC (Rd != PC, Rn != PC) 在对ADD进行修正时，采用了替换PC为Rr的方法，当Rd也为PC时，由于之前更改了Rr的值，可能会影响跳转后的正常功能。\n\tADD_THUMB16,\n\t// MOV Rd, PC\n\tMOV_THUMB16,\n\t// ADR Rd, <label>\n\tADR_THUMB16,\n\t// LDR Rt, <label>\n\tLDR_THUMB16,\n\n\t// CB{N}Z <Rn>, <label>\n\tCB_THUMB16,\n\n    //if-then\n    IT_THUMB16,\n\n    //dmb sy?\n    DMB_THUMB32,\n\n\t// BLX <label>\n\tBLX_THUMB32,\n\t// BL <label>\n\tBL_THUMB32,\n\t// B.W <label>\n\tB1_THUMB32,\n\t// B.W <label>\n\tB2_THUMB32,\n\t// ADR.W Rd, <label>\n\tADR1_THUMB32,\n\t// ADR.W Rd, <label>\n\tADR2_THUMB32,\n\t// LDR.W Rt, <label>\n\tLDR_THUMB32,\n\t// TBB [PC, Rm]\n\tTBB_THUMB32,\n\t// TBH [PC, Rm, LSL #1]\n\tTBH_THUMB32,\n\n\t// BLX <label>\n\tBLX_ARM,\n\t// BL <label>\n\tBL_ARM,\n\t// B <label>\n\tB_ARM,\n\t// BX PC\n\tBX_ARM,\n\t// ADD Rd, PC, Rm (Rd != PC, Rm != PC) 在对ADD进行修正时，采用了替换PC为Rr的方法，当Rd也为PC时，由于之前更改了Rr的值，可能会影响跳转后的正常功能;实际汇编中没有发现Rm也为PC的情况，故未做处理。\n\tADD_ARM,\n\t// ADR Rd, <label>\n\tADR1_ARM,\n\t// ADR Rd, <label>\n\tADR2_ARM,\n\t// MOV Rd, PC\n\tMOV_ARM,\n\t// LDR Rt, <label>\n\tLDR_ARM,\n\n\tUNDEFINE,\n};\n\nstatic int getTypeInThumb16(uint16_t instruction)\n{\n\tif ((instruction & 0xF000) == 0xD000) {\n\t\treturn B1_THUMB16;\n\t}\n\tif ((instruction & 0xF800) == 0xE000) {\n\t\treturn B2_THUMB16;\n\t}\n\tif ((instruction & 0xFFF8) == 0x4778) {\n\t\treturn BX_THUMB16;\n\t}\n\tif ((instruction & 0xFF78) == 0x4478) {\n\t\treturn ADD_THUMB16;\n\t}\n\tif ((instruction & 0xFF78) == 0x4678) {\n\t\treturn MOV_THUMB16;\n\t}\n\tif ((instruction & 0xF800) == 0xA000) {\n\t\treturn ADR_THUMB16;\n\t}\n\tif ((instruction & 0xF800) == 0x4800) {\n\t\treturn LDR_THUMB16;\n\t}\n\tif ((instruction & 0xF500) == 0xB100) {\n\t\treturn CB_THUMB16;\n\t}\n\tif ((instruction & 0xFF00) == 0xBF00) {\n\t\treturn IT_THUMB16;\n\t}\n\treturn UNDEFINE;\n}\n\nstatic int getTypeInThumb32(uint32_t instruction)\n{\n\tif ((instruction & 0xF800D000) == 0xF000C000) {\n\t\treturn BLX_THUMB32;\n\t}\n\tif ((instruction & 0xF800D000) == 0xF000D000) {\n\t\treturn BL_THUMB32;\n\t}\n    if ((instruction & 0xF3B08050) == 0xF3B08050) {\n        //FIXME\n        return DMB_THUMB32;\n    }\n\tif ((instruction & 0xF800D000) == 0xF0008000) {\n\t\treturn B1_THUMB32;\n\t}\n\tif ((instruction & 0xF800D000) == 0xF0009000) {\n\t\treturn B2_THUMB32;\n\t}\n\tif ((instruction & 0xFBFF8000) == 0xF2AF0000) {\n\t\treturn ADR1_THUMB32;\n\t}\n\tif ((instruction & 0xFBFF8000) == 0xF20F0000) {\n\t\treturn ADR2_THUMB32;\t\t\n\t}\n\tif ((instruction & 0xFF7F0000) == 0xF85F0000) {\n\t\treturn LDR_THUMB32;\n\t}\n\tif ((instruction & 0xFFFF00F0) == 0xE8DF0000) {\n\t\treturn TBB_THUMB32;\n\t}\n\tif ((instruction & 0xFFFF00F0) == 0xE8DF0010) {\n\t\treturn TBH_THUMB32;\n\t}\n\n\treturn UNDEFINE;\n}\n\nstatic int getTypeInArm(uint32_t instruction)\n{\n\tif ((instruction & 0xFE000000) == 0xFA000000) {\n\t\treturn BLX_ARM;\n\t}\n\tif ((instruction & 0xF000000) == 0xB000000) {\n\t\treturn BL_ARM;\n\t}\n\tif ((instruction & 0xF000000) == 0xA000000) {\n\t\treturn B_ARM;\n\t}\n\tif ((instruction & 0xFF000FF) == 0x120001F) {\n\t\treturn BX_ARM;\n\t}\n\tif ((instruction & 0xFEF0010) == 0x8F0000) {\n\t\treturn ADD_ARM;\n\t}\n\tif ((instruction & 0xFFF0000) == 0x28F0000) {\n\t\treturn ADR1_ARM;\n\t}\n\tif ((instruction & 0xFFF0000) == 0x24F0000) {\n\t\treturn ADR2_ARM;\t\t\n\t}\n\tif ((instruction & 0xE5F0000) == 0x41F0000) {\n\t\treturn LDR_ARM;\n\t}\n\tif ((instruction & 0xFE00FFF) == 0x1A0000F) {\n\t\treturn MOV_ARM;\n\t}\n\treturn UNDEFINE;\n}\n\nstatic int relocateInstructionInThumb16(uint32_t pc, uint16_t instruction, uint16_t *trampoline_instructions)\n{\n\tint type;\n\tint offset;\n\t\n\ttype = getTypeInThumb16(instruction);\n\tif (type == B1_THUMB16 || type == B2_THUMB16 || type == BX_THUMB16) {\n\t\tuint32_t x;\n\t\tint top_bit;\n\t\tuint32_t imm32;\n\t\tuint32_t value;\n\t\tint idx;\n\t\t\n\t\tidx = 0;\n\t\tif (type == B1_THUMB16) {\n\t\t\tx = (instruction & 0xFF) << 1;\n\t\t\ttop_bit = x >> 8;\n\t\t\timm32 = top_bit ? (x | (0xFFFFFFFF << 8)) : x;\n\t\t\t//value = pc + imm32;//FIXME\n\t\t\tvalue = (pc + imm32) | 0x1;\n\t\t\ttrampoline_instructions[idx++] = instruction & 0xFF00;\n\t\t\ttrampoline_instructions[idx++] = 0xE003;\t// B PC, #6\n\t\t}\n\t\telse if (type == B2_THUMB16) {\n\t\t\tx = (instruction & 0x7FF) << 1;\n\t\t\ttop_bit = x >> 11;\n\t\t\timm32 = top_bit ? (x | (0xFFFFFFFF << 11)) : x;\n\t\t\t//value = pc + imm32;//FIXME\n\t\t\tvalue = (pc + imm32) | 0x1;\n\t\t}\n\t\telse if (type == BX_THUMB16) {\n\t\t\tvalue = pc;\n\t\t}\n\t\t\n\t\ttrampoline_instructions[idx++] = 0xF8DF;\n\t\ttrampoline_instructions[idx++] = 0xF000;\t// LDR.W PC, [PC]\n\t\ttrampoline_instructions[idx++] = value & 0xFFFF;\n\t\ttrampoline_instructions[idx++] = value >> 16;\n\t\toffset = idx;\n\t}\n\telse if (type == ADD_THUMB16) {\n\t\tint rdn;\n\t\tint rm;\n\t\tint r;\n\t\t\n\t\trdn = ((instruction & 0x80) >> 4) | (instruction & 0x7);\n\t\t\n\t\tfor (r = 7; ; --r) {\n\t\t\tif (r != rdn) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\ttrampoline_instructions[0] = 0xB400 | (1 << r);\t// PUSH {Rr}\n\t\ttrampoline_instructions[1] = 0x4802 | (r << 8);\t// LDR Rr, [PC, #8]\n\t\ttrampoline_instructions[2] = (instruction & 0xFF87) | (r << 3);\n\t\ttrampoline_instructions[3] = 0xBC00 | (1 << r);\t// POP {Rr}\n\t\ttrampoline_instructions[4] = 0xE002;\t// B PC, #4\n\t\ttrampoline_instructions[5] = 0xBF00;\n\t\ttrampoline_instructions[6] = pc & 0xFFFF;\n\t\ttrampoline_instructions[7] = pc >> 16;\n\t\toffset = 8;\n\t}\n\telse if (type == MOV_THUMB16 || type == ADR_THUMB16 || type == LDR_THUMB16) {\n\t\tint r;\n\t\tuint32_t value;\n\t\t\n\t\tif (type == MOV_THUMB16) {\n\t\t\tr = instruction & 0x7;\n\t\t\tvalue = pc;\n\t\t}\n\t\telse if (type == ADR_THUMB16) {\n\t\t\tr = (instruction & 0x700) >> 8;\n\t\t\tvalue = ALIGN_PC(pc) + (instruction & 0xFF) << 2;\n\t\t}\n\t\telse {\n\t\t\tr = (instruction & 0x700) >> 8;\n\t\t\tvalue = ((uint32_t *) (ALIGN_PC(pc) + ((instruction & 0xFF) << 2)))[0];\n\t\t}\n\n\t\ttrampoline_instructions[0] = 0x4800 | (r << 8);\t// LDR Rd, [PC]\n\t\ttrampoline_instructions[1] = 0xE001;\t// B PC, #2\n\t\ttrampoline_instructions[2] = value & 0xFFFF;\n\t\ttrampoline_instructions[3] = value >> 16;\n\t\toffset = 4;\n\t}\n\telse if (type == CB_THUMB16) {\n\t\tint nonzero;\n\t\tuint32_t imm32;\n\t\tuint32_t value;\n\n\t\tnonzero = (instruction & 0x800) >> 11;\n\t\timm32 = ((instruction & 0x200) >> 3) | ((instruction & 0xF8) >> 2);\n\t\t//value = pc + imm32 + 1;\n\t\tvalue = (pc + imm32) | 0x1;\n\n\t\ttrampoline_instructions[0] = instruction & 0xFD07;\n\t\ttrampoline_instructions[1] = 0xE003;\t// B PC, #6\n\t\ttrampoline_instructions[2] = 0xF8DF;\n\t\ttrampoline_instructions[3] = 0xF000;\t// LDR.W PC, [PC]\n\t\ttrampoline_instructions[4] = value & 0xFFFF;\n\t\ttrampoline_instructions[5] = value >> 16;\n\t\toffset = 6;\n\t}\n    else if (type == IT_THUMB16) {\n        //FIXME: only considered IT XX.\n        //TODO: consider general situation like ITT, ITTT, ITE etc.\n\t\ttrampoline_instructions[0] = 0xBF00;  // NOP\n\t\ttrampoline_instructions[1] = instruction;\n\t\toffset = 2;\n    }\n\telse {\n\t\ttrampoline_instructions[0] = instruction;\n\t\ttrampoline_instructions[1] = 0xBF00;  // NOP\n\t\toffset = 2;\n\t}\n\t\n\treturn offset;\n}\n\nstatic int relocateInstructionInThumb32(uint32_t pc, uint16_t high_instruction, uint16_t low_instruction, uint16_t *trampoline_instructions)\n{\n\tuint32_t instruction;\n\tint type;\n\tint idx;\n\tint offset;\n\t\n\tinstruction = (high_instruction << 16) | low_instruction;\n\ttype = getTypeInThumb32(instruction);\n\tidx = 0;\n\tif (type == BLX_THUMB32 || type == BL_THUMB32 || type == B1_THUMB32 || type == B2_THUMB32) {\n\t\tuint32_t j1;\n\t\tuint32_t j2;\n\t\tuint32_t s;\n\t\tuint32_t i1;\n\t\tuint32_t i2;\n\t\tuint32_t x;\n\t\tuint32_t imm32;\n\t\tuint32_t value;\n\n\t\tj1 = (low_instruction & 0x2000) >> 13;\n\t\tj2 = (low_instruction & 0x800) >> 11;\n\t\ts = (high_instruction & 0x400) >> 10;\n\t\ti1 = !(j1 ^ s);\n\t\ti2 = !(j2 ^ s);\n\n\t\tif (type == BLX_THUMB32 || type == BL_THUMB32) {\n\t\t\ttrampoline_instructions[idx++] = 0xF20F;\n\t\t\ttrampoline_instructions[idx++] = 0x0E09;\t// ADD.W LR, PC, #9\n\t\t}\n\t\telse if (type == B1_THUMB32) {\n\t\t\ttrampoline_instructions[idx++] = 0xD000 | ((high_instruction & 0x3C0) << 2);\n\t\t\ttrampoline_instructions[idx++] = 0xE003;\t// B PC, #6\n\t\t}\n\t\ttrampoline_instructions[idx++] = 0xF8DF;\n\t\ttrampoline_instructions[idx++] = 0xF000;\t// LDR.W PC, [PC]\n\t\tif (type == BLX_THUMB32) {\n\t\t\tx = (s << 24) | (i1 << 23) | (i2 << 22) | ((high_instruction & 0x3FF) << 12) | ((low_instruction & 0x7FE) << 1);\n\t\t\timm32 = s ? (x | (0xFFFFFFFF << 25)) : x;\n\t\t\tvalue = pc + imm32;\n\t\t}\n\t\telse if (type == BL_THUMB32) {\n\t\t\tx = (s << 24) | (i1 << 23) | (i2 << 22) | ((high_instruction & 0x3FF) << 12) | ((low_instruction & 0x7FF) << 1);\n\t\t\timm32 = s ? (x | (0xFFFFFFFF << 25)) : x;\n\t\t\tvalue = pc + imm32 + 1;\n\t\t}\n\t\telse if (type == B1_THUMB32) {\n\t\t\tx = (s << 20) | (j2 << 19) | (j1 << 18) | ((high_instruction & 0x3F) << 12) | ((low_instruction & 0x7FF) << 1);\n\t\t\timm32 = s ? (x | (0xFFFFFFFF << 21)) : x;\n\t\t\tvalue = pc + imm32 + 1;\n\t\t}\n\t\telse if (type == B2_THUMB32) {\n\t\t\tx = (s << 24) | (i1 << 23) | (i2 << 22) | ((high_instruction & 0x3FF) << 12) | ((low_instruction & 0x7FF) << 1);\n\t\t\timm32 = s ? (x | (0xFFFFFFFF << 25)) : x;\n\t\t\tvalue = pc + imm32 + 1;\n\t\t}\n\t\ttrampoline_instructions[idx++] = value & 0xFFFF;\n\t\ttrampoline_instructions[idx++] = value >> 16;\n\t\toffset = idx;\n\t}\n\telse if (type == ADR1_THUMB32 || type == ADR2_THUMB32 || type == LDR_THUMB32) {\n\t\tint r;\n\t\tuint32_t imm32;\n\t\tuint32_t value;\n\t\t\n\t\tif (type == ADR1_THUMB32 || type == ADR2_THUMB32) {\n\t\t\tuint32_t i;\n\t\t\tuint32_t imm3;\n\t\t\tuint32_t imm8;\n\t\t\n\t\t\tr = (low_instruction & 0xF00) >> 8;\n\t\t\ti = (high_instruction & 0x400) >> 10;\n\t\t\timm3 = (low_instruction & 0x7000) >> 12;\n\t\t\timm8 = instruction & 0xFF;\n\t\t\t\n\t\t\timm32 = (i << 31) | (imm3 << 30) | (imm8 << 27);\n\t\t\t\n\t\t\tif (type == ADR1_THUMB32) {\n\t\t\t\tvalue = ALIGN_PC(pc) + imm32;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvalue = ALIGN_PC(pc) - imm32;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tint is_add;\n\t\t\tuint32_t *addr;\n\t\t\t\n\t\t\tis_add = (high_instruction & 0x80) >> 7;\n\t\t\tr = low_instruction >> 12;\n\t\t\timm32 = low_instruction & 0xFFF;\n\t\t\t\n\t\t\tif (is_add) {\n\t\t\t\taddr = (uint32_t *) (ALIGN_PC(pc) + imm32);\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddr = (uint32_t *) (ALIGN_PC(pc) - imm32);\n\t\t\t}\n\t\t\t\n\t\t\tvalue = addr[0];\n\t\t}\n\t\t\n\t\ttrampoline_instructions[0] = 0x4800 | (r << 8);\t// LDR Rr, [PC]\n\t\ttrampoline_instructions[1] = 0xE001;\t// B PC, #2\n\t\ttrampoline_instructions[2] = value & 0xFFFF;\n\t\ttrampoline_instructions[3] = value >> 16;\n\t\toffset = 4;\n\t}\n\n\telse if (type == TBB_THUMB32 || type == TBH_THUMB32) {\n\t\tint rm;\n\t\tint r;\n\t\tint rx;\n\t\t\n\t\trm = low_instruction & 0xF;\n\t\t\n\t\tfor (r = 7;; --r) {\n\t\t\tif (r != rm) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor (rx = 7; ; --rx) {\n\t\t\tif (rx != rm && rx != r) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\ttrampoline_instructions[0] = 0xB400 | (1 << rx);\t// PUSH {Rx}\n\t\ttrampoline_instructions[1] = 0x4805 | (r << 8);\t// LDR Rr, [PC, #20]\n\t\ttrampoline_instructions[2] = 0x4600 | (rm << 3) | rx;\t// MOV Rx, Rm\n\t\tif (type == TBB_THUMB32) {\n\t\t\ttrampoline_instructions[3] = 0xEB00 | r;\n\t\t\ttrampoline_instructions[4] = 0x0000 | (rx << 8) | rx;\t// ADD.W Rx, Rr, Rx\n\t\t\ttrampoline_instructions[5] = 0x7800 | (rx << 3) | rx; \t// LDRB Rx, [Rx]\n\t\t}\n\t\telse if (type == TBH_THUMB32) {\n\t\t\ttrampoline_instructions[3] = 0xEB00 | r;\n\t\t\ttrampoline_instructions[4] = 0x0040 | (rx << 8) | rx;\t// ADD.W Rx, Rr, Rx, LSL #1\n\t\t\ttrampoline_instructions[5] = 0x8800 | (rx << 3) | rx; \t// LDRH Rx, [Rx]\n\t\t}\n\t\ttrampoline_instructions[6] = 0xEB00 | r;\n\t\ttrampoline_instructions[7] = 0x0040 | (r << 8) | rx;\t// ADD Rr, Rr, Rx, LSL #1\n\t\ttrampoline_instructions[8] = 0x3001 | (r << 8);\t// ADD Rr, #1\n\t\ttrampoline_instructions[9] = 0xBC00 | (1 << rx);\t// POP {Rx}\n\t\ttrampoline_instructions[10] = 0x4700 | (r << 3);\t// BX Rr\n\t\ttrampoline_instructions[11] = 0xBF00;\n\t\ttrampoline_instructions[12] = pc & 0xFFFF;\n\t\ttrampoline_instructions[13] = pc >> 16;\n\t\toffset = 14;\n\t}\n\telse {\n\t\ttrampoline_instructions[0] = high_instruction;\n\t\ttrampoline_instructions[1] = low_instruction;\n\t\toffset = 2;\n\t}\n\n\treturn offset;\n}\n\nstatic void relocateInstructionInThumb(uint32_t target_addr, uint16_t *orig_instructions, int length, uint16_t *trampoline_instructions, int *orig_boundaries, int *trampoline_boundaries, int *count)\n{\n\tint orig_pos;\n\tint trampoline_pos;\n\tuint32_t pc;\n\tuint32_t lr;\n\n\torig_pos = 0;\n\ttrampoline_pos = 0;\n\tpc = target_addr + 4;\n\twhile (1) {\n\t\tint offset;\n\n\t\torig_boundaries[*count] = orig_pos * sizeof(uint16_t);\n\t\ttrampoline_boundaries[*count] = trampoline_pos * sizeof(uint16_t);\n\t\t++(*count);\n\t\t\n\t\tif ((orig_instructions[orig_pos] >> 11) >= 0x1D && (orig_instructions[orig_pos] >> 11) <= 0x1F) {\n\t\t\tif (orig_pos + 2 > length / sizeof(uint16_t)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toffset = relocateInstructionInThumb32(pc, orig_instructions[orig_pos], orig_instructions[orig_pos + 1], &trampoline_instructions[trampoline_pos]);\n\t\t\tpc += sizeof(uint32_t);\n\t\t\ttrampoline_pos += offset;\n\t\t\torig_pos += 2;\n\t\t}\n\t\telse {\n\t\t\toffset = relocateInstructionInThumb16(pc, orig_instructions[orig_pos], &trampoline_instructions[trampoline_pos]);\n\t\t\tpc += sizeof(uint16_t);\n\t\t\ttrampoline_pos += offset;\n\t\t\t++orig_pos;\n\t\t}\n\t\t\n\t\tif (orig_pos >= length / sizeof(uint16_t)) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\n\t\n\tlr = target_addr + orig_pos * sizeof(uint16_t) + 1;\n\ttrampoline_instructions[trampoline_pos] = 0xF8DF;\n\ttrampoline_instructions[trampoline_pos + 1] = 0xF000;\t// LDR.W PC, [PC]\n\ttrampoline_instructions[trampoline_pos + 2] = lr & 0xFFFF;\n\ttrampoline_instructions[trampoline_pos + 3] = lr >> 16;\n}\n\nstatic void relocateInstructionInArm(uint32_t target_addr, uint32_t *orig_instructions, int length, uint32_t *trampoline_instructions, int *orig_boundaries, int *trampoline_boundaries, int *count)\n{\n\tuint32_t pc;\n\tuint32_t lr;\n\tint orig_pos;\n\tint trampoline_pos;\n\n\tpc = target_addr + 8;\n\tlr = target_addr + length;\n\n\ttrampoline_pos = 0;\n\tfor (orig_pos = 0; orig_pos < length / sizeof(uint32_t); ++orig_pos) {\n\t\tuint32_t instruction;\n\t\tint type;\n\n\t\torig_boundaries[*count] = orig_pos * sizeof(uint32_t);\n\t\ttrampoline_boundaries[*count] = trampoline_pos * sizeof(uint32_t);\n\t\t++(*count);\n\n\t\tinstruction = orig_instructions[orig_pos];\n\t\ttype = getTypeInArm(instruction);\n\t\tif (type == BLX_ARM || type == BL_ARM || type == B_ARM || type == BX_ARM) {\n\t\t\tuint32_t x;\n\t\t\tint top_bit;\n\t\t\tuint32_t imm32;\n\t\t\tuint32_t value;\n\n\t\t\tif (type == BLX_ARM || type == BL_ARM) {\n\t\t\t\ttrampoline_instructions[trampoline_pos++] = 0xE28FE004;\t// ADD LR, PC, #4\n\t\t\t}\n\t\t\ttrampoline_instructions[trampoline_pos++] = 0xE51FF004;  \t// LDR PC, [PC, #-4]\n\t\t\tif (type == BLX_ARM) {\n\t\t\t\tx = ((instruction & 0xFFFFFF) << 2) | ((instruction & 0x1000000) >> 23);\n\t\t\t}\n\t\t\telse if (type == BL_ARM || type == B_ARM) {\n\t\t\t\tx = (instruction & 0xFFFFFF) << 2;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tx = 0;\n\t\t\t}\n\t\t\t\n\t\t\ttop_bit = x >> 25;\n\t\t\timm32 = top_bit ? (x | (0xFFFFFFFF << 26)) : x;\n\t\t\tif (type == BLX_ARM) {\n\t\t\t\tvalue = pc + imm32 + 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvalue = pc + imm32;\n\t\t\t}\n\t\t\ttrampoline_instructions[trampoline_pos++] = value;\n\t\t\t\n\t\t}\n\t\telse if (type == ADD_ARM) {\n\t\t\tint rd;\n\t\t\tint rm;\n\t\t\tint r;\n\t\t\t\n\t\t\trd = (instruction & 0xF000) >> 12;\n\t\t\trm = instruction & 0xF;\n\t\t\t\n\t\t\tfor (r = 12; ; --r) {\n\t\t\t\tif (r != rd && r != rm) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//ADD Rd, PC, Rm\n\t\t\ttrampoline_instructions[trampoline_pos++] = 0xE52D0004 | (r << 12);\t// PUSH {Rr}\n\t\t\ttrampoline_instructions[trampoline_pos++] = 0xE59F0008 | (r << 12);\t// LDR Rr, [PC, #8]\n\t\t\ttrampoline_instructions[trampoline_pos++] = (instruction & 0xFFF0FFFF) | (r << 16);\n\t\t\ttrampoline_instructions[trampoline_pos++] = 0xE49D0004 | (r << 12);\t// POP {Rr}\n\t\t\ttrampoline_instructions[trampoline_pos++] = 0xE28FF000;\t// ADD PC, PC\n\t\t\ttrampoline_instructions[trampoline_pos++] = pc;\n\n            //ADD   PC, R12, PC\n            //ADD   \n\t\t}\n\t\telse if (type == ADR1_ARM || type == ADR2_ARM || type == LDR_ARM || type == MOV_ARM) {\n\t\t\tint r;\n\t\t\tuint32_t value;\n\t\t\t\n\t\t\tr = (instruction & 0xF000) >> 12;\n\t\t\t\n\t\t\tif (type == ADR1_ARM || type == ADR2_ARM || type == LDR_ARM) {\n\t\t\t\tuint32_t imm32;\n\t\t\t\t\n\t\t\t\timm32 = instruction & 0xFFF;\n\t\t\t\tif (type == ADR1_ARM) {\n\t\t\t\t\tvalue = pc + imm32;\n\t\t\t\t}\n\t\t\t\telse if (type == ADR2_ARM) {\n\t\t\t\t\tvalue = pc - imm32;\n\t\t\t\t}\n\t\t\t\telse if (type == LDR_ARM) {\n\t\t\t\t\tint is_add;\n\t\t\t\t\t\n\t\t\t\t\tis_add = (instruction & 0x800000) >> 23;\n\t\t\t\t\tif (is_add) {\n\t\t\t\t\t\tvalue = ((uint32_t *) (pc + imm32))[0];\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tvalue = ((uint32_t *) (pc - imm32))[0];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvalue = pc;\n\t\t\t}\n\t\t\t\t\n\t\t\ttrampoline_instructions[trampoline_pos++] = 0xE51F0000 | (r << 12);\t// LDR Rr, [PC]\n\t\t\ttrampoline_instructions[trampoline_pos++] = 0xE28FF000;\t// ADD PC, PC\n\t\t\ttrampoline_instructions[trampoline_pos++] = value;\n\t\t}\n\t\telse {\n\t\t\ttrampoline_instructions[trampoline_pos++] = instruction;\n\t\t}\n\t\tpc += sizeof(uint32_t);\n\t}\n\t\n\ttrampoline_instructions[trampoline_pos++] = 0xe51ff004;\t// LDR PC, [PC, #-4]\n\ttrampoline_instructions[trampoline_pos++] = lr;\n}\n\nvoid relocateInstruction(uint32_t target_addr, void *orig_instructions, int length, void *trampoline_instructions, int *orig_boundaries, int *trampoline_boundaries, int *count)\n{\n\tif (target_addr & 1 == 1) {\n\t\trelocateInstructionInThumb(target_addr - 1, (uint16_t *) orig_instructions, length, (uint16_t *) trampoline_instructions, orig_boundaries, trampoline_boundaries, count);\n\t}\n\telse {\n\t\trelocateInstructionInArm(target_addr, (uint32_t *) orig_instructions, length, (uint32_t *) trampoline_instructions, orig_boundaries, trampoline_boundaries, count);\n\t}\n}\n"
  },
  {
    "path": "jni/relocate.h",
    "content": "#ifndef __RELOCATE_H__\n#define __RELOCATE_H__\n\n#include <stdio.h>\n\nvoid relocateInstruction(uint32_t target_addr, void *orig_instructions, int length, void *trampoline_instructions, int *orig_boundaries, int *trampoline_boundaries, int *count);\n\n#endif\n"
  },
  {
    "path": "jni/stalker.c",
    "content": "#include \"hook.h\"\n//#include <stdio.h>\n//#include <stdlib.h>\n////#include <asm/user.h>\n//#include <sys/user.h>\n//#include <asm/ptrace.h>\n//#include <sys/ptrace.h>\n//#include <sys/wait.h>\n//#include <sys/mman.h>\n//#include <dlfcn.h>\n//#include <dirent.h>\n//#include <unistd.h>\n//#include <string.h>\n//#include <elf.h>\n//#include <android/log.h>\n\n//#define LOG_TAG \"MY_HOOK\"\n//#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, fmt, ##args)\n//#define LOGF(...) \\\n//        {FILE *fp = fopen(\"/data/local/tmp/hook.log\", \"a+\"); if (fp) {\\\n//        fprintf(fp, __VA_ARGS__);\\\n//        fclose(fp);}}\n\n#define CPSR_T_MASK     ( 1u << 5 )\n\nconst char *libc_path = \"/system/lib/libc.so\";\nconst char *linker_path = \"/system/bin/linker\";\nconst char *libdl_path = \"/system/lib/libdl.so\";\n\nconst int long_size = sizeof(long);\n\n\nuint32_t get_remote_addr(pid_t target_pid, const char* module_name, void* local_addr)\n{\n    uint32_t local_handle, remote_handle;\n\n    get_module_range(0, module_name, &local_handle, 0);\n    get_module_range(target_pid, module_name, &remote_handle, 0);\n    printf(\"remote %s handle = 0x%x\\n\", module_name, (unsigned int)remote_handle);\n\n    long ret_addr = (long)((uint32_t)local_addr + (uint32_t)remote_handle - (uint32_t)local_handle);\n\n    return ret_addr;\n}\n\nint ptrace_attach(pid_t pid)    \n{    \n    if (ptrace(PTRACE_ATTACH, pid, NULL, 0) < 0) {    \n        perror(\"ptrace_attach\");    \n        return -1;    \n    }    \n    \n    int status = 0;    \n    waitpid(pid, &status , WUNTRACED);    \n    \n    return 0;    \n}    \n\nlong ptrace_retval(struct pt_regs * regs)    \n{    \n#if defined(__arm__)    \n    return regs->ARM_r0;    \n#elif defined(__i386__)    \n    return regs->eax;    \n#else    \n#error \"Not supported\"    \n#endif    \n}    \n    \nlong ptrace_ip(struct pt_regs * regs)    \n{    \n#if defined(__arm__)    \n    return regs->ARM_pc;    \n#elif defined(__i386__)    \n    return regs->eip;    \n#else    \n#error \"Not supported\"    \n#endif    \n}\n\nint ptrace_setregs(pid_t pid, struct pt_regs * regs)    \n{    \n    if (ptrace(PTRACE_SETREGS, pid, NULL, regs) < 0) {    \n        perror(\"ptrace_setregs: Can not set register values\");    \n        return -1;    \n    }    \n    \n    return 0;    \n}   \n\nint ptrace_getregs(pid_t pid, struct pt_regs * regs)    \n{    \n    if (ptrace(PTRACE_GETREGS, pid, NULL, regs) < 0) {    \n        perror(\"ptrace_getregs: Can not get register values\");    \n        return -1;    \n    }    \n    \n    return 0;    \n}   \n\nint ptrace_continue(pid_t pid)\n{\n    if (ptrace(PTRACE_CONT, pid, NULL, 0) < 0) {\n        perror(\"ptrace_cont\");\n        return -1;\n    }\n\n    return 0;\n}\n\nint ptrace_detach(pid_t pid)    \n{    \n    if (ptrace(PTRACE_DETACH, pid, NULL, 0) < 0) {    \n        perror(\"ptrace_detach\");    \n        return -1;    \n    }    \n    \n    return 0;    \n}    \n\n\nint ptrace_readdata(pid_t pid,  uint8_t *src, uint8_t *buf, size_t size)    \n{    \n    uint32_t i, j, remain;    \n    uint8_t *laddr;    \n    \n    union u {    \n        long val;    \n        char chars[sizeof(long)];    \n    } d;    \n    \n    j = size / 4;    \n    remain = size % 4;    \n    \n    laddr = buf;    \n    \n    for (i = 0; i < j; i ++) {    \n        d.val = ptrace(PTRACE_PEEKTEXT, pid, src, 0);    \n        memcpy(laddr, d.chars, 4);    \n        src += 4;    \n        laddr += 4;    \n    }    \n    \n    if (remain > 0) {    \n        d.val = ptrace(PTRACE_PEEKTEXT, pid, src, 0);    \n        memcpy(laddr, d.chars, remain);    \n    }    \n    \n    return 0;    \n}    \n\nint ptrace_writedata(pid_t pid, uint8_t *dest, uint8_t *data, size_t size)    \n{    \n    uint32_t i, j, remain;    \n    uint8_t *laddr;    \n    \n    union u {    \n        long val;    \n        char chars[sizeof(long)];    \n    } d;    \n    \n    j = size / 4;    \n    remain = size % 4;    \n    \n    laddr = data;    \n    \n    for (i = 0; i < j; i ++) {    \n        memcpy(d.chars, laddr, 4);    \n        ptrace(PTRACE_POKETEXT, pid, dest, d.val);    \n    \n        dest  += 4;    \n        laddr += 4;    \n    }    \n    \n    if (remain > 0) {    \n        d.val = ptrace(PTRACE_PEEKTEXT, pid, dest, 0);    \n        for (i = 0; i < remain; i ++) {    \n            d.chars[i] = *laddr ++;    \n        }    \n    \n        ptrace(PTRACE_POKETEXT, pid, dest, d.val);    \n    }    \n    \n    return 0;    \n}    \n\nlong ptrace_call(pid_t pid, uint32_t addr, uint32_t *params, uint32_t num_params, struct pt_regs * regs)    \n{    \n#if defined(__i386__)    \n    regs->esp -= (num_params) * sizeof(uint32_t) ;    \n    ptrace_writedata(pid, (void *)regs->esp, (uint8_t *)params, (num_params) * sizeof(uint32_t));    \n    \n    long tmp_addr = 0x00;    \n    regs->esp -= sizeof(long);    \n    ptrace_writedata(pid, (void *)regs->esp, (uint8_t *)&tmp_addr, sizeof(tmp_addr));     \n    \n    regs->eip = addr;    \n    \n    if (ptrace_setregs(pid, regs) == -1     \n            || ptrace_continue( pid) == -1) {    \n        printf(\"error\\n\");    \n        return -1;    \n    }    \n\n    \n    int stat = 0;  \n    waitpid(pid, &stat, WUNTRACED);  \n\n#if 0\n    LOGD(\"stat: %x\", stat);\n    int i = 0;\n    for (i = 0; i < 10 ; i++) {\n        ptrace(PTRACE_SINGLESTEP, pid, 0, 0);\n        waitpid(pid, &stat, WUNTRACED);  \n        if (ptrace_getregs(pid, regs) == -1)    \n            return -1;    \n        LOGD(\"[+] Target process single stepped, return value=%lx, pc=%lx \\n\",     \n            ptrace_retval(regs), ptrace_ip(regs));    \n        LOGD(\"stat: %x\", stat);\n    }\n#endif\n\n    while (stat != 0xb7f) {  \n        if (ptrace_continue(pid) == -1) {  \n            printf(\"error\\n\");  \n            return -1;  \n        }  \n        waitpid(pid, &stat, WUNTRACED);  \n    }  \n#endif\n    \n    return 0;    \n}\n\n\nint ptrace_call_wrapper(pid_t target_pid, const char * func_name, void * func_addr, uint32_t* parameters, int param_num, struct pt_regs * regs)     \n{    \n    LOGD(\"[+] Calling %s in target process.\\n\", func_name);    \n    if (ptrace_call(target_pid, (uint32_t)func_addr, parameters, param_num, regs) == -1)    \n        return -1;    \n    \n    if (ptrace_getregs(target_pid, regs) == -1)    \n        return -1;    \n    LOGD(\"[+] Target process returned from %s, return value=%lx, pc=%lx \\n\",     \n            func_name, ptrace_retval(regs), ptrace_ip(regs));    \n    return 0;    \n}    \n\nint inject_remote_process(pid_t target_pid, const char *library_path, const char *function_name, const char *param, size_t param_size)    \n{    \n    int ret = -1;    \n    void *mmap_addr, *dlopen_addr, *dlsym_addr, *dlclose_addr, *dlerror_addr;\n    void *local_handle, *remote_handle, *dlhandle;    \n    uint32_t map_base = 0;    \n    \n    struct pt_regs regs, original_regs;    \n    \n    uint32_t parameters[10];    \n    \n    LOGD(\"[+] Injecting process: %d\\n\", target_pid);    \n    \n    if (ptrace_attach(target_pid) == -1)    \n        goto exit;    \n    \n    if (ptrace_getregs(target_pid, &regs) == -1)    \n        goto exit;    \n    \n    /* save original registers */    \n    memcpy(&original_regs, &regs, sizeof(regs));    \n    \n    mmap_addr = (void*)get_remote_addr(target_pid, libc_path, (void *)mmap);    \n    LOGD(\"[+] Remote mmap address: %x\\n\", (uint32_t)mmap_addr);    \n    \n    /* call mmap */    \n    parameters[0] = 0;  // addr    \n    parameters[1] = 0x4000; // size    \n    parameters[2] = PROT_READ | PROT_WRITE | PROT_EXEC;  // prot    \n    parameters[3] =  MAP_ANONYMOUS | MAP_PRIVATE; // flags    \n    parameters[4] = 0; //fd    \n    parameters[5] = 0; //offset    \n    \n    if (ptrace_call_wrapper(target_pid, \"mmap\", mmap_addr, parameters, 6, &regs) == -1)    \n        goto exit;    \n    \n    map_base = ptrace_retval(&regs);\n    LOGD(\"[+] map_base %p\\n\", (void *)map_base);\n    \n    dlopen_addr = (void*)get_remote_addr( target_pid, linker_path, (void *)dlopen );    \n    dlsym_addr = (void*)get_remote_addr( target_pid, linker_path, (void *)dlsym );    \n    dlclose_addr = (void*)get_remote_addr( target_pid, linker_path, (void *)dlclose );    \n    dlerror_addr = (void*)get_remote_addr( target_pid, linker_path, (void *)dlerror );    \n    \n    LOGD(\"[+] Get imports: dlopen: %p, dlsym: %p, dlclose: %p, dlerror: %p\\n\",    \n            dlopen_addr, dlsym_addr, dlclose_addr, dlerror_addr);    \n    \n    printf(\"library path = %s\\n\", library_path);\n    ptrace_writedata(target_pid, (uint8_t *)map_base, (uint8_t *)library_path, strlen(library_path) + 1);\n    \n    parameters[0] = map_base;       \n    parameters[1] = RTLD_NOW| RTLD_GLOBAL;     \n    \n    if (ptrace_call_wrapper(target_pid, \"dlopen\", dlopen_addr, parameters, 2, &regs) == -1)    \n        goto exit;    \n    \n    uint32_t sohandle = (uint32_t)ptrace_retval(&regs);    \n    \n#define FUNCTION_NAME_ADDR_OFFSET       0x100    \n    ptrace_writedata(target_pid, (uint8_t *)(map_base + FUNCTION_NAME_ADDR_OFFSET), (uint8_t *)function_name, strlen(function_name) + 1);    \n    parameters[0] = sohandle;       \n    parameters[1] = map_base + FUNCTION_NAME_ADDR_OFFSET;     \n    \n    if (ptrace_call_wrapper(target_pid, \"dlsym\", dlsym_addr, parameters, 2, &regs) == -1)    \n        goto exit;    \n    \n    void * hook_init_addr = (void *)ptrace_retval(&regs);    \n    LOGD(\"hook_init_addr = %p\\n\", hook_init_addr);    \n    \n#define FUNCTION_PARAM_ADDR_OFFSET      0x200    \n    ptrace_writedata(target_pid, (uint8_t *)(map_base + FUNCTION_PARAM_ADDR_OFFSET), (uint8_t *)param, strlen(param) + 1);    \n    parameters[0] = map_base + FUNCTION_PARAM_ADDR_OFFSET;\n  \n    if (ptrace_call_wrapper(target_pid, \"init_func\", hook_init_addr, parameters, 1, &regs) == -1)\n        goto exit;        \n    \n#if 0\n    printf(\"Press enter to dlclose and detach\\n\");\n    getchar();\n    parameters[0] = sohandle;       \n    \n    if (ptrace_call_wrapper(target_pid, \"dlclose\", dlclose, parameters, 1, &regs) == -1)    \n        goto exit;    \n#endif\n    \n    /* restore */    \n\tprintf(\"detach\\n\");\n    ptrace_setregs(target_pid, &original_regs);    \n    ptrace_detach(target_pid);    \n    ret = 0;    \n    \nexit:    \n    return ret;    \n}    \n\nstatic int get_all_tids(pid_t pid, pid_t *tids)\n{\n    char dir_path[32];\n    DIR *dir;\n    int i;\n    struct dirent *entry;\n    pid_t tid;\n\n    if (pid < 0) {\n        snprintf(dir_path, sizeof(dir_path), \"/proc/self/task\");\n    }\n    else {\n        snprintf(dir_path, sizeof(dir_path), \"/proc/%d/task\", pid);\n    }\n\n    dir = opendir(dir_path);\n    if (dir == NULL) {\n        return 0;\n    }\n\n    i = 0;\n    while((entry = readdir(dir)) != NULL) {\n        tid = atoi(entry->d_name);\n        if (tid != 0 && tid != getpid()) {\n            tids[i++] = tid;\n        }\n    }\n    closedir(dir);\n    return i;\n}\n\n\n\nint main(int argc, char *argv[])\n{\n    if(argc != 2) {\n        printf(\"Usage: %s <pid to be traced>\\n\", argv[0]);\n        return 1;\n    }\n                                                                                                     \n    pid_t pid;\n    pid_t tids[1024];\n    int status;\n    pid = atoi(argv[1]);\n    int i = 0;\n\n    char* so_path = \"/data/local/tmp/libinject.so\";\n    char* init_func = \"init_func\";\n    char* parameter = \"init_func called, initializing\";\n\n\n#if 0\n    if(0 != ptrace(PTRACE_ATTACH, pid, NULL, NULL)) {\n        printf(\"Trace process failed:%d.\\n\", errno);\n        return 1;\n    }\n\n    \n    waitpid(pid, &status, WUNTRACED);\n#endif\n    \n\n#if 0\n\n    int count = get_all_tids(pid, tids);\n\n    for (i = 0; i < count; ++i) {\n        if (tids[i] == pid)\n            continue;\n        if (ptrace(PTRACE_ATTACH, tids[i], NULL, NULL) == 0) {\n            waitpid(tids[i], &status, WUNTRACED);\n            struct pt_regs regs;\n            ptrace(PTRACE_GETREGS, tids[i], NULL, &regs);\n        }\n    }\n#endif\n\n#if 0\n    uint32_t entry_addr = get_entry_addr(\"libc.so\", 0x11640);\n    uint32_t hook_func = get_hook_func();\n    _hook(&eph1, entry_addr, (void*)hook_func);\n#endif\n\n\n#if 0\n    struct pt_regs regs;\n    if (ptrace(PTRACE_GETREGS, pid, NULL, &regs) < 0) {\n        perror(\"ptrace_getregs: Can not get register values\");\n    }\n    \n    \n#ifdef __i386__\n    regs.eip = 0x00;\n    printf(\"regs.eax = %x\\n\", regs.eax);\n    printf(\"regs.eip = %x\\n\", regs.eip);\n#elif defined __arm__\n    //regs.ARM_pc = 0x00;\n    printf(\"regs.ARM_r0 = %x\\n\", regs.ARM_r0);\n    printf(\"regs.ARM_pc = %x\\n\", regs.ARM_pc);\n#endif\n\n    ptrace_setregs(pid, &regs);\n#endif\n    \n#if 1\n    inject_remote_process(pid, so_path, init_func, parameter, strlen(parameter));\n#endif\n\n#if 0\n    for (i = 0; i < count; ++i) {\n        printf(\"releasing [%d]\\n\", tids[i]);\n        ptrace(PTRACE_CONT, tids[i], NULL, 0);\n        ptrace(PTRACE_DETACH, tids[i], NULL, 0);\n    }\n#endif\n    return 0;\n}\n"
  },
  {
    "path": "jni/target.c",
    "content": "#include <stdio.h>\n#include <time.h>\n#include <dlfcn.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\nint main(){\n    srand(time(NULL));\n    int j = 0;\n    scanf(\"%d\", &j);\n    j = 0;\n    //dlopen(\"/data/local/tmp/libinject.so\", RTLD_NOW);\n    while(1) {\n        j++;\n        sleep(1);\n        printf(\"hello world: %d\\n\",rand()%100);\n\n        if (j == 5) {\n            void* p = malloc(100);\n            int i = 0;\n            for (i = 0 ; i < 100 ; i++) {\n                ((int*)p)[i] = i*i;\n                //printf(\"p[i]: %d\\n\", ((int*)p)[i]);\n            }\n        }\n    }\n    return 0;\n}\n"
  },
  {
    "path": "push.cmd",
    "content": "adb push libs/armeabi-v7a/librealinject.so /data/local/tmp\nadb push libs/x86/stalker /data/local/tmp\nadb push libs/x86/libinject.so /data/local/tmp\n"
  }
]