[
  {
    "path": ".appveyor.yml",
    "content": "os:\n  - Visual Studio 2015\n\nplatform: x64\n  - x64\n\nbranches:\n  only:\n    - master\n   \ninstall:\n  - git submodule update --init --recursive\n  - set PATH=C:\\Program Files\\CMake\\bin;%PATH%\n\nbuild:\n  verbosity: detailed\n\nconfiguration:\n  - Release\n  \nenvironment:\n  artifactName: $(APPVEYOR_PROJECT_NAME)-$(APPVEYOR_REPO_COMMIT)-$(CONFIGURATION)\n  matrix:\n    - env_arch: \"x64\"\n      QT5: C:\\Qt\\5.11\\msvc2015_64\n    - env_arch: \"x86\"\n      QT5: C:\\Qt\\5.11\\msvc2015\n\nbefore_build:\n  - set PATH=%PATH%;%QT5%\\bin;%QT5%\\lib\\cmake\n  - set Qt5Core_DIR=%QT5%\n  - mkdir build\n  - cd build\n  - if [%env_arch%]==[x64] (\n    cmake .. -A x64 )\n  - if [%env_arch%]==[x86] (\n    cmake .. )\n    \nbuild_script:\n  - cmake --build . --config %CONFIGURATION%\n  \nafter_build:\n  - mkdir %artifactName%\n  - cp -r patcher/%CONFIGURATION%/* %artifactName%\n  - cp %QT5%\\bin\\Qt5Core.dll %artifactName%\n  - cp %QT5%\\bin\\Qt5Gui.dll %artifactName%\n  - cp %QT5%\\bin\\Qt5Widgets.dll %artifactName%\n  - mkdir %artifactName%\\platforms\n  - mkdir %artifactName%\\styles\n  - mkdir %artifactName%\\imageformats\n  - cp %QT5%\\plugins\\platforms\\qwindows.dll %artifactName%\\platforms\n  - cp %QT5%\\plugins\\styles\\qwindowsvistastyle.dll %artifactName%\\styles\n  - cp %QT5%\\plugins\\imageformats\\qico.dll %artifactName%\\imageformats\n  \nartifacts:\n- path: build\\%artifactName%\n"
  },
  {
    "path": ".gitignore",
    "content": "build/\n\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"bearparser\"]\n\tpath = bearparser\n\turl = https://github.com/hasherezade/bearparser.git\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: cpp\nsudo: true\n\nos:\n  - linux\n    \ncompiler:\n  - gcc\n  - clang\n\naddons:\n  apt:\n    packages:\n      - qt5-default\n      - qt5-qmake\n\nbefore_script:\n  - cmake --version\n  - qmake -v\n\nscript:\n  - mkdir build\n  - cd build\n  - mkdir $(pwd)/out\n  - cmake -DCMAKE_INSTALL_PREFIX:PATH=$(pwd)/out ..\n  - cmake --build . --target install\n\n"
  },
  {
    "path": "CMakeLists.txt",
    "content": "cmake_minimum_required (VERSION 2.8)\nproject (IAT_Patcher)\n\n# modules:\nset ( M_BEARPARSER \"bearparser/parser\" )\nset ( M_IATP \"patcher\" )\n\n# modules paths:\nset (PARSER_DIR \"${CMAKE_SOURCE_DIR}/${M_BEARPARSER}\" CACHE PATH \"BearParser main path\")\nset (PARSER_INC \"${PARSER_DIR}/include\" CACHE PATH \"BearParser include path\")\n\nset (IATP_DIR \"${CMAKE_SOURCE_DIR}/${M_IATP}\" CACHE PATH \"IATPatcher main path\")\n\n# Add sub-directories\n#\n# libs\nadd_subdirectory (${M_BEARPARSER})\nset (PARSER_LIB bearparser CACHE FILE \"BearParser library path\")\n\n# executables\nadd_subdirectory(patcher)\n\n# dependencies\nadd_dependencies(IAT_Patcher bearparser)\n\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright (c) 2014-2016, hasherezade <hasherezade@gmail.com>\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n"
  },
  {
    "path": "README.md",
    "content": "IAT patcher \n==========\n\n[![Build status](https://ci.appveyor.com/api/projects/status/dv42sbge09b3i77h?svg=true)](https://ci.appveyor.com/project/hasherezade/iat-patcher)\n[![Build status](https://travis-ci.org/hasherezade/IAT_patcher.svg?branch=master)](https://travis-ci.org/hasherezade/IAT_patcher)\n[![Codacy Badge](https://api.codacy.com/project/badge/Grade/e5a1d1892c2642faba08d678c0a6fbf6)](https://www.codacy.com/manual/hasherezade/IAT_patcher?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=hasherezade/IAT_patcher&amp;utm_campaign=Badge_Grade)\n[![Total alerts](https://img.shields.io/lgtm/alerts/g/hasherezade/IAT_patcher.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/hasherezade/IAT_patcher/alerts/)\n[![GitHub release](https://img.shields.io/github/release/hasherezade/IAT_patcher.svg)](https://github.com/hasherezade/IAT_patcher/releases)\n[![Github All Releases](https://img.shields.io/github/downloads/hasherezade/IAT_patcher/total.svg)](https://github.com/hasherezade/IAT_patcher/releases)\n\n**Persistent IAT hooking application (for PE files).**\n\n📖 Read more: http://hasherezade.github.io/IAT_patcher/\n\nPlease report any bugs and remarks to: [issues](https://github.com/hasherezade/IAT_patcher/issues).\n\nRequires:\n+ bearparser: https://github.com/hasherezade/bearparser\n+ Qt5 SDK\n+ Qt5 Core\n+ Qt5 GUI\n+ cmake http://www.cmake.org\n\n## Clone\n\nUse recursive clone to get the repo together with the submodule:\n\n```\ngit clone --recursive https://github.com/hasherezade/IAT_patcher.git\n```\n\n## Autobuild\n\nTo build it on Linux or MacOS you can use the given script - it automatically downloads this repository and all the dependencies:<br/>\n[iatp_autobuild.sh](https://raw.githubusercontent.com/hasherezade/IAT_patcher/master/iatp_autobuild.sh)<br/>\nJust run it, and it will automatically download and build everything.\n\n## Download builds\n\nYou can download the latest stable Windows builds from the [releases](https://github.com/hasherezade/IAT_patcher/releases)\n\n## Sample DLLs\n\nSample DLLs to be used with IAT Patcher can be found in [IAT_patcher_samples](https://github.com/hasherezade/IAT_patcher_samples)\n"
  },
  {
    "path": "build.sh",
    "content": "#!/bin/bash\necho \"Trying to autobuild IAT_patcher...\"\n\n#QT check\n\nQT_VER=`qmake -v`\nstr=$QT_VER\nsubstr=\"Qt version 5\"\n\necho $QT_VER\nif [[ $str == *\"$substr\"* ]]; then\n    echo \"[+] Qt5 found!\"\nelse\n    str2=`whereis qt5`\n    substr2=\"/qt5\"\n    if [[ $str2 == *\"$substr2\"* ]]; then\n        echo \"[+] Qt5 found!\"\n    else\n        echo \"Install Qt5 SDK first\"\n        exit -1\n    fi\nfi\n\nCMAKE_VER=`cmake --version`\nCMAKEV=\"cmake version\"\nif echo \"$CMAKE_VER\" | grep -q \"$CMAKEV\"; then\n    echo \"[+] CMake found!\"\nelse\n    echo \"[-] CMake NOT found!\"\n    echo \"Install cmake first\"\n    exit -1\nfi\n\nmkdir build\necho \"[+] build directory created\"\ncd build\nmkdir $(pwd)/out\ncmake -DCMAKE_INSTALL_PREFIX:PATH=$(pwd)/out ..\ncmake --build . --target install\n\n"
  },
  {
    "path": "iatp_autobuild.sh",
    "content": "#!/bin/bash\necho \"Trying to autobuild IAT_patcher...\"\ngit clone --recursive https://github.com/hasherezade/IAT_patcher.git\necho \"[+] IAT_patcher cloned\"\necho $$\ncd IAT_patcher\nsh build.sh\n\n"
  },
  {
    "path": "patcher/.gitignore",
    "content": "\n"
  },
  {
    "path": "patcher/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.12)\nproject (IAT_Patcher)\n\nmessage (STATUS \"parser_dir='${PARSER_DIR}'\")\nmessage (STATUS \"parser_lib='${PARSER_LIB}'\")\n\n# Find the QtWidgets library\nfind_package(Qt5Widgets)\nfind_package(Qt5Core)\n\ninclude_directories ( ${PARSER_INC} )\n\nset (stub_hdrs\n    stub/Stub.h\n    stub/Stub32.h\n    stub/Stub64.h\n    stub/Stub32Data.h\n    stub/Stub64Data.h\n)\n\nset (dllparse_hdrs\n    dllparse/LibraryParser.h\n    dllparse/LibraryInfo.h\n    dllparse/LibsModel.h\n    dllparse/FunctionsModel.h\n)\n\nset (dllparse_srcs\n    dllparse/LibraryParser.cpp\n    dllparse/LibraryInfo.cpp\n    dllparse/LibsModel.cpp\n    dllparse/FunctionsModel.cpp\n)\n\nset (hdrs\n    StubMaker.h\n    FuncReplacements.h\n    ImportsLookup.h\n    ExeHandler.h\n    Executables.h\n    ExeController.h\n    InfoTableModel.h\n    ImportsTableModel.h\n    FileLoader.h\n    ExeHandlerLoader.h\n    ReplacementsDialog.h\n    mainwindow.h\n    resource.h\n)\n\nset (stub_srcs\n    stub/Stub.cpp\n    stub/Stub32.cpp\n    stub/Stub64.cpp\n)\n\nset (srcs\n    StubMaker.cpp\n    FuncReplacements.cpp\n    ImportsLookup.cpp\n    ExeHandler.cpp\n    Executables.cpp\n    ExeController.cpp\n    InfoTableModel.cpp\n    ImportsTableModel.cpp\n    FileLoader.cpp\n    ExeHandlerLoader.cpp\n    ReplacementsDialog.cpp\n    mainwindow.cpp\n    main.cpp\n)\n\nset (forms \n    mainwindow.ui\n    replacements.ui\n)\n\nset (rcc application.qrc )\nqt5_add_resources(rcc_src ${rcc})\n\nQT5_WRAP_UI (forms_hdrs ${forms})\nQT5_WRAP_CPP (hdrs_moc ${hdrs} ${dllparse_hdrs})\n\nSOURCE_GROUP(\"Source Files\\\\Auto Generated\" FILES ${hdrs_moc} ${rcc_src} )\nSOURCE_GROUP(\"Source Files\\\\stub\" FILES ${stub_srcs} )\nSOURCE_GROUP(\"Header Files\\\\stub\" FILES ${stub_hdrs} )\nSOURCE_GROUP(\"Source Files\\\\dllparse\" FILES ${dllparse_srcs} )\nSOURCE_GROUP(\"Header Files\\\\dllparse\" FILES ${dllparse_hdrs} )\n\nIF (WIN32)\n\tset(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} /SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup\")\nENDIF()\n\nadd_executable (IAT_Patcher IAT_Patcher.rc ${hdrs_moc} ${forms_hdrs} ${stub_srcs} ${stub_hdrs} ${dllparse_hdrs} ${dllparse_srcs} ${hdrs} ${srcs}  ${rcc_src})\n\nINCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})\n\ntarget_link_libraries(IAT_Patcher bearparser Qt5::Core Qt5::Widgets)\n\n# dependencies\nadd_dependencies(IAT_Patcher bearparser)\n\n#install\nINSTALL( TARGETS ${PROJECT_NAME} DESTINATION ${CMAKE_INSTALL_PREFIX} COMPONENT ${PROJECT_NAME} )\n\n\n"
  },
  {
    "path": "patcher/ExeController.cpp",
    "content": "#include \"ExeController.h\"\n\n#include <QFileDialog>\n#include <QMessageBox>\n\nbool ExeController::saveExecutable(ExeHandler* exeHndl, QString newFilename)\n{\n    if (exeHndl == NULL) {\n        return false;\n    }\n\n    Executable *exe = exeHndl->getExe();\n    if (exe == NULL) return false;\n\n    if (AbstractFileBuffer::dump(newFilename, *exe, true) > 0) {\n        exeHndl->onFileSaved(newFilename);\n        emit exeUpdated(exeHndl);\n        return true;\n    }\n    return false;\n}\n\nbool ExeController::hookExecutable(ExeHandler* exeHndl, StubSettings &settings)\n{\n    bool isSuccess = StubMaker::makeStub(exeHndl, settings);\n    //update view even if hooking partialy failed...\n    StubMaker::fillHookedInfo(exeHndl);\n    emit exeUpdated(exeHndl);\n    return isSuccess;\n}\n\nsize_t ExeController::saveReplacementsToFile(ExeHandler* exeHndl, QString fileName)\n{\n    if (fileName.length() == 0) {\n        return 0;\n    }\n    size_t counter = exeHndl->m_Repl.save(fileName);\n    return counter;\n}\n\nsize_t ExeController::loadReplacementsFromFile(ExeHandler* exeHndl, QString fileName)\n{\n    if (fileName.length() == 0) return 0;\n\n    size_t counter = exeHndl->m_Repl.load(fileName);\n    if (counter == 0) {\n        return 0;\n    }\n\n    size_t invalidThunks = exeHndl->m_Repl.dropInvalidThunks(exeHndl->m_FuncMap);\n    counter -= invalidThunks;\n    if (counter != 0) {\n        exeHndl->setUnappliedState(true);\n    }\n    return counter;\n}\n"
  },
  {
    "path": "patcher/ExeController.h",
    "content": "#pragma once\n\n#include <QtWidgets>\n#include \"Executables.h\"\n#include \"StubMaker.h\"\n\nclass ExeController : public QObject\n{\n    Q_OBJECT\npublic:\n    enum EXE_ACTION\n    {\n        ACTION_HOOK = 0,\n        ACTION_SAVE,\n        ACTION_UNLOAD,\n        ACTION_RELOAD,\n        ACTION_EXPORT_REPL,\n        ACTION_IMPORT_REPL,\n        COUNT_ACTION\n    };\n\n    ExeController(QObject* parent = NULL) {}\n    virtual ~ExeController() { }\n\n    bool saveExecutable(ExeHandler* exeHndl, QString newFilename); //throws CustomException\n    bool hookExecutable(ExeHandler* exeHndl, StubSettings &settings); //throws CustomException\n    size_t loadReplacementsFromFile(ExeHandler* exeHndl, QString filename);\n    size_t saveReplacementsToFile(ExeHandler* exeHndl, QString filename);\n\nsignals:\n    void exeUpdated(ExeHandler* exeHndl);\n};\n\n"
  },
  {
    "path": "patcher/ExeHandler.cpp",
    "content": "#include \"ExeHandler.h\"\n\nbool ExeHandler::defineReplacement(offset_t thunk, FuncDesc newFunc)\n{\n    bool ret = m_Repl.defineReplacement(thunk, newFunc);\n    if (ret) hasUnapplied = true;\n    emit stateChanged();\n    return ret;\n}\n"
  },
  {
    "path": "patcher/ExeHandler.h",
    "content": "#pragma once\n#include <QFile>\n#include <bearparser/core.h>\n\n#include \"ImportsLookup.h\"\n#include \"FuncReplacements.h\"\n\nclass ExeHandler : public QObject\n{\nQ_OBJECT\n\nsignals:\n    void stateChanged();\n\npublic:\n    ExeHandler(AbstractByteBuffer *buf, Executable* exe)\n        : m_Buf(buf), m_Exe(exe), isModified(false), hasUnapplied(false),\n        dataStoreRva(INVALID_ADDR)\n    {\n        m_FuncMap.wrap(getImports());\n        originalEP = exe->getEntryPoint();\n        m_fileName = (m_Exe) ? m_Exe->getFileName(): \"\";\n        connect(&m_Repl, SIGNAL(stateChanged()), this, SLOT(onChildStateChanged()));\n    }\n\n    virtual ~ExeHandler() { delete m_Exe, delete m_Buf;}\n    Executable* getExe() { return m_Exe; }\n\n    QString getFileName() { return m_fileName; }\n\n    bool defineReplacement(offset_t thunk, FuncDesc newFunc);\n    FuncDesc getReplAt(offset_t thunk) { return m_Repl.getAt(thunk); }\n    bool hasReplacements() { return m_Repl.size() > 0; }\n\n    ImportDirWrapper* getImports()\n    {\n        MappedExe *mappedExe = dynamic_cast<MappedExe*>(m_Exe);\n        if (mappedExe == NULL) return NULL;\n\n        return dynamic_cast<ImportDirWrapper*>(mappedExe->getWrapper(PEFile::WR_DIR_ENTRY + pe::DIR_IMPORT));\n    }\n\n    void rewrapFuncMap()\n    {\n        this->m_FuncMap.wrap(getImports());\n    }\n    void setHookedState(bool flag) { isHooked = flag; }\n    bool getHookedState() { return isHooked; }\n    bool getModifiedState() { return isModified; }\n    bool getUnappliedState() { return hasUnapplied; }\n\n    offset_t getOriginalEP() { return originalEP; }\n    offset_t getCurrentEP() { return m_Exe->getEntryPoint(); }\n\n    ImportsLookup m_FuncMap;\n    FuncReplacements m_Repl;\n\npublic slots:\n    void onFileSaved(QString newName)\n    {\n        this->m_fileName = newName;\n        this->isModified = false; //modifications are saved\n        emit stateChanged();\n    }\n\nprotected slots:\n    void onChildStateChanged() { emit stateChanged(); }\n\nprotected:\n    void setUnappliedState(bool flag) { hasUnapplied = flag; }\n\n    AbstractByteBuffer *m_Buf;\n    Executable* m_Exe;\n\n    QString m_fileName;\n    bool isModified, hasUnapplied;\n    //TODO: finish and refactor it\n    bool isHooked;\n    offset_t originalEP, dataStoreRva; // TODO: keep params in separate structure\n\nfriend class StubMaker;\nfriend class ExeController;\n};\n"
  },
  {
    "path": "patcher/ExeHandlerLoader.cpp",
    "content": "#include \"ExeHandlerLoader.h\"\n\nbool ExeHandlerLoader::parse(QString &fileName)\n{\n    bool isLoaded = false;\n    ExeHandler *exeHndl = NULL;\n    try {\n        const bufsize_t MINBUF = 0x200;\n        AbstractByteBuffer *buf = new FileBuffer(fileName, MINBUF, false);\n        if (buf == NULL) {\n            return false;\n        }\n        ExeFactory::exe_type exeType = ExeFactory::findMatching(buf);\n        if (exeType == ExeFactory::NONE) {\n            delete buf;\n            return false;\n        }\n\n        Executable *exe = ExeFactory::build(buf, exeType);\n        exeHndl = new ExeHandler(buf, exe);\n        if (exeHndl) {\n            isLoaded = true;\n        }\n\n    } catch (CustomException &e) { }\n\n    emit loaded(exeHndl);\n    return isLoaded;\n}\n//----\n\n"
  },
  {
    "path": "patcher/ExeHandlerLoader.h",
    "content": "#pragma once\n\n#include <QtWidgets>\n#include <QFile>\n#include <bearparser/core.h>\n#include <stdexcept>\n\n#include \"FileLoader.h\"\n#include \"ExeHandler.h\"\n \nclass ExeHandlerLoader : public FileLoader\n{\n    Q_OBJECT\nsignals:\n    void loaded(ExeHandler *exeHndl);\n\npublic:\n    ExeHandlerLoader(QString fileName) : FileLoader(fileName) {}\n    virtual bool parse(QString &fileName);\n};"
  },
  {
    "path": "patcher/Executables.cpp",
    "content": "#include \"Executables.h\"\n#include \"StubMaker.h\"\n\nsize_t Executables::size() { \n    QMutexLocker lock(&m_listMutex); //LOCKER \n    return m_Exes.size(); \n}\n\nExeHandler* Executables::at(size_t index)\n{\n    QMutexLocker lock(&m_listMutex); //LOCKER\n    if (index >= m_Exes.size()) return NULL;\n    return m_Exes.at(index);\n}\n\nbool Executables::_addExe(ExeHandler *exeHndl)\n{\n    if (exeHndl == NULL) return false;\n\n    { //start locked scope\n        QMutexLocker lock(&m_listMutex); //LOCKER\n        m_Exes.push_back(exeHndl);\n    } //end locked scope\n\n    StubMaker::fillHookedInfo(exeHndl);\n    connect(exeHndl, SIGNAL(stateChanged()), this, SLOT(onChildStateChanged()));\n    return true;\n}\n\nbool  Executables::_removeExe(ExeHandler *exe)\n {\n    QMutexLocker lock(&m_listMutex); //LOCKER\n    size_t indx = m_Exes.indexOf(exe);\n    if (indx != -1) {\n        m_Exes.removeAt(indx);\n        return true;\n    }\n    return false;\n }\n\nQStringList Executables::listFiles()\n{\n    QStringList fileNames;\n    QList<ExeHandler*>::iterator itr;\n    QString fileName = \"\";\n\n    QMutexLocker lock(&m_listMutex); //LOCKER\n    for (itr = m_Exes.begin(); itr != m_Exes.end(); itr++) {\n        ExeHandler *exeHndl = (*itr);\n        if (exeHndl->getExe() != NULL) {\n            fileName = exeHndl->getFileName();\n            fileNames << fileName;\n        }\n    }\n    return fileNames;\n }\n\nvoid Executables::_clear()\n{\n    QMutexLocker lock(&m_listMutex); //LOCKER\n    QList<ExeHandler*>::iterator itr;\n    for (itr = m_Exes.begin(); itr != m_Exes.end(); itr++) {\n        ExeHandler *exe = (*itr);\n        delete exe;\n    }\n    m_Exes.clear();\n}\n"
  },
  {
    "path": "patcher/Executables.h",
    "content": "#pragma once\n#include <QFile>\n#include <bearparser/core.h>\n\n#include \"ExeHandler.h\"\n\nclass Executables : public QObject\n{\nQ_OBJECT\n\nsignals:\n    void exeListChanged();\n\npublic slots:\n    void addExe(ExeHandler *exe) { if (_addExe(exe)) emit exeListChanged(); }\n    void removeExe(ExeHandler *exe) { if (_removeExe(exe)) emit exeListChanged(); }\n    void clear() { _clear(); emit exeListChanged(); }\n\npublic:\n    size_t size();\n    ExeHandler* at(size_t index);\n\n    QStringList listFiles();\n\nprotected slots:\n    void onChildStateChanged() { emit exeListChanged(); }\n\nprivate:\n    bool _addExe(ExeHandler *exe);\n    bool _removeExe(ExeHandler *exe);\n    void _clear();\n\n    QList<ExeHandler*> m_Exes;\n    QMutex m_listMutex;\n};\n"
  },
  {
    "path": "patcher/FileLoader.cpp",
    "content": "#include \"FileLoader.h\"\n\n#include <stdexcept>\n\nvoid FileLoader::run()\n{\n    QMutexLocker lock(&m_arrMutex);\n    bool parsed = false;\n    try {\n        if (m_FileName == NULL) return;\n        parsed = parse(m_FileName);\n    } catch (...) { }\n\n    if (!parsed) {\n        emit loadingFailed(m_FileName);\n    }\n    emit loaded(m_Buffer);\n}\n\nbool FileLoader::parse(QString &fileName)\n{\n    bufsize_t maxMapSize = FILE_MAXSIZE;\n    bool isLoaded = false;\n    try {\n        const bufsize_t MINBUF = 0x200;\n        m_Buffer = new FileBuffer(fileName, MINBUF, false);\n        isLoaded = true;\n    } catch (CustomException &e) {\n    }\n\n    return isLoaded;\n}\n\n"
  },
  {
    "path": "patcher/FileLoader.h",
    "content": "#pragma once\n\n#include <QtWidgets>\n#include <QFile>\n#include <bearparser/core.h>\n#include <stdexcept>\n\nclass FileLoader : public QThread\n{\n    Q_OBJECT\npublic:\n    FileLoader(QString fileName) :  m_Buffer(NULL), m_Status(false) { m_FileName = fileName; }\n    virtual ~FileLoader() { }\n\nsignals:\n    void loaded(AbstractByteBuffer *buffer);\n    void loadingFailed(QString fileName);\n\nprotected:\n    void run();\n    virtual bool parse(QString &fileName);\n\n    QString m_FileName;\n    bool m_Status;\n\n\nprivate:\n    AbstractByteBuffer *m_Buffer;\n    QMutex m_arrMutex;\n};\n"
  },
  {
    "path": "patcher/FuncReplacements.cpp",
    "content": "#include \"FuncReplacements.h\"\n\nbool FuncReplacements::defineReplacement(offset_t thunk, FuncDesc newFunc)\n{\n    if (_defineReplacement(thunk, newFunc)) {\n        emit stateChanged();\n        return true;\n    }\n    return false;\n}\n\nbool FuncReplacements::undefReplacement(offset_t thunk)\n{\n    if (_undefReplacement(thunk)) {\n        emit stateChanged();\n        return true;\n    }\n    return false;\n}\n\nbool FuncReplacements::_undefReplacement(offset_t thunk)\n{\n    QMap<offset_t, FuncDesc>::Iterator found = m_replacements.find(thunk);\n    bool exist = found != m_replacements.end();\n    if (exist) {\n        m_replacements.erase(found);\n        return true;\n    }\n    return false;\n}\n\nbool FuncReplacements::_defineReplacement(offset_t thunk, FuncDesc newFunc)\n{\n    QMap<offset_t, FuncDesc>::Iterator found = m_replacements.find(thunk);\n    if (newFunc.size() == 0) {\n        return _undefReplacement(thunk);\n    }\n    if (FuncUtil::validateFuncDesc(newFunc) == false) {\n        return false;\n    }\n    m_replacements[thunk] = newFunc;\n    return true;\n}\n\nFuncDesc FuncReplacements::getAt(offset_t thunk)\n{\n    if (hasAt(thunk) == false) return \"\";\n    return m_replacements[thunk];\n}\n\nbool FuncReplacements::hasAt(offset_t thunk)\n{\n    return m_replacements.find(thunk) != m_replacements.end();\n}\n\nsize_t  FuncReplacements::load(QString &fileName)\n{\n    size_t loaded = 0;\n    QFile inputFile(fileName);\n\n    if ( !inputFile.open(QIODevice::ReadOnly) ) {\n        printf(\"Cannot open file!\");\n        return 0;\n    }\n    offset_t thunk = 0;\n    QString thunkStr = \"\";\n    QString funcDesc = \"\";\n\n    QTextStream in(&inputFile);\n    while ( !in.atEnd() ) {\n        QString line = in.readLine();\n        QTextStream(&line) >> thunkStr >> funcDesc;\n        bool isOk = false;\n        thunk = thunkStr.toLongLong(&isOk, 16);\n\n        if (!isOk || !FuncUtil::validateFuncDesc(funcDesc) ) {\n            continue;\n        }\n        if (_defineReplacement(thunk, funcDesc)) loaded++;\n    }\n    inputFile.close();\n\n    if (loaded > 0) {\n        emit stateChanged();\n    }\n    return loaded;\n}\n\nsize_t FuncReplacements::save(QString &fileName)\n{\n    QFile outputFile(fileName);\n    if ( !outputFile.open(QIODevice::WriteOnly | QIODevice::Text) ) return 0;\n\n    QTextStream out(&outputFile);\n    QMap<offset_t, FuncDesc>::iterator itr;\n    size_t counter = 0;\n    for (itr = m_replacements.begin(); itr != m_replacements.end(); itr++) {\n        out << hex << itr.key();\n        out << \" \";\n        out << itr.value();\n        out << '\\n';\n        counter++;\n        \n    }\n    outputFile.close(); \n    return counter;\n}\n\nsize_t FuncReplacements::dropInvalidThunks(ImportsLookup &lookup)\n{\n    size_t invalidThunks = 0;\n    QList<offset_t>::iterator itr;\n    QList<offset_t> thunks = getThunks();\n    for (itr = thunks.begin(); itr != thunks.end(); itr++) {\n        if (lookup.hasThunk(*itr) == false) {\n            invalidThunks++;\n            this->_undefReplacement(*itr);\n        }\n    }\n    if (invalidThunks > 0) {\n        emit stateChanged();\n    }\n    return invalidThunks;\n}\n"
  },
  {
    "path": "patcher/FuncReplacements.h",
    "content": "#pragma once\n#include <QFile>\n#include <bearparser/core.h>\n\n#include \"ImportsLookup.h\"\n\ntypedef QString FuncDesc;\n\nclass FuncUtil {\npublic:\n    static bool validateFuncDesc(FuncDesc library)\n    {\n        int indx = library.lastIndexOf('.');\n        if (indx == -1) {\n            return false;\n        }\n\n        QString libName = library.left(indx);\n        QString funcName = library.mid(indx + 1);\n        if (libName.length() == 0 || funcName == 0) return false;\n        return true;\n    }\n\n    static bool parseFuncDesc(FuncDesc library, QString &libName, QString &funcName)\n    {\n        int indx = library.lastIndexOf('.');\n        if (indx == -1) {\n            //printf(\"Invalid library format!\\n\");\n            return false;\n        }\n\n        libName = library.left(indx);\n        funcName = library.mid(indx + 1);\n        if (libName.length() == 0 || funcName == 0) return false;\n        return true;\n    }\n};\n\nclass FuncReplacements : public QObject\n{\nQ_OBJECT\n\nsignals:\n    void stateChanged();\n\npublic:\n    FuncReplacements() { }\n    ~FuncReplacements() { }\n\n    size_t load(QString &fileName);\n    size_t save(QString &fileName);\n    size_t dropInvalidThunks(ImportsLookup &lookup);\n\n    bool defineReplacement(offset_t thunk, FuncDesc newFunc);\n    bool undefReplacement(offset_t thunk);\n\n    size_t size() { return m_replacements.size(); }\n    QList<offset_t> getThunks() { return m_replacements.keys(); }\n\n    FuncDesc getAt(offset_t thunk);\n    bool hasAt(offset_t thunk);\n\nprotected:\n    bool _undefReplacement(offset_t thunk);\n    bool _defineReplacement(offset_t thunk, FuncDesc newFunc);\n\n    QMap<offset_t, FuncDesc> m_replacements;\n};\n\n"
  },
  {
    "path": "patcher/ImportsLookup.cpp",
    "content": "#include \"ImportsLookup.h\"\n\nvoid ImportsLookup::wrap(ImportDirWrapper* imports)\n{\n    m_Thunks.clear();\n    m_Imports = imports;\n    if (m_Imports != NULL) {\n        m_Thunks = m_Imports->getThunksList();\n    }\n    wrapFunctions();\n}\n\nbool ImportsLookup::hasLib(QString libName)\n{\n    libName = libName.toUpper();\n    QMap<QString, FuncToThunk>::iterator itr = m_libs.find(libName);\n    if (itr == m_libs.end()) return false;\n    return true;\n}\n\nbool ImportsLookup::hasFunc(QString funcName)\n{\n    funcName = funcName.toUpper();\n    FuncToThunk::iterator itr = m_func.find(funcName);\n    if (itr == m_func.end()) return false;\n    return true;\n}\n\noffset_t ImportsLookup::findThunk(QString libName, QString funcName)\n{\n    libName = libName.toUpper();\n    funcName = funcName.toUpper();\n\n    QMap<QString, FuncToThunk>::iterator itr = m_libs.find(libName);\n    if (itr == m_libs.end()) return INVALID_ADDR;\n\n    FuncToThunk &func = m_libs[libName];\n    FuncToThunk::iterator itr2 = func.find(funcName);\n    if (itr2 == func.end()) return INVALID_ADDR;\n    return m_func[funcName];\n}\n\n/* protected */\n\nvoid ImportsLookup::wrapFunctions()\n{\n    for (size_t i = 0; i < m_Thunks.size(); i++) {\n        offset_t thunk = m_Thunks[i];\n        if (thunk == 0 || thunk == INVALID_ADDR) continue;\n\n        QString lib = thunkToLibName(thunk);\n        QString func = thunkToFuncName(thunk);\n        addFunc(lib, func, thunk);\n    }\n}\n\nbool ImportsLookup::addFunc(QString libName, QString funcName, offset_t thunk)\n{\n    if (libName.size() == 0 || funcName.size() == 0 || thunk == INVALID_ADDR) return false;\n\n    funcName = funcName.toUpper();\n    libName = libName.toUpper();\n\n    m_libs[libName].insert(funcName, thunk);\n    m_func.insert(funcName, thunk);\n    return true;\n}\n"
  },
  {
    "path": "patcher/ImportsLookup.h",
    "content": "#pragma once\n#include <QFile>\n#include <QMap>\n#include <bearparser/pe.h>\n\ntypedef QMap<QString, offset_t> FuncToThunk;\n\nclass ImportsLookup : public QObject\n{\n    Q_OBJECT\n\npublic:\n    ImportsLookup() { }\n\n    void wrap(ImportDirWrapper* imports);\n\n    QString thunkToLibName(offset_t thunk) { return (m_Imports) ? m_Imports->thunkToLibName(thunk) : \"\"; }\n    QString thunkToFuncName(offset_t thunk) { return (m_Imports) ? m_Imports->thunkToFuncName(thunk) : \"\"; }\n    \n    bool hasThunk(const offset_t &thunk) { return  m_Thunks.contains(thunk); }\n    bool hasLib(QString libName);\n    bool hasFunc(QString funcName);\n    offset_t findThunk(QString libName, QString funcName);\n\n    size_t countLibs() { return m_libs.size(); }\n    size_t countImps() { return (m_Imports == NULL) ? 0 : m_Thunks.size(); }\n    offset_t thunkAt(size_t impNum) { return impNum > m_Thunks.size() ? INVALID_ADDR : m_Thunks.at(impNum); }\n\nprotected:\n    void wrapFunctions();\n    bool addFunc(QString libName, QString funcName, offset_t thunk);\n\n    QMap<QString, FuncToThunk> m_libs;\n    FuncToThunk m_func;\n    QList<offset_t> m_Thunks;\n\n    ImportDirWrapper* m_Imports;\n};\n"
  },
  {
    "path": "patcher/ImportsTableModel.cpp",
    "content": "#include \"ImportsTableModel.h\"\n\n#include <QFileDialog>\n#include <QMessageBox>\n\nQVariant ImportsTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n    if (role != Qt::DisplayRole) return QVariant();\n    if (orientation != Qt::Horizontal) return QVariant();\n    switch (section) {\n        case COL_THUNK : return \"Thunk\";\n        case COL_LIB : return \"Lib\";\n        case COL_FUNC : return \"Functions\";\n        case COL_REPLACEMENT : return \"ReplacementFunction\";\n    }\n    return QVariant();\n}\n\nQt::ItemFlags ImportsTableModel::flags(const QModelIndex &index) const\n{\n    if (!index.isValid()) return 0;\n    Qt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n    if (index.column() == COL_REPLACEMENT) {\n        f |= Qt::ItemIsEditable;\n    }\n    return f;\n}\n\nbool ImportsTableModel::setData(const QModelIndex &index, const QVariant &data, int role)\n{\n    if (index.column() != COL_REPLACEMENT) {\n        return false;\n    }\n    //TODO: put it in the controller?\n    offset_t thunk = indexToFunctionThunk(index);\n    QString substName = data.toString();\n    if (this->m_ExeHandler->m_Repl.getAt(thunk) == substName) return false;\n\n    if (this->m_ExeHandler->defineReplacement(thunk, substName) == false) {\n        QMessageBox::warning(NULL, \"Error\", \"Invalid format supplied!\\nValid: <library>.<function>\");\n        return false;\n    }\n    return true;\n}\n\nQVariant ImportsTableModel::data(const QModelIndex &index, int role) const\n{\n    if (this->countElements() == 0 || m_FuncMap == NULL) return QVariant();\n\n    offset_t thunk = indexToFunctionThunk(index);\n    if (thunk == INVALID_ADDR) return QVariant();\n\n    if (role == Qt::UserRole) {\n        return qint64(thunk);\n    }\n\n    if (role != Qt::DisplayRole && role != Qt::EditRole) return QVariant();\n    int attribute = index.column();\n    switch (attribute) {\n        case COL_THUNK : return QString::number(thunk, 16);\n        case COL_LIB : return m_FuncMap->thunkToLibName(thunk);\n        case COL_FUNC : return m_FuncMap->thunkToFuncName(thunk);\n        case COL_REPLACEMENT :\n        {\n            QString replName = this->m_ExeHandler->getReplAt(thunk);\n            return replName;\n        }\n    }\n    return QVariant();\n}\n\n\n"
  },
  {
    "path": "patcher/ImportsTableModel.h",
    "content": "#pragma once\n\n#include <QAbstractTableModel>\n#include <QMenu>\n#include \"Executables.h\"\n\nclass ImportsTableModel : public QAbstractTableModel\n{\n    Q_OBJECT\n\npublic slots:\n    void modelChanged()\n    { \n        this->beginResetModel(); \n        this->endResetModel();\n    }\n\npublic:\n    enum COLS\n    {\n        COL_THUNK = 0,\n        COL_LIB,\n        COL_FUNC,\n        COL_REPLACEMENT,\n        COUNT_COL\n    };\n    ImportsTableModel(QObject *v_parent)\n        : QAbstractTableModel(v_parent), m_ExeHandler(NULL), m_FuncMap(NULL) {}\n\n    virtual ~ImportsTableModel() { }\n\n    QVariant headerData(int section, Qt::Orientation orientation, int role) const;\n    Qt::ItemFlags flags(const QModelIndex &index) const;\n\n    int columnCount(const QModelIndex &parent) const { return COUNT_COL; }\n    int rowCount(const QModelIndex &parent) const { return countElements(); }\n\n    QVariant data(const QModelIndex &index, int role) const;\n    bool setData(const QModelIndex &, const QVariant &, int);\n\n    QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const\n    {\n        //no index item pointer\n        return createIndex(row, column);\n    }\n\n    QModelIndex parent(const QModelIndex &index) const { return QModelIndex(); } // no parent\n\npublic slots:\n    void setExecutable(ExeHandler* exeHndl)\n    {\n        //>\n        this->beginResetModel();\n        \n        this->m_FuncMap = NULL;\n        this->m_ExeHandler = exeHndl;\n\n        if (this->m_ExeHandler) {\n            this->m_FuncMap = &(m_ExeHandler->m_FuncMap);\n\n        }\n        this->endResetModel();\n        //<\n    }\n\nprotected slots:\n    void onExeChanged()\n    {\n        //>\n        this->beginResetModel();\n        this->endResetModel();\n        //<\n    }\n\nprotected:\n\n    offset_t indexToFunctionThunk(const QModelIndex &index) const\n    {\n        if (index.isValid() == false) {\n            return INVALID_ADDR;\n        }\n        int impNum = index.row();\n        size_t entriesCount = countElements();\n        if (entriesCount == 0 || impNum >= entriesCount) return INVALID_ADDR;\n        \n        offset_t thunk = this->m_FuncMap->thunkAt(impNum);\n        //printf(\"Thunk = %llx (%x)\\n\", thunk, impNum);\n        return thunk;\n    }\n\n    ExeHandler* m_ExeHandler;\n    ImportsLookup *m_FuncMap;\n    int countElements() const { return (m_FuncMap == NULL) ? 0 : m_FuncMap->countImps(); }\n};\n"
  },
  {
    "path": "patcher/InfoTableModel.cpp",
    "content": "#include \"InfoTableModel.h\"\n#include \"StubMaker.h\"\n\n#include <QtWidgets>\n #include <QIcon>\n\n#define HIGLIHHT_COLOR \"yellow\"\n#define OK_COLOR \"green\"\n#define NOT_OK_COLOR \"red\"\n\nQVariant InfoTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n    {\n    if (role != Qt::DisplayRole) return QVariant();\n    if (orientation != Qt::Horizontal) return QVariant();\n    switch (section) {\n        case COL_NAME : return \"FileName\";\n        case COL_HOOKED: return \"Hooked?\";\n        case COL_RAW_SIZE: return \"RawSize\";\n        case COL_VIRTUAL_SIZE: return \"VirtualSize\";\n        case COL_SECNUM : return \"Sections\";\n        case COL_IMPNUM : return \"Imports\";\n    }\n    return QVariant();\n}\n\nQt::ItemFlags InfoTableModel::flags(const QModelIndex &index) const\n{\n    if (!index.isValid()) return 0;\n    Qt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n\n    if (index.column() == COL_HOOKED) {\n        f |= Qt::ItemIsUserCheckable;\n        f |= Qt::ItemIsEditable;\n    }\n    return f;\n}\n\nbool InfoTableModel::setData(const QModelIndex &index, const QVariant &, int role)\n{\n    if (index.column() == COL_HOOKED) {\n        if ( role == Qt::CheckStateRole) {\n            int id = index.row();\n            if (m_Exes == NULL) return false;\n            emit hookRequested(this->m_Exes->at(id));\n        }\n        return true;\n    }\n    return false;\n}\n\n\nQVariant InfoTableModel::data(const QModelIndex &index, int role) const\n{\n    int elNum = index.row();\n    if (elNum > countElements()) return QVariant();\n\n    int attribute = index.column();\n    if (attribute >= COUNT_COL) return QVariant();\n\n    if (role == Qt::UserRole) {\n        return uint(elNum);\n    }\n\n    ExeHandler *exeHndl = m_Exes->at(elNum);\n    if (exeHndl == NULL) return QVariant();\n    Executable *exe = exeHndl->getExe();\n    if (exe == NULL) return QVariant();\n\n    if (role == Qt::DisplayRole) {\n        return getDisplayData(role, attribute, exeHndl);\n    }\n\n    if (role == Qt::BackgroundColorRole) {\n        if (exeHndl->getUnappliedState() == true) {\n            return QColor(HIGLIHHT_COLOR);\n        }\n        return QVariant();\n    }\n\n    if (role == Qt::DecorationRole && attribute == COL_NAME) {\n        if (exe->isBit32()) return QIcon(\":/icons/app32.ico\");\n        if (exe->isBit64()) return QIcon(\":/icons/app64.ico\");\n    }\n\n    if (role == Qt::CheckStateRole && attribute == COL_HOOKED) {\n        if (exeHndl->getHookedState()) return Qt::Checked;\n        else return Qt::Unchecked;\n    }\n\n    PEFile *pe = dynamic_cast<PEFile*>(exeHndl->getExe());\n    if (pe == NULL) return QVariant();\n\n    if (role == Qt::TextColorRole ) {\n        if (attribute == COL_SECNUM) {\n            if (pe->canAddNewSection()) return QColor(OK_COLOR);\n                return QColor(NOT_OK_COLOR);\n            }\n        if (attribute == COL_IMPNUM) {\n            if (StubMaker::countMissingImports(exeHndl) > 0) return QColor(NOT_OK_COLOR);\n            return QColor(OK_COLOR);\n        }\n        return QVariant();\n    }\n\n    if (role == Qt::ToolTipRole ) {\n        if (attribute == COL_SECNUM) {\n            if (pe->canAddNewSection()) return \"Can add section\";\n            return \"Can NOT add section\";\n        }\n        if (attribute == COL_IMPNUM) {\n            if (StubMaker::countMissingImports(exeHndl) > 0) return \"Needs to add imports\";\n            return \"Can reuse all imports\";\n        }\n        if (attribute == COL_HOOKED) {\n            QString info = exeHndl->getHookedState() ? \"Hooked\": \"Not hooked\";\n            info += \"\\nDefined \"+ QString::number(exeHndl->m_Repl.size()) + \" replacements\";\n            return info;\n        }\n        if (attribute == COL_NAME) {\n            QString epInfo = \"OEP\\t= \"+ QString::number( exeHndl->getOriginalEP(), 16 );\n\n            if (exeHndl->getHookedState()) {\n                epInfo += \"\\nEP \\t= \"+ QString::number( exeHndl->getCurrentEP(), 16 );\n            }\n            return epInfo;\n        }\n        return \"\";\n    }\n    return QVariant();\n}\n\nQVariant InfoTableModel::getDisplayData(int role, int attribute, ExeHandler *exeHndl) const\n{\n    Executable *exe = exeHndl->getExe();\n    if (exe == NULL) return QVariant();\n\n    if (role != Qt::DisplayRole) return QVariant();\n\n    switch (attribute) {\n        case COL_NAME :\n        {\n            QFileInfo inputInfo(exeHndl->getFileName());\n            QString name = inputInfo.fileName();\n            if (exeHndl->getModifiedState() == true) {\n                name = \"* \" + name;\n            }\n            return name;\n        }\n        case COL_RAW_SIZE : return  exe->getMappedSize(Executable::RAW);\n        case COL_VIRTUAL_SIZE : return  exe->getMappedSize(Executable::RVA);\n    }\n\n    PEFile *pe = dynamic_cast<PEFile*>(exeHndl->getExe());\n    if (pe == NULL) return QVariant();\n\n    switch (attribute) {\n        case COL_SECNUM :\n            return qint64(pe->hdrSectionsNum());\n\n        case COL_IMPNUM :\n        {\n            ExeNodeWrapper *wr = dynamic_cast<ExeNodeWrapper*>(pe->getWrapper(PEFile::WR_DIR_ENTRY + pe::DIR_IMPORT));\n            if (!wr) return 0;\n            return qint64(wr->getEntriesCount());\n        }\n        case COL_HOOKED :\n        {\n            return qint64(exeHndl->m_Repl.size());\n        }\n    }\n    return QVariant();\n}\n"
  },
  {
    "path": "patcher/InfoTableModel.h",
    "content": "#pragma once\n\n#include <QAbstractTableModel>\n#include \"Executables.h\"\n\n#include <bearparser/core.h>\n\nclass InfoTableModel : public QAbstractTableModel\n{\n    Q_OBJECT\n\nsignals:\n    void hookRequested(ExeHandler* exe);\n\npublic slots:\n    void modelChanged()\n    {\n        //>\n        this->beginResetModel();\n        this->endResetModel();\n        //<\n    }\n\npublic:\n    enum COLS\n    {\n        COL_NAME = 0,\n        COL_HOOKED,\n        COL_RAW_SIZE,\n        COL_VIRTUAL_SIZE,\n        COL_SECNUM,\n        COL_IMPNUM,\n        COUNT_COL\n    };\n    InfoTableModel(QObject *v_parent)\n        : QAbstractTableModel(v_parent), m_Exes(NULL) {}\n\n    virtual ~InfoTableModel() { }\n\n    QVariant headerData(int section, Qt::Orientation orientation, int role) const;\n    Qt::ItemFlags flags(const QModelIndex &index) const;\n\n    int columnCount(const QModelIndex &parent) const { return COUNT_COL; }\n    int rowCount(const QModelIndex &parent) const { return countElements(); }\n\n    QVariant data(const QModelIndex &index, int role) const;\n    bool setData(const QModelIndex &, const QVariant &, int);\n\n    QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const\n    {\n        //no index item pointer\n        return createIndex(row, column);\n    }\n\n    QModelIndex parent(const QModelIndex &index) const { return QModelIndex(); } // no parent\n\npublic slots:\n    void setExecutables(Executables *exes)\n    {\n        //>\n        this->beginResetModel();\n        if (this->m_Exes != NULL) {\n            //disconnect old\n            QObject::disconnect(this->m_Exes, SIGNAL(exeListChanged()), this, SLOT( onExeListChanged() ) );\n        }\n        this->m_Exes = exes;\n        if (this->m_Exes != NULL) {\n            QObject::connect(this->m_Exes, SIGNAL(exeListChanged()), this, SLOT( onExeListChanged() ) );\n        }\n        this->endResetModel();\n        //<\n    }\nprotected slots:\n    void onExeListChanged()\n    {\n        //>\n        this->beginResetModel();\n        this->endResetModel();\n        //<\n    }\n\nprotected:\n    Executables* m_Exes;\n\n    QVariant getDisplayData(int role, int attribute, ExeHandler *exeHndl) const;\n    int countElements() const { return (m_Exes == NULL)? 0: m_Exes->size(); }\n};\n"
  },
  {
    "path": "patcher/LICENSE",
    "content": "GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>\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    {description}\n    Copyright (C) {year}  {fullname}\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."
  },
  {
    "path": "patcher/README.md",
    "content": "IAT patcher\n============\nMain application source.\n"
  },
  {
    "path": "patcher/ReplacementsDialog.cpp",
    "content": "#include \"ReplacementsDialog.h\"\n\nReplacementsDialog::ReplacementsDialog(QWidget *parent)\n     : QDialog(parent)\n{\n    this->m_uiReplacements = new Ui_Replacements();\n    this->m_uiReplacements->setupUi(this);\n    setAcceptDrops(true);\n\n    m_libsModel = new LibsModel(this->m_uiReplacements->libraryCombo);\n    m_functModel = new FunctionsModel(this->m_uiReplacements->functionCombo);\n\n    this->m_uiReplacements->libraryCombo->setModel(m_libsModel);\n    this->m_uiReplacements->functionCombo->setModel(m_functModel);\n\n    m_libsModel->setLibraries(&m_libInfos);\n    m_functModel->setLibraries(&m_libInfos);\n\n    connect(this->m_uiReplacements->okCancel_buttons, SIGNAL(rejected()), this, SLOT(hide()));\n    connect(this->m_uiReplacements->okCancel_buttons, SIGNAL(accepted()), this, SLOT(requestReplacement()));\n    connect(m_uiReplacements->addLibraryButton, SIGNAL(clicked()), this, SLOT(openLibrary()));\n\n    connect(m_uiReplacements->libraryCombo, SIGNAL(currentIndexChanged(int)), m_functModel, SLOT(on_currentndexChanged(int)));\n    connect(this, SIGNAL(parseLibrary(QString&)), &m_libParser, SLOT(on_parseLibrary(QString&)) );\n    connect(&m_libParser, SIGNAL(infoCreated(LibraryInfo*)), &m_libInfos, SLOT(addElement(LibraryInfo *)) );\n}\n\nvoid ReplacementsDialog::displayFuncToReplace(offset_t thunk, QString libName, QString funcName)\n{\n    this->m_uiReplacements->thunkLabel->setText(QString::number(thunk, 16));\n    this->m_uiReplacements->libToReplaceLabel->setText(libName+\".\"+funcName);\n}\n\nvoid ReplacementsDialog::displayReplacement(QString libName, QString funcName)\n{\n    this->m_uiReplacements->libraryEdit->setText(libName);\n    this->m_uiReplacements->functionEdit->setText(funcName);\n}\n\nvoid ReplacementsDialog::displayReplacement(FuncDesc &desc)\n{\n    QString libName;\n    QString funcName;\n    FuncUtil::parseFuncDesc(desc, libName, funcName);\n    this->displayReplacement(libName, funcName);\n}\n\nQString ReplacementsDialog::getLibName()\n{\n    int tabNum = this->m_uiReplacements->tabWidget->currentIndex();\n\n    switch (tabNum) {\n        case TAB_EDIT :\n            return this->m_uiReplacements->libraryEdit->text();\n        case TAB_CHOSE :\n            return this->m_uiReplacements->libraryCombo->currentText();\n    }\n    return \"\";\n}\n\nQString ReplacementsDialog::getFuncName()\n{\n    int tabNum = this->m_uiReplacements->tabWidget->currentIndex();\n\n    switch (tabNum) {\n        case TAB_EDIT :\n            return this->m_uiReplacements->functionEdit->text();\n        case TAB_CHOSE :\n            return this->m_uiReplacements->functionCombo->currentText();\n    }\n    return \"\";\n}\n\nvoid ReplacementsDialog::openLibrary()\n{\n    QString fileName = QFileDialog::getOpenFileName(\n        this,\n        tr(\"Open executable\"),\n        QDir::homePath(),\n        \"DLL Files (*.dll);;All files (*)\"\n        );\n\n    if (fileName != \"\") {\n        emit parseLibrary(fileName);\n    }\n}\n\nvoid ReplacementsDialog::requestReplacement()\n{\n    emit setReplacement(getLibName(), getFuncName());\n}\n\nvoid ReplacementsDialog::dragEnterEvent(QDragEnterEvent *event)\n{\n    event->accept();\n}\n\nvoid ReplacementsDialog::dropEvent(QDropEvent* ev)\n{\n    this->m_uiReplacements->tabWidget->setCurrentIndex(TAB_CHOSE);\n    QList<QUrl> urls = ev->mimeData()->urls();\n    QList<QUrl>::Iterator urlItr;\n    QCursor cur = this->cursor();\n    this->setCursor(Qt::BusyCursor);\n\n    for (urlItr = urls.begin() ; urlItr != urls.end(); urlItr++) {\n        QString fileName = urlItr->toLocalFile();\n        if (fileName == \"\") continue;\n        emit parseLibrary(fileName);\n    }\n    this->setCursor(cur);\n}\n"
  },
  {
    "path": "patcher/ReplacementsDialog.h",
    "content": "#pragma once\n\n#include <QtWidgets>\n#include <QFile>\n#include <bearparser/core.h>\n\n#include \"Executables.h\"\n#include \"ui_replacements.h\"\n\n#include \"dllparse/LibraryParser.h\"\n#include \"dllparse/LibsModel.h\"\n#include \"dllparse/FunctionsModel.h\"\n\nclass ReplacementsDialog : public QDialog\n{\n    Q_OBJECT\n\nsignals:\n    void setReplacement(QString libName, QString funcName);\n    void parseLibrary(QString &path);\n\npublic:\n    enum TABS\n    {\n        TAB_EDIT = 0,\n        TAB_CHOSE = 1,\n        COUNT_TABS\n    };\n\n    explicit ReplacementsDialog(QWidget *parent = 0);\n    ~ReplacementsDialog() { }\n\n    void displayFuncToReplace(offset_t thunk, QString libName, QString funcName);\n    void displayReplacement(QString libName, QString funcName);\n    void displayReplacement(FuncDesc &desc);\n\n    QString getLibName();\n    QString getFuncName();\n\n    /* events */\n    void dragEnterEvent(QDragEnterEvent *ev);\n    void dropEvent(QDropEvent* ev);\n\nprivate slots:\n    void requestReplacement();\n    void openLibrary();\n\nprivate:\n    Ui_Replacements* m_uiReplacements;\n\n    LibsModel *m_libsModel;\n    FunctionsModel *m_functModel;\n    LibInfos m_libInfos;\n    LibraryParser m_libParser;\n};\n"
  },
  {
    "path": "patcher/StubMaker.cpp",
    "content": "#include \"StubMaker.h\"\n\n#include \"stub/Stub32.h\"\n#include \"stub/Stub64.h\"\n\nconst size_t SEC_PADDING = 10;\n\nsize_t StubMaker::countMissingImports(ImportsLookup &funcMap)\n{\n    QString libName = \"Kernel32.dll\";\n    QStringList funcNames = (QStringList() << \"LoadLibraryA\" << \"GetProcAddress\"); // << \"VirtualProtect\"\n\n    size_t count = 0;\n    for ( size_t i = 0; i < funcNames.size(); i++) {\n        offset_t thunk = funcMap.findThunk(libName, funcNames[i]);\n        if (thunk == INVALID_ADDR) {\n            count++;\n        }\n    }\n    return count;\n}\n\nbool StubMaker::fillHookedInfo(ExeHandler *exeHndl)\n{\n    if (exeHndl == NULL) return false;\n\n    PEFile *pe = static_cast<PEFile*> (exeHndl->getExe());\n    if (pe == NULL) return false;\n\n    offset_t ep = pe->getEntryPoint();\n    offset_t epRaw = pe->convertAddr(ep, Executable::RVA, Executable::RAW);\n    if (epRaw == INVALID_ADDR) return false;\n\n    BufferView epView(pe, epRaw, pe->getContentSize() - epRaw);\n\n    Stub *stub = NULL;\n    if (pe->isBit32()) {\n        stub = new Stub32();\n    } else {\n        stub = new Stub64();\n    }\n\n    bool isContained = stub->containsStub(&epView);\n    exeHndl->setHookedState(isContained);\n\n    if (isContained) {\n        if (stub->readParams(&epView)) {\n            //TODO: fill all the params in exeHndl\n            /*size_t pCnt = stub->getParamsCount();\n            for (size_t id = 0; id< pCnt; id++) {\n                printf(\"[%d] = %llx\\n\", id, stub->getParamValue(id));\n            }*/\n            //TODO: keep stub params in a separate structure\n            exeHndl->originalEP = stub->getParamValue(Stub::OEP);\n            exeHndl->dataStoreRva = stub->getParamValue(Stub::DATA_RVA);\n\n            offset_t dataRva =exeHndl->dataStoreRva;\n            offset_t dataRaw = pe->toRaw(dataRva, Executable::RVA);\n            BufferView dataBuf(pe, dataRaw, pe->getContentSize() - dataRaw);\n            //printf(\"Reading dataStore at = %llx -> %llx\\n\", dataRva, dataRaw);\n            readDataStore(&dataBuf, dataRva, exeHndl->m_Repl);\n            //printf(\"Params OK, OEP = %llx\\n\", exeHndl->originalEP);\n        }\n    }\n    delete stub;\n    return isContained;\n}\n\nStub* StubMaker::makeStub(PEFile *pe)\n{\n    if (pe == NULL) return NULL;\n\n    Stub *stb = NULL;\n    if (pe->isBit32()) {\n        stb = new Stub32();\n    } else {\n        stb  = new Stub64();\n    }\n    return stb;\n}\n\nbool StubMaker::setStubParams(Stub* stb, PEFile *pe, const offset_t newEntry, const offset_t dataRva, ImportsLookup &funcMap)\n{\n    offset_t loadLib = funcMap.findThunk(\"Kernel32.dll\",\"LoadLibraryA\");\n    offset_t getProc = funcMap.findThunk(\"Kernel32.dll\",\"GetProcAddress\");\n    offset_t oldEntry = pe->getEntryPoint();\n\n    stb->setParam(Stub::NEW_EP, newEntry);\n    stb->setParam(Stub::OEP, oldEntry);\n    stb->setParam(Stub::DATA_RVA, dataRva);\n    stb->setParam(Stub::FUNC_LOAD_LIB_RVA, loadLib);\n    stb->setParam(Stub::FUNC_GET_MODULE_RVA, getProc);\n\n    return true;\n}\n\nsize_t StubMaker::calcReplNamesSize(FuncReplacements &funcRepl)\n{\n    const size_t PADDING = 1;\n    size_t requiredLen = PADDING;\n\n    QList<offset_t> thunks = funcRepl.getThunks();\n\n    QList<offset_t>::Iterator itr;\n    for (itr = thunks.begin(); itr != thunks.end(); itr++) {\n        FuncDesc desc = funcRepl.getAt(*itr);\n        requiredLen += desc.size();\n        requiredLen += PADDING;\n    }\n    return requiredLen;\n}\n\nsize_t StubMaker::calcDataStoreSize(FuncReplacements &funcRepl)\n{\n    const size_t ELEMENTS = 4; //libRVA, funcRVA, thunk, EMPTY\n\n    const size_t OFFSETS_SPACE = (funcRepl.size() * ELEMENTS * sizeof(DWORD)) + sizeof(DWORD) * 2;\n    const size_t NAMES_SPACE = calcReplNamesSize(funcRepl);\n\n    const size_t TOTAL_SPACE = OFFSETS_SPACE + NAMES_SPACE;\n    return TOTAL_SPACE;\n}\n\nByteBuffer* StubMaker::makeDataStore(const offset_t dataRva, FuncReplacements &funcRepl)\n{\n    const size_t ELEMENTS = 4; //libRVA, funcRVA, thunk, EMPTY\n\n    const size_t OFFSETS_SPACE = (funcRepl.size() * ELEMENTS * sizeof(DWORD)) + sizeof(DWORD) * 2;\n    const size_t NAMES_SPACE = calcReplNamesSize(funcRepl);\n\n    const size_t TOTAL_SPACE = OFFSETS_SPACE + NAMES_SPACE;\n    char *buffer = new char[TOTAL_SPACE];\n\n    memset(buffer, 0, TOTAL_SPACE);\n    size_t DELTA1 = OFFSETS_SPACE;\n\n    char* namesBuf = &buffer[DELTA1];\n\n    DWORD nameRva = dataRva + DELTA1;\n    QList<offset_t> allThunks = funcRepl.getThunks();\n\n    DWORD *fAddress = (DWORD*) buffer;\n    size_t addrIndx = 0;\n\n    for (int i = 0; i < allThunks.size(); i++) {\n\n        offset_t thunk = allThunks[i];\n        FuncDesc library = funcRepl.getAt(thunk);\n\n        QString libName;\n        QString funcName;\n        if (FuncUtil::parseFuncDesc(library, libName, funcName) == false) {\n            //printf(\"Invalid library format!\\n\");\n            continue;\n        }\n\n        strcpy(namesBuf, libName.toStdString().c_str());\n        fAddress[addrIndx++] = nameRva;\n        size_t libLen = libName.length() + 1;\n        nameRva  += libLen;\n        namesBuf += libLen;\n\n        strcpy(namesBuf, funcName.toStdString().c_str());\n        fAddress[addrIndx++] = nameRva;\n        size_t funcLen = funcName.length() + 1;\n        nameRva += funcLen;\n        namesBuf += funcLen;\n\n        //save thunk:\n        fAddress[addrIndx++] = thunk;\n\n        //add space:\n        fAddress[addrIndx++] = 0;\n    }\n    ByteBuffer *dataBuf = new ByteBuffer((BYTE*) buffer, TOTAL_SPACE, 0);\n    delete []buffer;\n    return dataBuf;\n}\n\nbool StubMaker::readDataStore(AbstractByteBuffer* buf, const offset_t dataRva, FuncReplacements &funcRepl)\n{\n    const offset_t start = dataRva;\n    const size_t unitSize = sizeof(DWORD);\n\n    offset_t valOffset = 0;\n    offset_t value = 0;\n\n    bool isOk = true;\n\n    for (valOffset = 0; isOk ;) {\n        value = buf->getNumValue(valOffset, unitSize, &isOk);\n        valOffset += unitSize;\n\n        if (!isOk || value == 0) break;\n        offset_t dllNameOffset = value - start;\n        QString dllName = buf->getStringValue(dllNameOffset);\n\n        while (isOk) {\n            value = buf->getNumValue(valOffset, unitSize, &isOk);\n            valOffset += unitSize;\n            offset_t funcNameOffset = value - start;\n            if (!isOk || value == 0) break; //end of DLL processing\n\n            value = buf->getNumValue(valOffset, unitSize, &isOk);\n            valOffset += unitSize;\n            if (!isOk || value == 0) break; //end of DLL processing\n            offset_t thunk = value;\n\n            QString funcName = buf->getStringValue(funcNameOffset);\n            //TODO: refactor it...\n            FuncDesc desc = dllName + \".\" + funcName;\n            funcRepl.defineReplacement(thunk, desc);\n        }\n    }\n    return isOk;\n}\n\nbool StubMaker::overwriteDataStore(ExeHandler *exeHndl)\n{\n    if (exeHndl->isHooked == false) return false;\n    PEFile *pe = dynamic_cast<PEFile*>(exeHndl->getExe());\n    if (!pe) return false;\n\n    offset_t dataRva = exeHndl->dataStoreRva;\n    offset_t dataRaw = pe->toRaw(dataRva, Executable::RVA);\n    if (dataRaw == INVALID_ADDR || dataRaw == 0) return false;\n\n    bufsize_t currentSize = pe->getContentSize() - dataRaw;\n    bufsize_t requiredSize = calcDataStoreSize(exeHndl->m_Repl);\n\n    if (requiredSize > currentSize) {\n        bufsize_t dif = requiredSize - currentSize;\n        //perform resising...\n        if (!pe->extendLastSection(dif + SEC_PADDING)) return false;\n    }\n\n    BufferView dataBuf(pe, dataRaw, pe->getContentSize() - dataRaw);\n    dataBuf.fillContent(0);\n    ByteBuffer* newStore = makeDataStore(dataRva, exeHndl->m_Repl);\n    bool isOk = dataBuf.pasteBuffer(0, newStore, false);\n    delete newStore;\n    return isOk;\n}\n\nbool StubMaker::addFunction(PEFile *pe, ImportEntryWrapper* libWr, ImportedFuncWrapper* func, const QString& name, offset_t &storageOffset)\n{\n    if (pe == NULL) return false;\n\n    ImportedFuncWrapper* fWr = dynamic_cast<ImportedFuncWrapper*>(libWr->addEntry(func));\n    if (fWr == NULL) {\n        printf(\"Cannot add function\\n\");\n        return false;\n    }\n\n    offset_t thunkRVA = pe->convertAddr(storageOffset, Executable::RAW, Executable::RVA);\n\n    fWr->setNumValue(ImportedFuncWrapper::THUNK, thunkRVA);\n    fWr->setNumValue(ImportedFuncWrapper::ORIG_THUNK, thunkRVA);\n\n    storageOffset += sizeof(WORD); //add sizeof Hint\n    if (pe->setStringValue(storageOffset, name) == false) {\n        printf(\"Failed to fill lib  name\\n\");\n        return false;\n    }\n    storageOffset += name.length() + 1;\n    return true;\n}\n\nImportEntryWrapper* StubMaker::addLibrary(PEFile *pe, QString name, offset_t &storageOffset)\n{\n    //add new library wrapper:\n    ImportDirWrapper* imports = dynamic_cast<ImportDirWrapper*> (pe->getWrapper(PEFile::WR_DIR_ENTRY + pe::DIR_IMPORT));\n    ImportEntryWrapper* libWr = dynamic_cast<ImportEntryWrapper*> (imports->addEntry(NULL));\n    if (libWr == NULL) return NULL;\n\n    const size_t PADDING = libWr->getSize();\n    storageOffset = imports->getOffset() +  imports->getContentSize() + PADDING;\n\n    offset_t nameOffset = storageOffset;\n\n    if (pe->setStringValue(storageOffset, name) == false) {\n        printf(\"Failed to fill lib  name\\n\");\n        return NULL;\n    }\n    storageOffset += name.length() + PADDING;\n\n    offset_t firstThunk = pe->convertAddr(storageOffset, Executable::RAW, Executable::RVA);\n\n    libWr->setNumValue(ImportEntryWrapper::FIRST_THUNK, firstThunk);\n    libWr->setNumValue(ImportEntryWrapper::ORIG_FIRST_THUNK, firstThunk);\n    libWr->wrap();\n\n    storageOffset += PADDING;\n    offset_t nameRva = pe->convertAddr(nameOffset, Executable::RAW, Executable::RVA);\n    libWr->setNumValue(ImportEntryWrapper::NAME, nameRva);\n\n    return libWr;\n}\n\nbool StubMaker::addMissingFunctions(PEFile *pe, ImportsLookup &funcMap, bool tryReuse)\n{\n    offset_t storageOffset = 0;\n    QString library = \"Kernel32.dll\";\n\n    ImportEntryWrapper* libWr = addLibrary(pe, library, storageOffset);\n    if (libWr == NULL) {\n        //printf(\"Adding library failed!\\n\");\n        return false;\n    }\n    ImportDirWrapper* imports = dynamic_cast<ImportDirWrapper*> (pe->getWrapper(PEFile::WR_DIR_ENTRY + pe::DIR_IMPORT));\n    if (imports == NULL) {\n        printf(\"Cannot fetch imports!\\n\");\n        return false;\n    }\n\n    //TODO: add missing without relying on previous...\n    size_t prevEntry = imports->getEntriesCount() - 2;\n    ImportEntryWrapper* prevWr = dynamic_cast<ImportEntryWrapper*> (imports->getEntryAt(prevEntry));\n    if (prevWr == NULL) return false;\n\n    size_t prevWrCount = prevWr->getEntriesCount();\n    if (prevWrCount == 0) {\n        return false;\n    }\n    ImportedFuncWrapper* prevLast = dynamic_cast<ImportedFuncWrapper*> (prevWr->getEntryAt(prevWrCount - 1));\n    if (prevLast == NULL) return false;\n    //----\n    const size_t fNum = 2;\n    const QString fNames[] = {\"LoadLibraryA\", \"GetProcAddress\" };\n    size_t entrySize = prevLast->getSize();\n\n    storageOffset += (fNum + 1) * entrySize;\n\n    bool isOk = true;\n    for ( size_t i = 0; i < fNum; i++) {\n\n        if (tryReuse && funcMap.findThunk(library, fNames[i]) != INVALID_ADDR) {\n            //Function exist, no need to add...\n            continue;\n        }\n        if (addFunction(pe, libWr, prevLast, fNames[i], storageOffset) == false) {\n            isOk = false;\n            break;\n        }\n    }\n    imports->reloadMapping();\n    return isOk;\n}\n\nbool StubMaker::makeThunksWriteable(PEFile *pe, FuncReplacements* funcRepl)\n{\n    ImportDirWrapper* imps = dynamic_cast<ImportDirWrapper* >( pe->getDataDirEntry(pe::DIR_IMPORT));\n    if (imps == NULL) return false;\n\n    QList<offset_t> thunks = (funcRepl) ? funcRepl->getThunks() : imps->getThunksList();\n    //TODO: optimize it\n\n    for (size_t i = 0; i < thunks.size(); i++) {\n        offset_t thunk = thunks[i];\n        SectionHdrWrapper *sHdr = pe->getSecHdrAtOffset(thunk, Executable::RVA, true);\n        if (sHdr == NULL) continue;\n        DWORD oldCharact = sHdr->getCharacteristics();\n        sHdr->setCharacteristics(oldCharact | 0xC0000000);\n    }\n    return true;\n}\n\nsize_t StubMaker::calcNewImportsSize(PEFile *pe, size_t addedFuncCount)\n{\n    ImportDirWrapper* imports = dynamic_cast<ImportDirWrapper*> (pe->getWrapper(PEFile::WR_DIR_ENTRY + pe::DIR_IMPORT));\n    IMAGE_DATA_DIRECTORY* ddir = pe->getDataDirectory();\n    size_t impDirSize = ddir[pe::DIR_IMPORT].Size;\n    size_t impSize = imports->getContentSize();\n    if (impDirSize > impSize) impSize = impDirSize;\n\n    size_t impNewSize = impSize;\n    impNewSize += sizeof(IMAGE_IMPORT_DESCRIPTOR) * (addedFuncCount + 1); //append new functions + one as padding\n    return impNewSize;\n}\n\nbool StubMaker::makeStub(PEFile *pe, ImportsLookup &funcMap, FuncReplacements &funcRepl, const StubSettings &settings)\n{\n    try {\n        if (pe == NULL) {\n            return false;\n        }\n        ExeNodeWrapper* sec = dynamic_cast<ExeNodeWrapper*>(pe->getWrapper(PEFile::WR_SECTIONS));\n        if (sec == NULL) {\n            return false;\n        }\n\n        bufsize_t startOffset = 0;\n        bufsize_t stubOffset = 0;\n        bufsize_t TABLE_PADDING = 0x100;\n\n        Stub* stb = StubMaker::makeStub(pe);\n\n        size_t stubSize = stb->getSize();\n        bufsize_t stubSectionSize = StubMaker::calcDataStoreSize(funcRepl) + stubSize + TABLE_PADDING;\n\n        bool mustRewriteImports = false;\n        size_t missingCount = StubMaker::countMissingImports(funcMap);\n\n        //Check if adding imports is required\n        if ( missingCount != 0 || (settings.reuseImports == false)) {\n            //TODO: try to add to existing lib...\n            //TODO: if failed: try to add to existing Import Table...\n            //if failed: include import dir in the new section size...\n            mustRewriteImports = true;\n\n            stubOffset = calcNewImportsSize(pe, missingCount) + TABLE_PADDING;\n            stubSectionSize += stubOffset;\n        }\n\n        SectionHdrWrapper *stubHdr = NULL;\n        if (settings.getAddNewSection() && pe->canAddNewSection()) {\n            stubHdr = pe->addNewSection(\"stub\", stubSectionSize);\n            if (!stubHdr) {\n                printf(\"Failed adding section...\\n\");\n            }\n        }\n\n        if (stubHdr == NULL) {\n            stubHdr = pe->getLastSection();\n            if (stubHdr == NULL) {\n                printf(\"Cannot fetch last section!\\n\");\n                return false;\n            }\n\n            // resize section\n            offset_t secROffset = stubHdr->getContentOffset(Executable::RAW, true);\n            startOffset = pe->getContentSize() - secROffset;\n            startOffset += SEC_PADDING;\n            stubHdr = pe->extendLastSection(stubSectionSize + SEC_PADDING);\n            if (stubHdr == NULL) {\n                printf(\"Cannot fetch last section!\\n\");\n                return false;\n            }\n        }\n        DWORD oldCharact = stubHdr->getCharacteristics();\n\n        stubHdr->setCharacteristics(oldCharact | 0xE0000000);\n        stubOffset += startOffset;\n\n        //fetch again after modification...\n        sec = dynamic_cast<ExeNodeWrapper*>(pe->getWrapper(PEFile::WR_SECTIONS));\n\n        if (sec == NULL) {\n            printf(\"Cannot fetch sections wrapper\\n\");\n            return false;\n        }\n        size_t stubSecId = sec->getEntriesCount() - 1;\n        //printf(\"Last section: %d\\n\", stubSecId);\n\n        const offset_t SEC_RVA = stubHdr->getContentOffset(Executable::RVA);\n        //printf(\"Last sectiont RVA = %llx\\n\", SEC_RVA );\n        const offset_t START_RVA  = SEC_RVA + startOffset;\n        //printf(\"Start writing at : %llx\\n\", START_RVA );\n\n        if (mustRewriteImports) {\n            bool added = false;\n            try {\n                if (pe->moveDataDirEntry(pe::DIR_IMPORT, START_RVA, Executable::RVA)) {\n                    added = addMissingFunctions(pe, funcMap, settings.reuseImports);\n                    if (added == false) {\n                        printf(\"Unable to add all the required functions!\\n\");\n                        return false;\n                    }\n                    makeThunksWriteable(pe);\n                    added = true;\n                }\n            } catch (ExeException &e) {\n                printf(\"Not moved, because: %s\\n\", e.what());\n            }\n            if (!added) {\n                printf(\"Unable to add all the required functions#2\\n\");\n                return false;\n            }\n        }\n\n        pe->unbindImports();\n        ImportDirWrapper* imps = dynamic_cast<ImportDirWrapper* >( pe->getDataDirEntry(pe::DIR_IMPORT));\n        funcMap.wrap(imps);\n\n        BufferView* stubSecView = pe->createSectionView(stubSecId);\n        if (stubSecView == NULL) {\n            return false;\n        }\n        size_t DATA_OFFSET = stubOffset + stubSize;\n        offset_t dataRva = SEC_RVA + stubOffset + stubSize;\n        offset_t newEntryPoint = SEC_RVA + stubOffset;\n\n        ByteBuffer* dataStore = StubMaker::makeDataStore(dataRva, funcRepl);\n        if (StubMaker::setStubParams(stb, pe, newEntryPoint, dataRva, funcMap) == false) {\n            printf(\"Making stub failed: loaderStub == NULL\\n\");\n        }\n\n        ByteBuffer *loaderStub = stb->createStubBuffer();\n        delete stb;\n        stb = NULL;\n\n        bool hasAdded = false;\n\n        if (stubSecView->pasteBuffer(stubOffset, loaderStub, false)) {\n            pe->setEntryPoint(newEntryPoint, Executable::RVA);\n            hasAdded = true;\n        } else {\n            printf(\"pasting buffer failed!\\n\");\n        }\n\n        if (hasAdded) {\n            if (stubSecView->pasteBuffer(DATA_OFFSET, dataStore, false)) {\n                printf(\"pasted data\");\n                hasAdded = true;\n            }\n        }\n\n        delete loaderStub;\n        delete dataStore;\n        delete stubSecView;\n\n        return hasAdded;\n\n    } catch (CustomException &e) {\n        printf (\"Not added, because: %s\\n\", e.what());\n    }\n\n    return false;\n}\n"
  },
  {
    "path": "patcher/StubMaker.h",
    "content": "#pragma once\n#include <bearparser/core.h>\n\n#include \"Executables.h\"\n#include \"FuncReplacements.h\"\n#include \"stub/Stub.h\"\n\nclass StubSettings : public QObject\n{\n    Q_OBJECT\npublic:\n    StubSettings() : addNewSection(true), reuseImports(true) {}\n    void setAddNewSection(bool isEnabled) { this->addNewSection = isEnabled; }\n    void setReuseImports(bool isEnabled) { this->reuseImports = isEnabled; }\n\n    bool getAddNewSection() const { return this->addNewSection; }\n    bool getReuseImports() const { return this->reuseImports; }\n\nprotected:\n    bool addNewSection;\n    bool reuseImports;\n\nfriend class StubMaker;\n};\n\nclass StubMaker {\n\npublic:\n    static bool makeStub(ExeHandler *exeHndl, const StubSettings &settings)\n    {\n        if (exeHndl == NULL) return false;\n        bool isOk = false;\n        PEFile *pe = dynamic_cast<PEFile*>(exeHndl->getExe());\n        if (exeHndl->isHooked) {\n            //File already hooked. Overwriting DataStore...\n            isOk = overwriteDataStore(exeHndl);\n        } else {\n            isOk = makeStub(pe, exeHndl->m_FuncMap, exeHndl->m_Repl, settings);\n        }\n        if (isOk) {\n            makeThunksWriteable(pe, &exeHndl->m_Repl);\n            exeHndl->hasUnapplied = false;\n            exeHndl->isModified = true;\n        }\n        exeHndl->rewrapFuncMap();\n        return isOk;\n    }\n\n    static size_t countMissingImports(ExeHandler *exeHndl)\n    {\n        return countMissingImports(exeHndl->m_FuncMap);\n    }\n\n    static bool fillHookedInfo(ExeHandler *exeHndl);\n\nprotected:\n    static Stub* makeStub(PEFile *pe);\n    static bool setStubParams(Stub* stb, PEFile *pe, const offset_t newEntry, const offset_t dataRva, ImportsLookup &funcMap);\n\n    static size_t calcReplNamesSize(FuncReplacements &funcRepl);\n    static size_t calcDataStoreSize(FuncReplacements &funcRepl);\n    static size_t calcNewImportsSize(PEFile *pe, size_t addedFuncCount);\n\n    static ByteBuffer* makeDataStore(const offset_t dataRva, FuncReplacements &funcRepl);\n    static bool readDataStore(AbstractByteBuffer* storeBuf, const offset_t dataRva, FuncReplacements &out_funcRepl);\n    static bool overwriteDataStore(ExeHandler *exeHndl);\n\n//    static ByteBuffer* createStub32(PEFile *peFile, offset_t stubRva, offset_t loadLib, offset_t getProcAddr);\n\n    static size_t countMissingImports(ImportsLookup &funcMap);\n    static bool makeThunksWriteable(PEFile *pe, FuncReplacements* m_funcRepl = NULL);\n\n    static bool makeStub(PEFile *pe, ImportsLookup &funcMap, FuncReplacements &funcRepl, const StubSettings &settings);\n    static bool addMissingFunctions(PEFile *pe, ImportsLookup &funcMap, bool tryReuse);\n\n    static ImportEntryWrapper* addLibrary(PEFile *pe, QString name, offset_t &storageOffset);\n    static bool addFunction(PEFile *pe, ImportEntryWrapper* libWr, ImportedFuncWrapper* func, const QString& name, offset_t &storageOffset);\n\n};\n"
  },
  {
    "path": "patcher/application.qrc",
    "content": "<RCC>\n  <qresource prefix=\"/\">\n    <file>icons/Add.ico</file>\n    <file>icons/DeleteAll.ico</file>\n    <file>icons/Delete.ico</file>\n    <file>icons/reload.ico</file>\n    <file>icons/app32.ico</file>\n    <file>icons/app64.ico</file>\n    <file>icons/apply.ico</file>\n    <file>icons/save_black.ico</file>\n    <file>icons/edit.ico</file>\n    <file>icons/import.ico</file>\n    <file>icons/export.ico</file>\n    <file>favicon.ico</file>\n  </qresource>\n</RCC>\n"
  },
  {
    "path": "patcher/dllparse/FunctionsModel.cpp",
    "content": "#include \"FunctionsModel.h\"\n\n#include <QFileDialog>\n#include <QMessageBox>\n\nint FunctionsModel::countElements() const \n{\n    if (m_LibInfos == NULL) return 0;\n    LibraryInfo *info = m_LibInfos->at(m_libIndex);\n    if (info == NULL) return 0;\n    return info->getFunctionsCount();\n}\n\nQVariant FunctionsModel::headerData(int section, Qt::Orientation orientation, int role) const\n\t{\n\tif (role != Qt::DisplayRole) return QVariant();\n\tif (orientation != Qt::Horizontal) return QVariant();\n\tswitch (section) {\n        case COL_NAME : return \"Library Name\";\n\t}\n\treturn QVariant();\n}\n\nQt::ItemFlags FunctionsModel::flags(const QModelIndex &index) const\n{\n\tif (!index.isValid()) return Qt::NoItemFlags;\n    int elNum = index.row();\n    LibraryInfo *info = m_LibInfos->at(m_libIndex);\n\tif (info == NULL) return Qt::NoItemFlags;\n\n    if (info->isFunctionNamed(elNum))\n\t    return Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n\treturn Qt::NoItemFlags;\n}\n\nbool FunctionsModel::setData(const QModelIndex &index, const QVariant &, int role)\n{\n    return false;\n}\n\nQVariant FunctionsModel::data(const QModelIndex &index, int role) const\n{\n    int elNum = index.row();\n    if (elNum > countElements()) return QVariant();\n\n    int attribute = index.column();\n    if (attribute >= COUNT_COL) return QVariant();\n\n    LibraryInfo *info = m_LibInfos->at(m_libIndex);\n\tif (info == NULL) return QVariant();\n\n    switch (role) {\n        case Qt::DisplayRole: return info->getFuncNameAt(elNum);\n        case Qt::UserRole : return elNum;\n        case Qt::ToolTipRole: \n        {\n            if (!info->isFunctionNamed(elNum)) return \"Not supported\";\n            return \"\";\n        }\n    }\n    return QVariant();\n}\n"
  },
  {
    "path": "patcher/dllparse/FunctionsModel.h",
    "content": "#pragma once\n\n#include <QAbstractTableModel>\n#include <bearparser/core.h>\n\n#include \"LibraryInfo.h\"\n\nclass FunctionsModel : public QAbstractTableModel\n{\n\tQ_OBJECT\n\npublic slots:\n    void modelChanged()\n    {\n        //>\n        this->beginResetModel();\n        this->endResetModel();\n        //<\n    }\n\n    void on_currentndexChanged(int index)\n    {\n        //>\n        this->beginResetModel();\n        m_libIndex = index;\n        this->endResetModel();\n        //<\n    }\n\npublic:\n    enum COLS\n    {\n        COL_NAME = 0,\n        COUNT_COL\n    };\n\n\tFunctionsModel(QObject *v_parent)\n\t\t: QAbstractTableModel(v_parent), m_LibInfos(NULL) {}\n\n\tvirtual ~FunctionsModel() { }\n\n\tQVariant headerData(int section, Qt::Orientation orientation, int role) const;\n\tQt::ItemFlags flags(const QModelIndex &index) const;\n\n\tint columnCount(const QModelIndex &parent) const { return COUNT_COL; }\n\tint rowCount(const QModelIndex &parent) const { return countElements(); }\n\n\tQVariant data(const QModelIndex &index, int role) const;\n\tbool setData(const QModelIndex &, const QVariant &, int);\n\n\tQModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const\n\t{\n\t\t//no index item pointer\n\t\treturn createIndex(row, column);\n\t}\n\n\tQModelIndex parent(const QModelIndex &index) const { return QModelIndex(); } // no parent\n\npublic slots:\n    void setLibraries(LibInfos* exes)\n    {\n        //>\n        this->beginResetModel();\n        if (this->m_LibInfos != NULL) {\n            //disconnect old\n            QObject::disconnect(this->m_LibInfos, SIGNAL(listChanged()), this, SLOT( on_listChanged() ) );\n        }\n        this->m_LibInfos = exes;\n\n        if (this->m_LibInfos != NULL) {\n            QObject::connect(this->m_LibInfos, SIGNAL(listChanged()), this, SLOT( on_listChanged() ) );\n        }\n        this->endResetModel();\n        //<\n    }\n\nprotected slots:\n    void on_listChanged()\n    {\n        //>\n        this->beginResetModel();\n        this->endResetModel();\n        //<\n    }\n\nprotected:\n    int countElements() const;\n\n\tLibInfos* m_LibInfos;\n    size_t m_libIndex;\n};\n"
  },
  {
    "path": "patcher/dllparse/LibraryInfo.cpp",
    "content": "#include \"LibraryInfo.h\"\n\nsize_t LibInfos::size() { \n    QMutexLocker lock(&m_listMutex); //LOCKER \n    return m_Libs.size(); \n}\n\nLibraryInfo* LibInfos::at(size_t index)\n{\n    QMutexLocker lock(&m_listMutex); //LOCKER\n    if (index >= m_Libs.size()) return NULL;\n    return m_Libs.at(index);\n}\n\nbool LibInfos::_addElement(LibraryInfo *hndl)\n{\n    if (hndl == NULL) return false;\n\n    { //start locked scope\n        QMutexLocker lock(&m_listMutex); //LOCKER\n        const QString fileName = hndl->getFileName();\n        if (m_NameToLibInfo.contains(fileName)) {\n            //already exist, reload...\n            LibraryInfo *info = m_NameToLibInfo[fileName];\n            m_Libs.removeOne(info);\n            delete info;\n        }\n        m_Libs.push_back(hndl);\n        m_NameToLibInfo[fileName] = hndl;\n    } //end locked scope\n    connect(hndl, SIGNAL(stateChanged()), this, SLOT(onChildStateChanged()));\n    return true;\n}\n\nbool  LibInfos::_removeElement(LibraryInfo *exe)\n {\n    QMutexLocker lock(&m_listMutex); //LOCKER\n    size_t indx = m_Libs.indexOf(exe);\n    if (indx != -1) {\n        m_Libs.removeAt(indx);\n        return true;\n    }\n    return false;\n }\n\nQStringList LibInfos::listLibs()\n{\n    QStringList fileNames;\n    QList<LibraryInfo*>::iterator itr;\n    QString fileName = \"\";\n\n    QMutexLocker lock(&m_listMutex); //LOCKER\n    for (itr = m_Libs.begin(); itr != m_Libs.end(); itr++) {\n        LibraryInfo *info = (*itr);\n        fileNames << info->getLibName();\n    }\n    return fileNames;\n }\n\nvoid LibInfos::_clear()\n{\n    QMutexLocker lock(&m_listMutex); //LOCKER\n    QList<LibraryInfo*>::iterator itr;\n    for (itr = m_Libs.begin(); itr != m_Libs.end(); itr++) {\n        LibraryInfo *exe = (*itr);\n        delete exe;\n    }\n    m_Libs.clear();\n}\n"
  },
  {
    "path": "patcher/dllparse/LibraryInfo.h",
    "content": "#pragma once\n#include <QFile>\n#include <bearparser/pe.h>\n\nclass FunctionInfo\n{\npublic:\n    FunctionInfo(QString v_name, bool v_isByOrdinal=false)\n        : name(v_name), isByOrdinal(v_isByOrdinal) {}\n    virtual ~FunctionInfo() {}\n\nprotected:\n    QString name;\n    bool isByOrdinal;\nfriend class LibraryInfo;\n};\n\nclass LibraryInfo : public QObject\n{\n    Q_OBJECT\n\nsignals:\n    void stateChanged();\n\npublic:\n    LibraryInfo(QString filename, QObject* parent = NULL) \n        : QObject(parent), fileName(filename)\n    {\n        QFileInfo inputInfo(filename);\n        libName = inputInfo.fileName();\n    }\n\n    ~LibraryInfo() {}\n\n    QString getFileName() { return fileName; }\n    QString getLibName() { return libName; }\n    const QString getFuncNameAt(int i) { if (i > functions.size()) return \"\"; return functions.at(i).name; }\n    bool isFunctionNamed(int i) const { if (i > functions.size()) return false; return !(functions.at(i).isByOrdinal); }\n    size_t getFunctionsCount() const { return functions.size(); }\n\nprotected:\n    QString libName;\n    QString fileName;\n    QList<FunctionInfo> functions;\n\nfriend class LibraryParser;\n};\n\nclass LibInfos : public QObject\n{\nQ_OBJECT\n\nsignals:\n    void listChanged();\n\npublic slots:\n    void addElement(LibraryInfo *info) { if (_addElement(info)) emit listChanged(); }\n    void removeElement(LibraryInfo *info) { if (_removeElement(info)) emit listChanged(); }\n    void clear() { _clear(); emit listChanged(); }\n\npublic:\n    size_t size();\n    LibraryInfo* at(size_t index);\n\n    QStringList listLibs();\n\nprotected slots:\n    void onChildStateChanged() { emit listChanged(); }\n\nprivate:\n    bool _addElement(LibraryInfo *info);\n    bool _removeElement(LibraryInfo *info);\n    void _clear();\n\n    QList<LibraryInfo *> m_Libs;\n    QMap<QString, LibraryInfo*> m_NameToLibInfo;\n    QMutex m_listMutex;\n};\n"
  },
  {
    "path": "patcher/dllparse/LibraryParser.cpp",
    "content": "#include \"LibraryParser.h\"\n\nvoid LibraryParser::on_parseLibrary(QString& fileName)\n{\n    try {\n        FileView *buf = new FileView(fileName);\n\n        ExeFactory::exe_type exeType = ExeFactory::findMatching(buf);\n        if (exeType == ExeFactory::NONE) {\n            delete buf;\n            return;\n        }\n\n        Executable *exe = ExeFactory::build(buf, exeType);\n        makeLibraryInfo(exe, fileName);\n        delete exe;\n        delete buf;\n    } catch (CustomException &e) {\n        printf(\"ERR: %s\\n\", e.what());\n    }\n}\n\nExportDirWrapper* LibraryParser::getExports(Executable* exe)\n{\n    MappedExe *mappedExe = dynamic_cast<MappedExe*>(exe);\n    if (mappedExe == NULL) return NULL;\n    return dynamic_cast<ExportDirWrapper*>(mappedExe->getWrapper(PEFile::WR_DIR_ENTRY + pe::DIR_EXPORT));\n}\n\nvoid LibraryParser::makeLibraryInfo(Executable* exe, QString fileName)\n{\n    if (!exe) return;\n    ExportDirWrapper* exports = getExports(exe);\n    if (!exports) return;\n    size_t entriesCnt = exports->getEntriesCount();\n    if (entriesCnt == 0) return;\n\n    LibraryInfo *info = new LibraryInfo(fileName);\n    for(int i = 0; i < entriesCnt; i++) {\n        ExportEntryWrapper* entry = dynamic_cast<ExportEntryWrapper*>(exports->getEntryAt(i));\n        if (!entry) continue;\n        info->functions.append(FunctionInfo(entry->getName(), entry->isByOrdinal()));\n    }\n    emit infoCreated(info);\n}\n"
  },
  {
    "path": "patcher/dllparse/LibraryParser.h",
    "content": "#pragma once\n#include <QFile>\n#include <bearparser/core.h>\n\n#include \"LibraryInfo.h\"\n\nclass LibraryParser: public QObject\n{\n    Q_OBJECT\nsignals:\n    void infoCreated(LibraryInfo*);\npublic:\n    LibraryParser(QObject* parent = NULL) \n        : QObject(parent) {}\n    ~LibraryParser(){}\n\n    void makeLibraryInfo(Executable* exe, QString fileName);\n    ExportDirWrapper* getExports(Executable* exe);\n\npublic slots:\n    void on_parseLibrary(QString&);\n};\n"
  },
  {
    "path": "patcher/dllparse/LibsModel.cpp",
    "content": "#include \"LibsModel.h\"\n\n#include <QFileDialog>\n#include <QMessageBox>\n#include <QIcon>\n\nQVariant LibsModel::headerData(int section, Qt::Orientation orientation, int role) const\n\t{\n\tif (role != Qt::DisplayRole) return QVariant();\n\tif (orientation != Qt::Horizontal) return QVariant();\n\tswitch (section) {\n        case COL_NAME : return \"Library Name\";\n\t}\n\treturn QVariant();\n}\n\nQt::ItemFlags LibsModel::flags(const QModelIndex &index) const\n{\n\tif (!index.isValid()) return 0;\n\tQt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n\treturn f;\n}\n\nbool LibsModel::setData(const QModelIndex &index, const QVariant &, int role)\n{\n    return false;\n}\n\nQVariant LibsModel::data(const QModelIndex &index, int role) const\n{\n    int elNum = index.row();\n    if (elNum > countElements()) return QVariant();\n\n    int attribute = index.column();\n    if (attribute >= COUNT_COL) return QVariant();\n\n    LibraryInfo *info = m_LibInfos->at(elNum);\n\tif (info == NULL) return QVariant();\n    switch (role) {\n        case Qt::DisplayRole: return info->getLibName();\n        case Qt::ToolTipRole: return info->getFileName();\n        case Qt::UserRole : return elNum;\n    }\n    return QVariant();\n}\n"
  },
  {
    "path": "patcher/dllparse/LibsModel.h",
    "content": "#pragma once\n\n#include <QAbstractTableModel>\n#include <bearparser/core.h>\n\n#include \"LibraryInfo.h\"\n\nclass LibsModel : public QAbstractTableModel\n{\n\tQ_OBJECT\n\npublic slots:\n    void modelChanged()\n    {\n        //>\n        this->beginResetModel();\n        this->endResetModel();\n        //<\n    }\n\npublic:\n    enum COLS\n    {\n        COL_NAME = 0,\n        COUNT_COL\n    };\n\n\tLibsModel(QObject *v_parent)\n\t\t: QAbstractTableModel(v_parent), m_LibInfos(NULL) {}\n\n\tvirtual ~LibsModel() { }\n\n\tQVariant headerData(int section, Qt::Orientation orientation, int role) const;\n\tQt::ItemFlags flags(const QModelIndex &index) const;\n\n\tint columnCount(const QModelIndex &parent) const { return COUNT_COL; }\n\tint rowCount(const QModelIndex &parent) const { return countElements(); }\n\n\tQVariant data(const QModelIndex &index, int role) const;\n\tbool setData(const QModelIndex &, const QVariant &, int);\n\n\tQModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const\n\t{\n\t\t//no index item pointer\n\t\treturn createIndex(row, column);\n\t}\n\n\tQModelIndex parent(const QModelIndex &index) const { return QModelIndex(); } // no parent\n\npublic slots:\n    void setLibraries(LibInfos* exes)\n    {\n        //>\n        this->beginResetModel();\n\n        if (this->m_LibInfos != NULL) {\n            //disconnect old\n            QObject::disconnect(this->m_LibInfos, SIGNAL(listChanged()), this, SLOT( on_listChanged() ) );\n        }\n        this->m_LibInfos = exes;\n\n        if (this->m_LibInfos != NULL) {\n            QObject::connect(this->m_LibInfos, SIGNAL(listChanged()), this, SLOT( on_listChanged() ) );\n        }\n        this->endResetModel();\n        //<\n    }\nprotected slots:\n    void on_listChanged()\n    {\n        //>\n        this->beginResetModel();\n        this->endResetModel();\n        //<\n    }\n\nprotected:\n\tLibInfos* m_LibInfos;\n\n    int countElements() const { return (m_LibInfos == NULL)? 0: m_LibInfos->size(); }\n};\n"
  },
  {
    "path": "patcher/main.cpp",
    "content": "#include \"mainwindow.h\"\n#include <QApplication>\n#include <QtWidgets>\n\n#include <iostream>\n#include <stdio.h>\n\nint main(int argc, char *argv[])\n{\n    Q_INIT_RESOURCE(application);\n    QApplication app(argc, argv);\n    ExeFactory::init();\n\n    MainWindow w;\n    w.show();\n\n    return app.exec();\n}\n"
  },
  {
    "path": "patcher/mainwindow.cpp",
    "content": "#include \"mainwindow.h\"\n\n#include <QFileDialog>\n#include <QMessageBox>\n#include <stdexcept>\n\n#include \"ExeHandlerLoader.h\"\n#include \"ImportsTableModel.h\"\n#include \"StubMaker.h\"\n\nMainWindow::MainWindow(QWidget *parent) :\n    QMainWindow(parent), m_replacementsDialog(NULL), exeController(this),\n    infoModel(NULL), m_libsModel(NULL), m_functModel(NULL),\n    m_ExeSelected(NULL), customMenu(NULL), functionsMenu(NULL)\n{\n    m_ui.setupUi(this);\n    initReplacementsDialog();\n\n    makeCustomMenu();\n    makeFunctionsMenu();\n    makeFileMenu();\n    this->setWindowTitle(\"IAT Patcher v \" + QString(VERSION) + \" Qt\" + QString::number(QT_VER_NUM, 10));\n\n    this->infoModel = new InfoTableModel(m_ui.outputTable);\n    infoModel->setExecutables(&m_exes);\n\n    m_ui.outputTable->setModel(infoModel);\n    m_ui.outputTable->setSortingEnabled(false);\n    m_ui.outputTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);\n    m_ui.outputTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);\n    m_ui.outputTable->verticalHeader()->show();\n\n    m_ui.outputTable->setSelectionBehavior(QAbstractItemView::SelectRows);\n    m_ui.outputTable->setSelectionMode(QAbstractItemView::SingleSelection);\n    m_ui.outputTable->setEditTriggers(QAbstractItemView::NoEditTriggers);\n\n    m_ui.statusBar->addPermanentWidget(&urlLabel);\n    urlLabel.setTextFormat(Qt::RichText);\n    urlLabel.setTextInteractionFlags(Qt::TextBrowserInteraction);\n    urlLabel.setOpenExternalLinks(true);\n    urlLabel.setText(\"<a href=\\\"\"+ QString(SITE_LINK) +\"\\\">\"+SITE_LINK+\"</a>\");\n\n    this->setAcceptDrops(true);\n\n    this->impModel = new ImportsTableModel(m_ui.outputTable);\n    this->m_filteredImpModel = new QSortFilterProxyModel(this);\n    m_filteredImpModel->setDynamicSortFilter(true);\n    m_filteredImpModel->setSourceModel(impModel);\n\n    m_ui.importsTable->setModel(m_filteredImpModel);\n    m_ui.importsTable->setSortingEnabled(true);\n    m_ui.importsTable->setSelectionBehavior(QAbstractItemView::SelectRows);\n    m_ui.importsTable->setSelectionMode(QAbstractItemView::SingleSelection);\n    m_ui.importsTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);\n\n    connect( m_ui.filterLibEdit, SIGNAL( textChanged (const QString &)), this, SLOT( filterLibs(const QString &)) );\n    connect( m_ui.filterProcEdit, SIGNAL( textChanged (const QString &)), this, SLOT( filterFuncs(const QString &)) );\n    m_ui.outputTable->setContextMenuPolicy(Qt::CustomContextMenu);\n    connect(m_ui.outputTable, SIGNAL(customContextMenuRequested(QPoint)), SLOT(customMenuRequested(QPoint)));\n\n    m_ui.importsTable->setContextMenuPolicy(Qt::CustomContextMenu);\n    connect(m_ui.importsTable, SIGNAL(customContextMenuRequested(QPoint)), SLOT(functionsMenuRequested(QPoint)));\n\n    connect( m_ui.outputTable->selectionModel(), SIGNAL( currentRowChanged(QModelIndex,QModelIndex)), this, SLOT( rowChangedSlot(QModelIndex,QModelIndex) ) );\n    connect( this, SIGNAL( exeSelected(ExeHandler*)), impModel, SLOT( setExecutable(ExeHandler*) ) );\n    connect( this, SIGNAL( exeSelected(ExeHandler*)), this, SLOT( refreshExeView(ExeHandler*) ) );\n\n    connect( this, SIGNAL( exeUpdated(ExeHandler*)), impModel, SLOT( setExecutable(ExeHandler*) ) );\n    connect( this, SIGNAL( exeUpdated(ExeHandler*)), infoModel, SLOT( onExeListChanged() ) );\n    connect( &this->exeController, SIGNAL( exeUpdated(ExeHandler*)), this, SLOT( refreshExeView(ExeHandler*)) );\n\n    connect( &this->exeController, SIGNAL(exeUpdated(ExeHandler*)), infoModel, SLOT(onExeListChanged()) );\n\n    connect(&m_LoadersCount, SIGNAL(counterChanged()), this, SLOT(loadingStatusChanged() ));\n    connect(this, SIGNAL(hookRequested(ExeHandler* )), this, SLOT(onHookRequested(ExeHandler* ) ));\n    connect(infoModel, SIGNAL(hookRequested(ExeHandler* )), this, SLOT(onHookRequested(ExeHandler* )) );\n\n    connect(this, SIGNAL(thunkSelected(offset_t)), this, SLOT(setThunkSelected(offset_t)) );\n}\n\nMainWindow::~MainWindow()\n{\n    clear();\n}\n\nvoid MainWindow::initReplacementsDialog()\n{\n    m_replacementsDialog = new ReplacementsDialog(this);\n    connect(m_replacementsDialog, SIGNAL(setReplacement(QString, QString)), this, SLOT(updateReplacement(QString, QString)) );\n    connect(this, SIGNAL(replacementAccepted()), m_replacementsDialog, SLOT(hide()));\n\n}\n\nvoid MainWindow::filterLibs(const QString &str)\n{\n    m_filteredImpModel->setFilterRegExp(QRegExp(str, Qt::CaseInsensitive, QRegExp::FixedString));\n    m_filteredImpModel->setFilterKeyColumn(1);\n}\n\nvoid MainWindow::filterFuncs(const QString &str)\n{\n    m_filteredImpModel->setFilterRegExp(QRegExp(str, Qt::CaseInsensitive, QRegExp::FixedString));\n    m_filteredImpModel->setFilterKeyColumn(2);\n}\n\nvoid MainWindow::refreshExeView(ExeHandler* exe)\n{\n    if (m_ExeSelected == exe) {\n        QString fName = \"\";\n        if (exe) fName = exe->getFileName();\n        this->m_ui.fileEdit->setText(fName);\n    }\n}\n\nvoid MainWindow::loadingStatusChanged()\n{\n    size_t count = m_LoadersCount.getCount();\n    if (count == 0) {\n        this->m_ui.statusBar->showMessage(\"\");\n        return;\n    }\n    QString ending = \"s\";\n    if (count == 1) ending = \"\";\n    this->m_ui.statusBar->showMessage(\"Loading: \" + QString::number(count) + \" file\" + ending);\n}\n\nvoid MainWindow::dropEvent(QDropEvent* ev)\n{\n    QList<QUrl> urls = ev->mimeData()->urls();\n    QList<QUrl>::Iterator urlItr;\n    QCursor cur = this->cursor();\n    this->setCursor(Qt::BusyCursor);\n\n    for (urlItr = urls.begin() ; urlItr != urls.end(); urlItr++) {\n        QString fileName = urlItr->toLocalFile();\n        if (fileName == \"\") continue;\n        if (parse(fileName)) {\n            m_ui.fileEdit->setText(fileName);\n        }\n    }\n    this->setCursor(cur);\n}\n\nvoid MainWindow::closeEvent ( QCloseEvent * event )\n{\n    const size_t loadedCount = this->m_exes.size();\n    if (loadedCount == 0) {\n        event->accept();\n        return;\n    }\n    event->ignore();\n    bool hasModified = false;\n    for (int i = 0; i < loadedCount; i++) {\n        ExeHandler *hndl = this->m_exes.at(i);\n        if (hndl->getModifiedState() || hndl->getUnappliedState()) {\n            hasModified = true;\n            break;\n        }\n    }\n    if (!hasModified) {\n        event->accept();\n        return;\n    }\n    if (QMessageBox::Yes == QMessageBox::question(this, \"Exit confirmation\",\n        \"You made some unsaved changes, do you really want to exit?\", \n        QMessageBox::Yes|QMessageBox::No))\n    {\n        event->accept();\n    }\n}\n\nvoid MainWindow::on_pushButton_clicked()\n{\n    return openExe();\n}\n\nvoid MainWindow::openExe()\n{\n    QString fileName = QFileDialog::getOpenFileName(\n        this,\n        tr(\"Open executable\"),\n        QDir::homePath(),\n        \"Exe Files (*.exe);;DLL Files (*.dll);;All files (*)\"\n        );\n\n    if (fileName != \"\") {\n        this->parse(fileName);\n    }\n}\n\nvoid MainWindow::removeExe(ExeHandler* exe)\n{\n    selectExe(NULL);\n    this->m_exes.removeExe(exe);\n    delete exe;\n    exe = NULL;\n}\n\nvoid MainWindow::on_reloadButton_clicked()\n{\n    QStringList files = this->m_exes.listFiles();\n    clear();\n    QStringList::iterator itr;\n    for (itr = files.begin(); itr != files.end(); itr++) {\n        QString fileName = *itr;\n        this->parse(fileName);\n    }\n}\n\nvoid MainWindow::reloadExe(ExeHandler* exe)\n{\n    QString fName = \"\";\n    if (exe && exe->getExe())\n        fName = exe->getFileName();\n    this->removeExe(exe);\n    this->parse(fName);\n}\n\nvoid MainWindow::saveRequested(ExeHandler* exeHndl)\n{\n    if (exeHndl == NULL) {\n        QMessageBox::warning(this, \"Cannot save!\", \"No executable selected!\");\n        return;\n    }\n\n    Executable *exe = exeHndl->getExe();\n    if (exe == NULL) return;\n\n    if (exeHndl->getUnappliedState()) {\n        QMessageBox::warning(this, \"Unapplied replacements!\",\n            \"The file has unapplied replacements. Hook the file to apply them.\");\n        return;\n\n    }\n    if (exeHndl->getHookedState() == false) {\n\n        QMessageBox::StandardButton reply;\n        reply = QMessageBox::question(this, \"Unhooked file!\",\n            \"You are trying to save unhooked file. Do you really want?\",\n            QMessageBox::Yes | QMessageBox::No\n        );\n\n        if (reply == QMessageBox::No) {\n            return;\n        }\n    }\n    QFileInfo inputInfo(exeHndl->getFileName());\n\n    QString infoStr = \"Save executable as:\";\n    QString fileName = QFileDialog::getSaveFileName(\n        this,\n        infoStr,\n        inputInfo.absoluteDir().path(),\n        \"Exe Files (*.exe);;DLL Files (*.dll);;All files (*)\"\n    );\n    if (fileName.length() == 0) return;\n\n    try {\n        this->exeController.saveExecutable(exeHndl, fileName);\n    }\n    catch (CustomException &e) {\n        QMessageBox::warning(this, \"Error!\", e.getInfo());\n    }\n}\n\nvoid MainWindow::hookExecutable(ExeHandler* exeHndl, StubSettings &settings)\n{\n    if (exeHndl == NULL) return;\n\n    Executable *exe = exeHndl->getExe();\n    if (exe == NULL) return;\n\n    bool isHooked = exeHndl->getHookedState();\n    PEFile *pe = dynamic_cast<PEFile*>(exe);\n    if (pe == NULL) {\n        QMessageBox::warning(this, \"Cannot hook!\", \"It is not a PE File!\");\n        return;\n    }\n    if (isHooked) {\n        if (exeHndl->getUnappliedState() == false) {\n            QMessageBox::information(NULL, \"No changes!\", \"No changes to be applied\");\n            return;\n        }\n        QMessageBox::StandardButton reply;\n        reply = QMessageBox::question(this, \"Already hooked!\",\n            \"This file is already hooked.\\nDo you want to modify the existing stub?\",\n            QMessageBox::Yes | QMessageBox::No\n        );\n\n        if (reply == QMessageBox::No) {\n            return;\n        }\n    }\n\n    if (exeHndl->hasReplacements() == false && exeHndl->getHookedState() == false) {\n        QMessageBox::StandardButton reply;\n        reply = QMessageBox::question(this, \"No replacements!\",\n            \"You haven't defined any replacement functions.\\nDo you really want to add an empty stub?\",\n            QMessageBox::Yes | QMessageBox::No\n        );\n\n        if (reply == QMessageBox::No) {\n            return;\n        }\n    }\n\n    if (!isHooked && pe->canAddNewSection() == false && settings.getAddNewSection()) {\n        QMessageBox::information(this, \"Warning\", \"Cannot add new section in this file!\\nProceed by extending last section...\");\n    }\n    try {\n        if (this->exeController.hookExecutable(exeHndl, settings)) {\n            QMessageBox::information(this, \"Done!\", \"Hooked!\\nNow you can save and test the file!\");\n            return;\n        }\n        else {\n            QMessageBox::warning(this, \"Failed\", \"Cannot hook!\");\n        }\n    }\n    catch (CustomException &e) {\n        QMessageBox::warning(this, \"Error!\", e.getInfo());\n    }\n}\n\nvoid MainWindow::clear()\n{\n    selectExe(NULL);\n    this->m_exes.clear();\n}\n\nvoid MainWindow::on_hookButton_clicked()\n{\n    emit hookRequested(this->m_ExeSelected);\n}\n\nQAction* MainWindow::addExeAction(QMenu *customMenu, QString text, ExeController::EXE_ACTION a)\n{\n    QAction *action = new QAction(text, customMenu);\n    action->setData(a);\n    customMenu->addAction(action);\n    connect(action, SIGNAL(triggered()), this, SLOT(takeAction()));\n    return action;\n}\n\nvoid MainWindow::makeCustomMenu()\n{\n    this->customMenu = new QMenu(this);\n\n    addExeAction(customMenu, \"Hook\", ExeController::ACTION_HOOK)->setIcon(QIcon(\":/icons/apply.ico\"));\n    addExeAction(customMenu, \"Save as...\", ExeController::ACTION_SAVE)->setIcon(QIcon(\":/icons/save_black.ico\"));\n    addExeAction(customMenu, \"Reload\", ExeController::ACTION_RELOAD)->setIcon(QIcon(\":/icons/reload.ico\"));\n    addExeAction(customMenu, \"Unload\", ExeController::ACTION_UNLOAD)->setIcon(QIcon(\":icons/Delete.ico\"));\n    customMenu->addSeparator();\n    addExeAction(customMenu, \"Export replacements\", ExeController::ACTION_EXPORT_REPL)->setIcon(QIcon(\":icons/export.ico\"));\n    addExeAction(customMenu, \"Import replacements\", ExeController::ACTION_IMPORT_REPL)->setIcon(QIcon(\":icons/import.ico\"));\n}\n\nvoid MainWindow::makeFunctionsMenu()\n{\n    this->functionsMenu = new QMenu(this);\n\n    QAction *settingsAction = new QAction(\"Define replacement\", functionsMenu);\n    settingsAction->setIcon(QIcon(\":icons/edit.ico\"));\n    connect(settingsAction, SIGNAL(triggered()), this->m_replacementsDialog, SLOT(show()));\n    functionsMenu->addAction(settingsAction);\n}\n\nvoid MainWindow::makeFileMenu()\n{\n    QMenu *menu = this->m_ui.menuFile;\n\n    QAction *openAction = new QAction(\"Open executable\", menu);\n    openAction->setIcon(QIcon(\":/icons/Add.ico\"));\n    connect(openAction, SIGNAL(triggered()), this, SLOT(openExe()));\n    menu->addAction(openAction);\n\n    addExeAction(menu, \"Hook selected\", ExeController::ACTION_HOOK)->setIcon(QIcon(\":/icons/apply.ico\"));\n    addExeAction(menu, \"Save selected as...\", ExeController::ACTION_SAVE)->setIcon(QIcon(\":/icons/save_black.ico\"));\n}\n\nvoid MainWindow::customMenuRequested(QPoint pos)\n{\n    QTableView *table = this->m_ui.outputTable;\n\n    QModelIndex index = table->indexAt(pos);\n    if (index.isValid() == false) return;\n\n    this->customMenu->popup(table->viewport()->mapToGlobal(pos));\n}\n\nvoid MainWindow::functionsMenuRequested(QPoint pos)\n{\n    QTableView *table = this->m_ui.importsTable;\n    if (table == NULL ) return;\n    if (this->m_ExeSelected == NULL) return;\n\n    QModelIndex index = table->indexAt(pos);\n    if (index.isValid() == false) return;\n\n    bool isOk;\n    long long offset = m_filteredImpModel->data(index, Qt::UserRole).toLongLong(&isOk);\n    m_ThunkSelected = isOk ? offset : INVALID_ADDR;\n    emit thunkSelected(m_ThunkSelected);\n\n    FuncDesc replName = this->m_ExeSelected->getReplAt(m_ThunkSelected);\n    this->m_replacementsDialog->displayReplacement(replName);\n\n    this->functionsMenu->popup(table->viewport()->mapToGlobal(pos));\n}\n\nvoid MainWindow::setThunkSelected(offset_t thunk)\n{\n    QString libName = this->m_ExeSelected->m_FuncMap.thunkToLibName(thunk);\n    QString funcName = this->m_ExeSelected->m_FuncMap.thunkToFuncName(thunk);\n    this->m_replacementsDialog->displayFuncToReplace(thunk, libName, funcName);\n}\n\nvoid MainWindow::updateReplacement(QString libName, QString funcName)\n{\n    QString substName = \"\";\n\n    if (libName.length() != 0 && funcName.length() != 0) {\n        substName = libName + \".\" + funcName;\n    }\n    if (this->m_ExeSelected->m_Repl.getAt(m_ThunkSelected) == substName) {\n        emit replacementAccepted();\n        return;\n    }\n    if (this->m_ExeSelected->defineReplacement(m_ThunkSelected, substName) == false) {\n        QMessageBox::warning(this, \"Error\", \"Invalid replacement definition!\");\n        return;\n    }\n    emit replacementAccepted();\n}\n\nvoid MainWindow::onImportReplacements(ExeHandler* exeHndl)\n{\n    if (exeHndl == NULL) return;\n\n    QString infoStr = \"Import replacements\";\n    QFileInfo inputInfo(exeHndl->getFileName());\n\n    QString fileName = QFileDialog::getOpenFileName(\n        this,\n        infoStr,\n        inputInfo.absoluteDir().path(),\n        \"Config file (*.txt);;Config file (*.cfg);;All files (*)\"\n    );\n    if (fileName.length() == 0) return;\n\n    size_t counter = this->exeController.loadReplacementsFromFile(exeHndl, fileName);\n    if (counter == 0) {\n        QMessageBox::warning(NULL, \"Error!\", \"Cannot import!\");\n        return;\n    }\n\n    if (counter > 0) {\n        QString ending = (counter > 1) ? \"s\" : \" \";\n        QMessageBox::information(NULL, \"Done!\", \"Imported: \" + QString::number(counter) + \" replacement\" + ending);\n        \n    }\n}\n\nvoid MainWindow::onExportReplacements(ExeHandler* exeHndl)\n{\n    if (exeHndl == NULL) return;\n\n    if (exeHndl->hasReplacements() == false) {\n        QMessageBox::warning(NULL, \"Cannot save!\", \"The file have NO replacements defined!\");\n        return;\n    }\n    QString infoStr = \"Save replacements as...\";\n    QFileInfo inputInfo(exeHndl->getFileName());\n\n    QString fileName = QFileDialog::getSaveFileName(\n        this,\n        infoStr,\n        inputInfo.absoluteDir().path(),\n        \"Config file (*.txt);;Config file (*.cfg);;All files (*)\"\n    );\n    if (fileName.length() == 0) return;\n\n    size_t counter = this->exeController.saveReplacementsToFile(exeHndl, fileName);\n    if (counter == 0) {\n        QMessageBox::warning(NULL, \"Error!\", \"Cannot export!\");\n    }\n    else {\n        QString ending = (counter > 1) ? \"s\" : \" \";\n        QMessageBox::information(NULL, \"Done!\", \"Exported: \" + QString::number(counter) + \" replacement\" + ending);\n    }\n}\n\nvoid MainWindow::takeAction()\n{\n    QAction *action = qobject_cast<QAction *>(sender());\n    //TODO : refactor it\n    if (action->data() == ExeController::ACTION_HOOK) {\n        emit hookRequested(this->m_ExeSelected);\n        return;\n    }\n    if (action->data() == ExeController::ACTION_SAVE) {\n        this->saveRequested(this->m_ExeSelected);\n        return;\n    }\n    if (action->data() == ExeController::ACTION_UNLOAD) {\n        this->removeExe(this->m_ExeSelected);\n        return;\n    }\n    if (action->data() == ExeController::ACTION_RELOAD) {\n        this->reloadExe(this->m_ExeSelected);\n        return;\n    }\n    if (action->data() == ExeController::ACTION_IMPORT_REPL) {\n        this->onImportReplacements(this->m_ExeSelected);\n        return;\n    }\n    if (action->data() == ExeController::ACTION_EXPORT_REPL) {\n        this->onExportReplacements(this->m_ExeSelected);\n        return;\n    }\n}\n\nvoid MainWindow::onHookRequested(ExeHandler* exeHndl)\n{\n    StubSettings settings;\n    settings.setAddNewSection(this->m_ui.actionAdd_new_section->isChecked());\n    settings.setReuseImports(this->m_ui.actionAdd_imports->isChecked());\n    QString settingsStr = \"Settings: \";\n    if (settings.getAddNewSection()) {\n        settingsStr += \"add new section ;\";\n    }\n    if (settings.getReuseImports()) {\n        settingsStr += \"reuse imports\";\n    }\n    this->m_ui.statusBar->showMessage(settingsStr);\n    \n    this->hookExecutable(exeHndl, settings);\n}\n\nvoid MainWindow::on_saveButton_clicked()\n{\n    saveRequested(this->m_ExeSelected);\n}\n\nvoid MainWindow::onLoadingFailed(QString fileName)\n{\n    QMessageBox::warning(this, \"Error!\", \"Cannot load the file: \" + fileName);\n}\n\nvoid MainWindow::onLoaderThreadFinished()\n{\n    delete QObject::sender();\n    m_LoadersCount.dec();\n    this->repaint();\n}\n\nvoid MainWindow::rowChangedSlot(QModelIndex curr, QModelIndex prev)\n{\n    bool isOk = false;\n    size_t index =  this->infoModel->data(curr, Qt::UserRole).toUInt(&isOk);\n    if (!isOk) return;\n    ExeHandler *exe = this->m_exes.at(index);\n    selectExe(exe);\n}\n\nbool MainWindow::parse(QString &fileName)\n{\n    if (fileName == \"\") return false;\n\n    QString link = QFile::symLinkTarget(fileName);\n    if (link.length() > 0) fileName = link;\n\n    bufsize_t maxMapSize = FILE_MAXSIZE;\n    try {\n        FileView fileView(fileName, maxMapSize);\n        ExeFactory::exe_type exeType = ExeFactory::findMatching(&fileView);\n        if (exeType == ExeFactory::NONE) {\n            QMessageBox::warning(this, \"Cannot parse!\", \"Cannot parse the file: \\n\"+fileName+\"\\n\\nType not supported.\");\n            return false;\n        }\n\n        ExeHandlerLoader *loader = new ExeHandlerLoader(fileName);\n        QObject::connect(loader, SIGNAL( loaded(ExeHandler*) ), &m_exes, SLOT( addExe(ExeHandler*) ) );\n        QObject::connect(loader, SIGNAL( loadingFailed(QString ) ), this, SLOT( onLoadingFailed(QString ) ) );\n        QObject::connect(loader, SIGNAL(finished()), this, SLOT( onLoaderThreadFinished() ) );\n        //printf(\"Thread started...\\n\");\n        m_LoadersCount.inc();\n        loader->start();\n\n    } catch (CustomException &e) {\n        QMessageBox::warning(this, \"ERROR\", e.getInfo());\n        return false;\n    }\n    return true;\n}\n\nvoid MainWindow::info()\n{\n    int ret = 0;\n    int count = 0;\n    QPixmap p(\":/favicon.ico\");\n    QString msg = \"<b>IAT Patcher</b> - tool for persistent IAT hooking<br/>\";\n    msg += \"author: <a href='\" + QString(MY_SITE_LINK) + \"'>hasherezade</a><br/>\";\n    msg += \"using: Qt\" + QString::number(QT_VER_NUM, 10) + \"<br/><br/>\";\n\n    msg += \"<a href='\" + QString(LICENSE_LINK) + \"'>LICENSE: \" + LICENSE_TYPE + \"</a><br/>\";\n    msg += \"<a href='\" + QString(SITE_LINK) + \"'>Sourcecode & more info</a><br/>\";\n    msg += \"<a href='\" + QString(ISSUES_LINK) + \"'>Report an issue</a>\";\n\n    QMessageBox *msgBox = new QMessageBox(this);\n    msgBox->setAttribute(Qt::WA_DeleteOnClose);\n\n    msgBox->setWindowTitle(\"Info\");\n    msgBox->setTextFormat(Qt::RichText);\n\n    msgBox->setText(msg);\n    msgBox->setAutoFillBackground(true);\n    msgBox->setIconPixmap(p);\n\n    msgBox->setStandardButtons(QMessageBox::Ok);\n    msgBox->exec();\n}\n"
  },
  {
    "path": "patcher/mainwindow.h",
    "content": "#pragma once\n\n#include <QtGui>\n#include <QFile>\n\n#include \"Executables.h\"\n\n#include \"ui_mainwindow.h\"\n#include \"ui_replacements.h\"\n\n#include \"ImportsTableModel.h\"\n#include \"InfoTableModel.h\"\n#include \"ExeController.h\"\n#include \"ReplacementsDialog.h\"\n\n#ifndef QT_VERSION_MAJOR\n#define QT_VER_NUM 5\n#else\n#define QT_VER_NUM QT_VERSION_MAJOR\n#endif\n\n#define VERSION \"0.3.5.4\"\n#define MY_SITE_LINK \"https://hasherezade.net/\"\n#define LICENSE_TYPE \"BSD-2\"\n#define LICENSE_LINK \"https://raw.githubusercontent.com/hasherezade/IAT_patcher/master/LICENSE\"\n#define SITE_LINK \"http://hasherezade.github.io/IAT_patcher/\"\n#define ISSUES_LINK \"https://github.com/hasherezade/IAT_patcher/issues\"\n\nclass ThreadCounter : public QObject\n{\n    Q_OBJECT\n\nsignals:\n    void counterChanged();\n\npublic:\n    ThreadCounter() { counter = 0; }\n\n    void inc()\n    {\n        {\n        QMutexLocker lock(&m_Mutex);\n        counter++;\n        }\n        emit counterChanged();\n    }\n\n    void dec()\n    {\n        {\n        QMutexLocker lock(&m_Mutex);\n        counter--;\n        }\n        emit counterChanged();\n    }\n    size_t getCount()\n    {\n        QMutexLocker lock(&m_Mutex);\n        return counter;\n    }\n\nprotected:\n    size_t counter;\n    QMutex m_Mutex;\n};\n\nclass MainWindow : public QMainWindow\n{\n    Q_OBJECT\n\nsignals:\n    void exeSelected(ExeHandler* exe);\n    void exeUpdated(ExeHandler* exe);\n    void hookRequested(ExeHandler* exe);\n\n    void thunkSelected(offset_t thunk);\n    void replacementAccepted();\n\npublic:\n    explicit MainWindow(QWidget *parent = 0);\n    ~MainWindow();\n\nprotected:\n    /* events */\n    void dragEnterEvent(QDragEnterEvent* ev) { ev->accept(); }\n    void dropEvent(QDropEvent* ev);\n    void closeEvent(QCloseEvent* ev);\n\nprivate slots:\n    void filterLibs(const QString &str);\n    void filterFuncs(const QString &str);\n\n    void takeAction();\n    void loadingStatusChanged();\n    void onLoadingFailed(QString fileName);\n\n    void selectExe(ExeHandler* exe) \n    { \n        m_ExeSelected = exe;\n        emit exeSelected(exe);\n    }\n\n    void refreshExeView(ExeHandler* exe);\n\n    void customMenuRequested(QPoint pos);\n    void functionsMenuRequested(QPoint pos);\n    void onHookRequested(ExeHandler* exeHndl);\n    void updateReplacement(QString libName, QString funcName);\n    void onExportReplacements(ExeHandler* exeHndl);\n    void onImportReplacements(ExeHandler* exeHndl);\n\n    void setThunkSelected(offset_t thunk);\n\n    void onLoaderThreadFinished();\n    void rowChangedSlot(QModelIndex, QModelIndex);\n    void openExe();\n    //---\n    void on_pushButton_clicked();\n    void on_reloadButton_clicked();\n    void on_clearAllButton_clicked() { clear(); }\n    void on_hookButton_clicked();\n    void on_saveButton_clicked();\n\n    void on_actionAbout_triggered() {  info(); }\n\nprivate:\n    void reloadExe(ExeHandler* exe);\n    void removeExe(ExeHandler* exe);\n    void saveRequested(ExeHandler* exeHndl);\n    void hookExecutable(ExeHandler* exeHndl, StubSettings &settings);\n    void info();\n    void clear();\n    bool parse(QString &fileName);\n\n    QAction* addExeAction(QMenu *customMenu, QString text, ExeController::EXE_ACTION a);\n    void makeCustomMenu();\n    void makeFunctionsMenu();\n    void makeFileMenu();\n    void initReplacementsDialog();\n\n    ReplacementsDialog *m_replacementsDialog;\n    QMenu *customMenu, *functionsMenu;\n\n    QSortFilterProxyModel *m_filteredImpModel;\n\n    Ui::MainWindow m_ui;\n\n    ImportsTableModel *impModel;\n    InfoTableModel *infoModel;\n    LibsModel *m_libsModel;\n    FunctionsModel *m_functModel;\n\n    ThreadCounter m_LoadersCount;\n\n    Executables m_exes;\n    ExeHandler* m_ExeSelected;\n    offset_t m_ThunkSelected;\n    QLabel urlLabel;\n\n    ExeController exeController;\n};\n\n\n"
  },
  {
    "path": "patcher/mainwindow.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <author>hasherezade</author>\n <class>MainWindow</class>\n <widget class=\"QMainWindow\" name=\"MainWindow\">\n  <property name=\"windowModality\">\n   <enum>Qt::ApplicationModal</enum>\n  </property>\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>731</width>\n    <height>522</height>\n   </rect>\n  </property>\n  <property name=\"minimumSize\">\n   <size>\n    <width>100</width>\n    <height>300</height>\n   </size>\n  </property>\n  <property name=\"focusPolicy\">\n   <enum>Qt::StrongFocus</enum>\n  </property>\n  <property name=\"windowTitle\">\n   <string>IAT Patcher</string>\n  </property>\n  <property name=\"windowIcon\">\n   <iconset resource=\"application.qrc\">\n    <normaloff>:/favicon.ico</normaloff>:/favicon.ico</iconset>\n  </property>\n  <property name=\"windowOpacity\">\n   <double>1.000000000000000</double>\n  </property>\n  <property name=\"layoutDirection\">\n   <enum>Qt::LeftToRight</enum>\n  </property>\n  <property name=\"autoFillBackground\">\n   <bool>true</bool>\n  </property>\n  <property name=\"tabShape\">\n   <enum>QTabWidget::Rounded</enum>\n  </property>\n  <widget class=\"QWidget\" name=\"centralWidget\">\n   <layout class=\"QGridLayout\" name=\"gridLayout\">\n    <item row=\"0\" column=\"0\">\n     <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n      <property name=\"sizeConstraint\">\n       <enum>QLayout::SetMinAndMaxSize</enum>\n      </property>\n      <item>\n       <layout class=\"QHBoxLayout\" name=\"horizontalLayout_2\">\n        <item>\n         <widget class=\"QLineEdit\" name=\"fileEdit\">\n          <property name=\"readOnly\">\n           <bool>true</bool>\n          </property>\n          <property name=\"placeholderText\">\n           <string>Selected executable</string>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"QPushButton\" name=\"pushButton\">\n          <property name=\"sizePolicy\">\n           <sizepolicy hsizetype=\"Fixed\" vsizetype=\"Fixed\">\n            <horstretch>0</horstretch>\n            <verstretch>0</verstretch>\n           </sizepolicy>\n          </property>\n          <property name=\"toolTip\">\n           <string>Open file</string>\n          </property>\n          <property name=\"text\">\n           <string/>\n          </property>\n          <property name=\"icon\">\n           <iconset resource=\"application.qrc\">\n            <normaloff>:/icons/Add.ico</normaloff>:/icons/Add.ico</iconset>\n          </property>\n          <property name=\"iconSize\">\n           <size>\n            <width>24</width>\n            <height>24</height>\n           </size>\n          </property>\n          <property name=\"default\">\n           <bool>true</bool>\n          </property>\n          <property name=\"flat\">\n           <bool>false</bool>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"QPushButton\" name=\"reloadButton\">\n          <property name=\"sizePolicy\">\n           <sizepolicy hsizetype=\"Fixed\" vsizetype=\"Fixed\">\n            <horstretch>0</horstretch>\n            <verstretch>0</verstretch>\n           </sizepolicy>\n          </property>\n          <property name=\"toolTip\">\n           <string>Reload all</string>\n          </property>\n          <property name=\"text\">\n           <string/>\n          </property>\n          <property name=\"icon\">\n           <iconset resource=\"application.qrc\">\n            <normaloff>:/icons/reload.ico</normaloff>:/icons/reload.ico</iconset>\n          </property>\n          <property name=\"iconSize\">\n           <size>\n            <width>24</width>\n            <height>24</height>\n           </size>\n          </property>\n          <property name=\"default\">\n           <bool>true</bool>\n          </property>\n          <property name=\"flat\">\n           <bool>false</bool>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"QPushButton\" name=\"clearAllButton\">\n          <property name=\"sizePolicy\">\n           <sizepolicy hsizetype=\"Fixed\" vsizetype=\"Fixed\">\n            <horstretch>0</horstretch>\n            <verstretch>0</verstretch>\n           </sizepolicy>\n          </property>\n          <property name=\"toolTip\">\n           <string>Unload all</string>\n          </property>\n          <property name=\"text\">\n           <string/>\n          </property>\n          <property name=\"icon\">\n           <iconset resource=\"application.qrc\">\n            <normaloff>:/icons/DeleteAll.ico</normaloff>:/icons/DeleteAll.ico</iconset>\n          </property>\n          <property name=\"iconSize\">\n           <size>\n            <width>24</width>\n            <height>24</height>\n           </size>\n          </property>\n          <property name=\"default\">\n           <bool>true</bool>\n          </property>\n          <property name=\"flat\">\n           <bool>false</bool>\n          </property>\n         </widget>\n        </item>\n       </layout>\n      </item>\n      <item>\n       <widget class=\"QLabel\" name=\"label_2\">\n        <property name=\"text\">\n         <string>Preview:</string>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QSplitter\" name=\"splitter_2\">\n        <property name=\"orientation\">\n         <enum>Qt::Vertical</enum>\n        </property>\n        <widget class=\"QTableView\" name=\"outputTable\">\n         <property name=\"enabled\">\n          <bool>true</bool>\n         </property>\n         <property name=\"sizePolicy\">\n          <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Preferred\">\n           <horstretch>0</horstretch>\n           <verstretch>0</verstretch>\n          </sizepolicy>\n         </property>\n         <property name=\"autoFillBackground\">\n          <bool>true</bool>\n         </property>\n         <property name=\"frameShape\">\n          <enum>QFrame::StyledPanel</enum>\n         </property>\n         <property name=\"alternatingRowColors\">\n          <bool>true</bool>\n         </property>\n         <property name=\"sortingEnabled\">\n          <bool>true</bool>\n         </property>\n         <attribute name=\"horizontalHeaderStretchLastSection\">\n          <bool>true</bool>\n         </attribute>\n        </widget>\n        <widget class=\"QFrame\" name=\"frame\">\n         <property name=\"sizePolicy\">\n          <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Fixed\">\n           <horstretch>0</horstretch>\n           <verstretch>0</verstretch>\n          </sizepolicy>\n         </property>\n         <property name=\"minimumSize\">\n          <size>\n           <width>0</width>\n           <height>40</height>\n          </size>\n         </property>\n         <property name=\"maximumSize\">\n          <size>\n           <width>16777215</width>\n           <height>38</height>\n          </size>\n         </property>\n         <layout class=\"QHBoxLayout\" name=\"horizontalLayout_4\">\n          <property name=\"spacing\">\n           <number>1</number>\n          </property>\n          <property name=\"bottomMargin\">\n           <number>1</number>\n          </property>\n          <item>\n           <widget class=\"QLineEdit\" name=\"filterLibEdit\">\n            <property name=\"sizePolicy\">\n             <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Fixed\">\n              <horstretch>0</horstretch>\n              <verstretch>0</verstretch>\n             </sizepolicy>\n            </property>\n            <property name=\"acceptDrops\">\n             <bool>false</bool>\n            </property>\n            <property name=\"readOnly\">\n             <bool>false</bool>\n            </property>\n            <property name=\"placeholderText\">\n             <string>Filter libraries</string>\n            </property>\n           </widget>\n          </item>\n          <item>\n           <widget class=\"QLineEdit\" name=\"filterProcEdit\">\n            <property name=\"sizePolicy\">\n             <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Fixed\">\n              <horstretch>0</horstretch>\n              <verstretch>0</verstretch>\n             </sizepolicy>\n            </property>\n            <property name=\"acceptDrops\">\n             <bool>false</bool>\n            </property>\n            <property name=\"readOnly\">\n             <bool>false</bool>\n            </property>\n            <property name=\"placeholderText\">\n             <string>Filter functions</string>\n            </property>\n           </widget>\n          </item>\n         </layout>\n        </widget>\n        <widget class=\"QTableView\" name=\"importsTable\">\n         <property name=\"sizePolicy\">\n          <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Maximum\">\n           <horstretch>0</horstretch>\n           <verstretch>0</verstretch>\n          </sizepolicy>\n         </property>\n         <property name=\"layoutDirection\">\n          <enum>Qt::LeftToRight</enum>\n         </property>\n         <property name=\"autoFillBackground\">\n          <bool>true</bool>\n         </property>\n         <property name=\"alternatingRowColors\">\n          <bool>true</bool>\n         </property>\n         <attribute name=\"horizontalHeaderStretchLastSection\">\n          <bool>true</bool>\n         </attribute>\n        </widget>\n       </widget>\n      </item>\n      <item>\n       <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\"/>\n      </item>\n      <item>\n       <layout class=\"QHBoxLayout\" name=\"horizontalLayout_3\">\n        <item>\n         <widget class=\"QPushButton\" name=\"hookButton\">\n          <property name=\"text\">\n           <string>Hook!</string>\n          </property>\n          <property name=\"icon\">\n           <iconset resource=\"application.qrc\">\n            <normaloff>:/icons/apply.ico</normaloff>:/icons/apply.ico</iconset>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"QPushButton\" name=\"saveButton\">\n          <property name=\"text\">\n           <string>Save</string>\n          </property>\n          <property name=\"icon\">\n           <iconset resource=\"application.qrc\">\n            <normaloff>:/icons/save_black.ico</normaloff>:/icons/save_black.ico</iconset>\n          </property>\n         </widget>\n        </item>\n       </layout>\n      </item>\n     </layout>\n    </item>\n   </layout>\n  </widget>\n  <widget class=\"QMenuBar\" name=\"menuBar\">\n   <property name=\"geometry\">\n    <rect>\n     <x>0</x>\n     <y>0</y>\n     <width>731</width>\n     <height>21</height>\n    </rect>\n   </property>\n   <widget class=\"QMenu\" name=\"menuAbout\">\n    <property name=\"title\">\n     <string>Info</string>\n    </property>\n    <addaction name=\"actionAbout\"/>\n   </widget>\n   <widget class=\"QMenu\" name=\"menuSettings\">\n    <property name=\"title\">\n     <string>Settings</string>\n    </property>\n    <addaction name=\"actionAdd_new_section\"/>\n    <addaction name=\"actionAdd_imports\"/>\n   </widget>\n   <widget class=\"QMenu\" name=\"menuFile\">\n    <property name=\"title\">\n     <string>File</string>\n    </property>\n   </widget>\n   <addaction name=\"menuFile\"/>\n   <addaction name=\"menuSettings\"/>\n   <addaction name=\"menuAbout\"/>\n  </widget>\n  <widget class=\"QStatusBar\" name=\"statusBar\"/>\n  <action name=\"actionAbout\">\n   <property name=\"text\">\n    <string>About</string>\n   </property>\n  </action>\n  <action name=\"actionAdd_new_section\">\n   <property name=\"checkable\">\n    <bool>true</bool>\n   </property>\n   <property name=\"checked\">\n    <bool>true</bool>\n   </property>\n   <property name=\"text\">\n    <string>Add new section</string>\n   </property>\n  </action>\n  <action name=\"actionAdd_imports\">\n   <property name=\"checkable\">\n    <bool>true</bool>\n   </property>\n   <property name=\"checked\">\n    <bool>true</bool>\n   </property>\n   <property name=\"text\">\n    <string>Reuse imports</string>\n   </property>\n  </action>\n  <action name=\"actionOpen\">\n   <property name=\"text\">\n    <string>Open PE</string>\n   </property>\n  </action>\n  <action name=\"actionSave_as\">\n   <property name=\"text\">\n    <string>Save PE as..</string>\n   </property>\n  </action>\n  <action name=\"action\">\n   <property name=\"text\">\n    <string>-</string>\n   </property>\n  </action>\n  <action name=\"actionOpen_hooking_schema\">\n   <property name=\"text\">\n    <string>Open hooking schema</string>\n   </property>\n  </action>\n  <action name=\"actionSave_hooking_schema\">\n   <property name=\"text\">\n    <string>Save hooking schema</string>\n   </property>\n  </action>\n </widget>\n <layoutdefault spacing=\"6\" margin=\"11\"/>\n <resources>\n  <include location=\"application.qrc\"/>\n </resources>\n <connections/>\n <designerdata>\n  <property name=\"gridDeltaX\">\n   <number>10</number>\n  </property>\n  <property name=\"gridDeltaY\">\n   <number>10</number>\n  </property>\n  <property name=\"gridSnapX\">\n   <bool>true</bool>\n  </property>\n  <property name=\"gridSnapY\">\n   <bool>true</bool>\n  </property>\n  <property name=\"gridVisible\">\n   <bool>true</bool>\n  </property>\n </designerdata>\n</ui>\n"
  },
  {
    "path": "patcher/replacements.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>Replacements</class>\n <widget class=\"QDialog\" name=\"Replacements\">\n  <property name=\"windowModality\">\n   <enum>Qt::WindowModal</enum>\n  </property>\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>410</width>\n    <height>337</height>\n   </rect>\n  </property>\n  <property name=\"sizePolicy\">\n   <sizepolicy hsizetype=\"Fixed\" vsizetype=\"Fixed\">\n    <horstretch>0</horstretch>\n    <verstretch>0</verstretch>\n   </sizepolicy>\n  </property>\n  <property name=\"minimumSize\">\n   <size>\n    <width>410</width>\n    <height>320</height>\n   </size>\n  </property>\n  <property name=\"maximumSize\">\n   <size>\n    <width>410</width>\n    <height>500</height>\n   </size>\n  </property>\n  <property name=\"contextMenuPolicy\">\n   <enum>Qt::CustomContextMenu</enum>\n  </property>\n  <property name=\"acceptDrops\">\n   <bool>true</bool>\n  </property>\n  <property name=\"windowTitle\">\n   <string>Define replacement</string>\n  </property>\n  <property name=\"autoFillBackground\">\n   <bool>true</bool>\n  </property>\n  <property name=\"sizeGripEnabled\">\n   <bool>false</bool>\n  </property>\n  <property name=\"modal\">\n   <bool>false</bool>\n  </property>\n  <widget class=\"QDialogButtonBox\" name=\"okCancel_buttons\">\n   <property name=\"geometry\">\n    <rect>\n     <x>10</x>\n     <y>300</y>\n     <width>381</width>\n     <height>32</height>\n    </rect>\n   </property>\n   <property name=\"orientation\">\n    <enum>Qt::Horizontal</enum>\n   </property>\n   <property name=\"standardButtons\">\n    <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>\n   </property>\n  </widget>\n  <widget class=\"QGroupBox\" name=\"groupBox\">\n   <property name=\"geometry\">\n    <rect>\n     <x>10</x>\n     <y>10</y>\n     <width>391</width>\n     <height>101</height>\n    </rect>\n   </property>\n   <property name=\"sizePolicy\">\n    <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Preferred\">\n     <horstretch>0</horstretch>\n     <verstretch>0</verstretch>\n    </sizepolicy>\n   </property>\n   <property name=\"title\">\n    <string>Replace:</string>\n   </property>\n   <property name=\"flat\">\n    <bool>false</bool>\n   </property>\n   <property name=\"checkable\">\n    <bool>false</bool>\n   </property>\n   <layout class=\"QGridLayout\" name=\"gridLayout\">\n    <property name=\"leftMargin\">\n     <number>9</number>\n    </property>\n    <property name=\"topMargin\">\n     <number>5</number>\n    </property>\n    <property name=\"rightMargin\">\n     <number>9</number>\n    </property>\n    <property name=\"bottomMargin\">\n     <number>5</number>\n    </property>\n    <property name=\"horizontalSpacing\">\n     <number>10</number>\n    </property>\n    <property name=\"verticalSpacing\">\n     <number>5</number>\n    </property>\n    <item row=\"1\" column=\"1\">\n     <widget class=\"QLineEdit\" name=\"libToReplaceLabel\">\n      <property name=\"readOnly\">\n       <bool>true</bool>\n      </property>\n      <property name=\"placeholderText\">\n       <string/>\n      </property>\n     </widget>\n    </item>\n    <item row=\"0\" column=\"0\">\n     <widget class=\"QLabel\" name=\"label_10\">\n      <property name=\"text\">\n       <string>Thunk:</string>\n      </property>\n     </widget>\n    </item>\n    <item row=\"1\" column=\"0\">\n     <widget class=\"QLabel\" name=\"label_11\">\n      <property name=\"text\">\n       <string>Function:</string>\n      </property>\n     </widget>\n    </item>\n    <item row=\"0\" column=\"1\">\n     <widget class=\"QLineEdit\" name=\"thunkLabel\">\n      <property name=\"enabled\">\n       <bool>true</bool>\n      </property>\n      <property name=\"readOnly\">\n       <bool>true</bool>\n      </property>\n      <property name=\"placeholderText\">\n       <string/>\n      </property>\n     </widget>\n    </item>\n   </layout>\n  </widget>\n  <widget class=\"QGroupBox\" name=\"groupBox_3\">\n   <property name=\"geometry\">\n    <rect>\n     <x>10</x>\n     <y>110</y>\n     <width>391</width>\n     <height>191</height>\n    </rect>\n   </property>\n   <property name=\"sizePolicy\">\n    <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Preferred\">\n     <horstretch>0</horstretch>\n     <verstretch>0</verstretch>\n    </sizepolicy>\n   </property>\n   <property name=\"title\">\n    <string>With:</string>\n   </property>\n   <property name=\"flat\">\n    <bool>false</bool>\n   </property>\n   <property name=\"checkable\">\n    <bool>false</bool>\n   </property>\n   <layout class=\"QGridLayout\" name=\"gridLayout_4\">\n    <property name=\"leftMargin\">\n     <number>5</number>\n    </property>\n    <property name=\"topMargin\">\n     <number>20</number>\n    </property>\n    <property name=\"rightMargin\">\n     <number>5</number>\n    </property>\n    <property name=\"bottomMargin\">\n     <number>5</number>\n    </property>\n    <property name=\"horizontalSpacing\">\n     <number>10</number>\n    </property>\n    <property name=\"verticalSpacing\">\n     <number>5</number>\n    </property>\n    <item row=\"0\" column=\"0\">\n     <widget class=\"QTabWidget\" name=\"tabWidget\">\n      <property name=\"sizePolicy\">\n       <sizepolicy hsizetype=\"Expanding\" vsizetype=\"Expanding\">\n        <horstretch>0</horstretch>\n        <verstretch>0</verstretch>\n       </sizepolicy>\n      </property>\n      <property name=\"contextMenuPolicy\">\n       <enum>Qt::DefaultContextMenu</enum>\n      </property>\n      <property name=\"currentIndex\">\n       <number>0</number>\n      </property>\n      <widget class=\"QWidget\" name=\"tab_1\">\n       <attribute name=\"title\">\n        <string>Edit</string>\n       </attribute>\n       <widget class=\"QWidget\" name=\"gridLayoutWidget_2\">\n        <property name=\"geometry\">\n         <rect>\n          <x>0</x>\n          <y>0</y>\n          <width>361</width>\n          <height>91</height>\n         </rect>\n        </property>\n        <layout class=\"QGridLayout\" name=\"editLayout\">\n         <property name=\"sizeConstraint\">\n          <enum>QLayout::SetDefaultConstraint</enum>\n         </property>\n         <property name=\"leftMargin\">\n          <number>10</number>\n         </property>\n         <property name=\"topMargin\">\n          <number>10</number>\n         </property>\n         <property name=\"rightMargin\">\n          <number>10</number>\n         </property>\n         <property name=\"bottomMargin\">\n          <number>0</number>\n         </property>\n         <item row=\"0\" column=\"1\">\n          <widget class=\"QLineEdit\" name=\"libraryEdit\">\n           <property name=\"placeholderText\">\n            <string>example.dll</string>\n           </property>\n          </widget>\n         </item>\n         <item row=\"1\" column=\"0\">\n          <widget class=\"QLabel\" name=\"label_12\">\n           <property name=\"text\">\n            <string>Function:</string>\n           </property>\n          </widget>\n         </item>\n         <item row=\"1\" column=\"1\">\n          <widget class=\"QLineEdit\" name=\"functionEdit\">\n           <property name=\"placeholderText\">\n            <string>functionName</string>\n           </property>\n          </widget>\n         </item>\n         <item row=\"0\" column=\"0\">\n          <widget class=\"QLabel\" name=\"label_13\">\n           <property name=\"text\">\n            <string>Library:</string>\n           </property>\n          </widget>\n         </item>\n        </layout>\n       </widget>\n      </widget>\n      <widget class=\"QWidget\" name=\"tab_2\">\n       <attribute name=\"title\">\n        <string>Choose</string>\n       </attribute>\n       <widget class=\"QWidget\" name=\"gridLayoutWidget\">\n        <property name=\"geometry\">\n         <rect>\n          <x>0</x>\n          <y>0</y>\n          <width>361</width>\n          <height>91</height>\n         </rect>\n        </property>\n        <layout class=\"QGridLayout\" name=\"choseLayout\">\n         <property name=\"leftMargin\">\n          <number>10</number>\n         </property>\n         <property name=\"topMargin\">\n          <number>10</number>\n         </property>\n         <property name=\"rightMargin\">\n          <number>10</number>\n         </property>\n         <item row=\"0\" column=\"1\">\n          <widget class=\"QComboBox\" name=\"libraryCombo\"/>\n         </item>\n         <item row=\"0\" column=\"2\">\n          <widget class=\"QPushButton\" name=\"addLibraryButton\">\n           <property name=\"maximumSize\">\n            <size>\n             <width>30</width>\n             <height>16777215</height>\n            </size>\n           </property>\n           <property name=\"toolTip\">\n            <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Load replacement library&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>\n           </property>\n           <property name=\"autoFillBackground\">\n            <bool>true</bool>\n           </property>\n           <property name=\"text\">\n            <string>+</string>\n           </property>\n          </widget>\n         </item>\n         <item row=\"1\" column=\"1\">\n          <widget class=\"QComboBox\" name=\"functionCombo\"/>\n         </item>\n         <item row=\"1\" column=\"0\">\n          <widget class=\"QLabel\" name=\"label_15\">\n           <property name=\"sizeIncrement\">\n            <size>\n             <width>50</width>\n             <height>0</height>\n            </size>\n           </property>\n           <property name=\"text\">\n            <string>Function:</string>\n           </property>\n          </widget>\n         </item>\n         <item row=\"0\" column=\"0\">\n          <widget class=\"QLabel\" name=\"label_14\">\n           <property name=\"maximumSize\">\n            <size>\n             <width>50</width>\n             <height>16777215</height>\n            </size>\n           </property>\n           <property name=\"text\">\n            <string>Library:</string>\n           </property>\n          </widget>\n         </item>\n        </layout>\n       </widget>\n      </widget>\n     </widget>\n    </item>\n   </layout>\n  </widget>\n </widget>\n <tabstops>\n  <tabstop>okCancel_buttons</tabstop>\n  <tabstop>thunkLabel</tabstop>\n  <tabstop>libToReplaceLabel</tabstop>\n </tabstops>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "patcher/stub/Stub.cpp",
    "content": "#include \"Stub.h\"\n\nbool StubParam::insertIntoBuffer(AbstractByteBuffer* buf)\n{\n    if (buf == NULL) return false;\n\n    offset_t fullOffset = this->m_bigOffset + this->m_smallOffset;\n    bool isOk = buf->setNumValue(fullOffset, this->m_valueSize, this->m_value);\n    //TODO - verify if setting succeseded?\n    return true;\n}\n\nbool StubParam::readFromBuffer(AbstractByteBuffer* buf)\n{\n    if (buf == NULL) return false;\n\n    offset_t fullOffset = this->m_bigOffset + this->m_smallOffset;\n    bool isOk = false;\n\n    offset_t value = buf->getNumValue(fullOffset, this->m_valueSize, &isOk);\n    if (!isOk) return false;\n\n    this->m_value = value;\n    return true;\n}\n//-----\n\nByteBuffer* Stub::createStubBuffer()\n{\n    ByteBuffer* buf = bufferStubData();\n    if (buf == NULL) return NULL;\n\n    if (this->fillParams(buf) == false) {\n        printf(\"Unable to fill params!\\n\");\n        delete buf;\n        return NULL;\n    }\n    return buf;\n}\n\nByteBuffer* Stub::bufferStubData()\n{\n    const unsigned char* originalData = this->getData();\n    const bufsize_t stubSize = this->getSize();\n\n    unsigned char *stubData = new unsigned char[stubSize];\n    memcpy(stubData, originalData, stubSize);\n    ByteBuffer *stubBuf = new ByteBuffer(stubData, stubSize, 0);\n    delete []stubData;\n    return stubBuf;\n}\n\nbool Stub::fillParam(size_t id, AbstractByteBuffer* buf)\n{\n    StubParam *param = this->getParam(id);\n    if (param == NULL) {\n        //Param not found\n        return false;\n    }\n    if (param->m_relativeToId != param->m_id) {\n        offset_t dif = this->paramDistance(param->m_relativeToId, id);\n        param->setValue(dif);\n    }\n    return param->insertIntoBuffer(buf);\n}\n\n\nbool Stub::fillParams(AbstractByteBuffer* buf)\n{\n    std::map<size_t, StubParam*>::iterator itr;\n    for (itr = m_params.begin(); itr != m_params.end(); itr++) {\n        size_t paramId = itr->first;\n        if (fillParam(paramId, buf) == false) {\n            return false;\n        }\n    }\n    return true;\n}\n\noffset_t Stub::getAbsoluteValue(StubParam *param)\n{\n    if (param == NULL) {\n        return INVALID_ADDR;\n    }\n\n    offset_t myValue = param->m_value;\n\n    if (param->m_relativeToId != param->m_id) {\n        StubParam *relParam = this->getParam(param->m_relativeToId);\n        if (relParam == NULL) return INVALID_ADDR;\n\n        offset_t dif = ((int32_t) param->m_value);\n        offset_t relValue = relParam->m_value;\n\n        myValue = relParam->m_value + dif + param->getTotalOffset() + param->getValueSize();\n    }\n    return myValue;\n}\n\nbool Stub::readParam(size_t id, AbstractByteBuffer* buf)\n{\n    StubParam *param = this->getParam(id);\n    if (param == NULL) {\n        //Param not found\n        return false;\n    }\n    if (param->readFromBuffer(buf) == false) return false;\n\n    offset_t myValue = getAbsoluteValue(param);\n    if (myValue == INVALID_ADDR) return false;\n\n    param->setValue(myValue);\n    return true;\n}\n\n\nbool Stub::readParams(AbstractByteBuffer* buf)\n{\n    std::map<size_t, StubParam*>::iterator itr;\n    for (itr = m_params.begin(); itr != m_params.end(); itr++) {\n        size_t paramId = itr->first;\n        if (!readParam(paramId, buf)) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid Stub::deleteParams()\n{\n    bool isOk = false;\n    std::map<size_t, StubParam*>::iterator itr;\n    for (itr = m_params.begin(); itr != m_params.end(); itr++) {\n        StubParam* param = itr->second;\n        delete param;\n    }\n    m_params.clear();\n}\n\nbool Stub::containsStub(AbstractByteBuffer *buf) const\n{\n    const unsigned char* stubData = this->getData();\n    const bufsize_t stubSize = this->getSize();\n    const offset_t signStart = getSignatureStart();\n    const offset_t signEnd = getSignatureEnd();\n\n    /* sanity check */\n    if (buf == NULL) return false;\n    if (buf->getContentSize() < stubSize) return false;\n\n    unsigned char* bufData = (unsigned char*) buf->getContent();\n    if (bufData == NULL) return false;\n\n    /* sanity check */\n    if (stubData == NULL || signStart > signEnd || signEnd >= stubSize) {\n        printf(\"Malformated stub!\");\n        return false;\n    }\n\n    bufData += signStart;\n\n    const unsigned char* cmpData = stubData + signStart;\n    const size_t cmpSize = signEnd - signStart;\n\n    int res = memcmp(cmpData, bufData, cmpSize);\n    if (res == 0) {\n        return true;\n    }\n    return false;\n}\n"
  },
  {
    "path": "patcher/stub/Stub.h",
    "content": "#pragma once\n#include <bearparser/core.h>\n\n#include \"../Executables.h\"\n#include \"../FuncReplacements.h\"\n\n\nclass StubParam\n{\npublic:\n    StubParam(size_t id, offset_t bigOffset, offset_t smallOffset, size_t valueSize, size_t relId)\n        : m_id(id), m_bigOffset(bigOffset), m_smallOffset(smallOffset), m_valueSize(valueSize), m_value(0), m_relativeToId(relId) {}\n\n    StubParam(size_t id, offset_t bigOffset, offset_t smallOffset, size_t valueSize)\n        : m_id(id), m_bigOffset(bigOffset), m_smallOffset(smallOffset), m_valueSize(valueSize), m_value(0), m_relativeToId(id) {}\n\n    virtual ~StubParam() { /*printf(\"Deleting param id = %d\\n\", m_id);*/ }\n\n    void setValue(offset_t value) { this->m_value = value; }\n    offset_t getValue() { return m_value; }\n\n    bool insertIntoBuffer(AbstractByteBuffer* buf);\n    bool readFromBuffer(AbstractByteBuffer* buf);\n\n    offset_t getTotalOffset() { return m_bigOffset + m_smallOffset; }\n    offset_t getBigOffset() { return m_bigOffset; }\n    size_t getValueSize() { return m_valueSize; }\n\nprotected:\n    size_t m_id;\n    size_t m_relativeToId;\n    offset_t m_bigOffset; // offset of instruction in code\n    offset_t m_smallOffset;\n\n    size_t m_valueSize;\n    offset_t m_value;\n\nfriend class Stub;\n};\n\nclass Stub {\n\npublic:\n    enum STUB_PARAMS {\n        NEW_EP, //LABEL_newEP\n        DATA_RVA, //LABEL_dataRVA\n        OEP, //LABEL_oldEP\n        FUNC_GET_MODULE_RVA,\n        FUNC_LOAD_LIB_RVA\n    };\n\n    Stub() { }\n    virtual ~Stub() { deleteParams(); }\n\n    virtual bufsize_t getSize() const = 0;\n    virtual const unsigned char* getData() const = 0;\n\n    virtual offset_t getSignatureStart() const = 0;\n    virtual offset_t getSignatureEnd() const = 0;\n    virtual offset_t getDatastoreOffset() const = 0;\n\n    ByteBuffer* createStubBuffer();\n    bool containsStub(AbstractByteBuffer *buf) const;\n\n    size_t getParamsCount()\n    {\n        return m_params.size();\n    }\n\n    offset_t getParamValue(size_t id)\n    {\n        if (this->m_params.find(id) == m_params.end()) {\n            //No param with given ID\n            return INVALID_ADDR;\n        }\n        return this->m_params[id]->getValue();\n    }\n\n    bool setParam(size_t id, offset_t value) {\n        if (this->m_params.find(id) == m_params.end()) {\n            //No param with given ID\n            return false;\n        }\n        this->m_params[id]->setValue(value);\n        return true;\n    }\n\n   virtual bool readParams(AbstractByteBuffer* buf);\n\nprotected:\n\n    StubParam* getParam(size_t id) const {\n        std::map<size_t, StubParam*>::const_iterator itr = this->m_params.find(id);\n        if (itr == m_params.end()) return NULL;\n        return itr->second;\n    }\n\n    offset_t paramDistance(size_t idFrom, size_t idTo) {\n        StubParam *param = this->getParam(idTo);\n        StubParam *newEpParam = this->getParam(idFrom);\n\n        if (param == NULL || newEpParam == NULL) return INVALID_ADDR;\n\n        offset_t newEntry = newEpParam->getValue() + newEpParam->getValueSize();\n        offset_t oldEntry = param->getValue();\n\n        bufsize_t oldEntryOffset = param->getTotalOffset(); //toOffset\n\n        offset_t dif = ((newEntry + oldEntryOffset) - oldEntry) * (-1);\n        return dif;\n    }\n\n    offset_t getAbsoluteValue(StubParam *param); // autocalculate relative\n\n    virtual bool fillParam(size_t id, AbstractByteBuffer* buf);\n    virtual bool fillParams(AbstractByteBuffer* buf);\n\n    virtual bool readParam(size_t id, AbstractByteBuffer* buf);\n\n    ByteBuffer* bufferStubData();\n\n    virtual void createParams() = 0;\n    virtual void deleteParams();\n\n    std::map<size_t, StubParam*> m_params;\n};\n"
  },
  {
    "path": "patcher/stub/Stub32.cpp",
    "content": "#include \"Stub32.h\"\n#include \"Stub32Data.h\"\n\nbufsize_t Stub32::getSize() const\n{\n    return Stub32Data::size;\n}\n\nconst unsigned char* Stub32::getData() const\n{\n    return Stub32Data::data;\n}\n\noffset_t Stub32::getSignatureStart() const\n{\n    return Stub32Data::pointers[2] + 1 + sizeof(DWORD);\n}\n\noffset_t Stub32::getSignatureEnd() const\n{\n    return Stub32Data::pointers[3];\n}\n\noffset_t Stub32::getDatastoreOffset() const\n{\n    return Stub32Data::pointers[DATA_RVA];\n}\n\nvoid Stub32::createParams()\n{\n    this->m_params[NEW_EP] = new StubParam(NEW_EP, Stub32Data::pointers[0], 1, sizeof(DWORD));\n    this->m_params[DATA_RVA] = new StubParam(DATA_RVA, Stub32Data::pointers[1], 1, sizeof(DWORD));\n    this->m_params[OEP] = new StubParam(OEP, Stub32Data::pointers[2], 1, sizeof(DWORD) , NEW_EP);\n\n    this->m_params[FUNC_LOAD_LIB_RVA] = new StubParam(FUNC_LOAD_LIB_RVA, Stub32Data::pointers[3], 1, sizeof(DWORD));\n    this->m_params[FUNC_GET_MODULE_RVA] = new StubParam(FUNC_GET_MODULE_RVA, Stub32Data::pointers[4], 1, sizeof(DWORD));\n}\n"
  },
  {
    "path": "patcher/stub/Stub32.h",
    "content": "#pragma once\n#include \"Stub.h\"\n\nclass Stub32 : public Stub {\npublic:\n    Stub32() : Stub() { createParams(); }\n\n    virtual bufsize_t getSize() const;\n    virtual const unsigned char* getData() const;\n\n    virtual offset_t getSignatureStart() const;\n    virtual offset_t getSignatureEnd() const;\n    virtual offset_t getDatastoreOffset() const;\n\nprotected:\n    virtual void createParams();\n};\n"
  },
  {
    "path": "patcher/stub/Stub32Data.h",
    "content": "#include <stdio.h>\n\nnamespace Stub32Data {\n\n    const unsigned char data[] = {\n0xb8, 0x11, 0x11, 0x11, \n0x11, 0xbb, 0x22, 0x22, \n0x22, 0x22, 0xe8, 0x05, \n0x00, 0x00, 0x00, 0xe9, \n0x64, 0x56, 0x34, 0x12, \n0x83, 0xc0, 0x0f, 0x8b, \n0x3c, 0x24, 0x29, 0xc7, \n0x01, 0xfb, 0xe8, 0x4a, \n0x00, 0x00, 0x00, 0x85, \n0xc0, 0x75, 0x01, 0xc3, \n0x89, 0xc1, 0x51, 0xbe, \n0x22, 0x22, 0x22, 0x22, \n0x01, 0xfe, 0xff, 0x16, \n0x85, 0xc0, 0x75, 0x0b, \n0xe8, 0x3c, 0x00, 0x00, \n0x00, 0x85, 0xc0, 0x75, \n0xf7, 0xeb, 0xdb, 0x89, \n0xc1, 0xe8, 0x23, 0x00, \n0x00, 0x00, 0x85, 0xc0, \n0x74, 0xd0, 0x50, 0x51, \n0xbe, 0x22, 0x22, 0x22, \n0x22, 0x01, 0xfe, 0xff, \n0x16, 0x89, 0xc6, 0xe8, \n0x0d, 0x00, 0x00, 0x00, \n0x85, 0xc0, 0x75, 0x01, \n0xc3, 0x85, 0xf6, 0x74, \n0x02, 0x89, 0x30, 0xeb, \n0xd6, 0xe8, 0x07, 0x00, \n0x00, 0x00, 0x85, 0xc0, \n0x74, 0x02, 0x01, 0xf8, \n0xc3, 0x8b, 0x03, 0x83, \n0xc3, 0x04, 0xc3\n    };\n\nDWORD pointers[] = {\n0x00, //LABEL_newEP\n0x05, //LABEL_dataRVA\n0x0f, //LABEL_oldEP \n0x2b, //LABEL_loadLibrary \n0x50  //LABEL_GetProcAddress\n    };\n\n    const size_t size = sizeof(data);\n\n};//Stub32Data\n"
  },
  {
    "path": "patcher/stub/Stub64.cpp",
    "content": "#include \"Stub64.h\"\n#include \"Stub64Data.h\"\n\nbufsize_t Stub64::getSize() const\n{\n    return Stub64Data::size;\n}\n\nconst unsigned char* Stub64::getData() const\n{\n    return Stub64Data::data;\n}\n\noffset_t Stub64::getSignatureStart() const\n{\n    return Stub64Data::pointers[2] + 1 + sizeof(DWORD);\n}\n\noffset_t Stub64::getSignatureEnd() const\n{\n    return Stub64Data::pointers[3];\n}\n\noffset_t Stub64::getDatastoreOffset() const\n{\n    return Stub64Data::pointers[DATA_RVA];\n}\n\n\nvoid Stub64::createParams()\n{\n    this->m_params[NEW_EP] = new StubParam(NEW_EP, Stub64Data::pointers[0], 3, sizeof(DWORD));\n    this->m_params[DATA_RVA] = new StubParam(DATA_RVA, Stub64Data::pointers[1], 3, sizeof(DWORD));\n    this->m_params[OEP] = new StubParam(OEP, Stub64Data::pointers[2], 1, sizeof(DWORD) , NEW_EP);\n\n    this->m_params[FUNC_LOAD_LIB_RVA] = new StubParam(FUNC_LOAD_LIB_RVA, Stub64Data::pointers[3], 2, sizeof(DWORD), NEW_EP);\n    this->m_params[FUNC_GET_MODULE_RVA] = new StubParam(FUNC_GET_MODULE_RVA, Stub64Data::pointers[4], 2, sizeof(DWORD), NEW_EP);\n\n}\n"
  },
  {
    "path": "patcher/stub/Stub64.h",
    "content": "#pragma once\n#include \"Stub.h\"\n\nclass Stub64 : public Stub {\npublic:\n    Stub64() : Stub() { createParams(); }\n    virtual bufsize_t getSize() const;\n    virtual const unsigned char* getData() const;\n\n    virtual offset_t getSignatureStart() const;\n    virtual offset_t getSignatureEnd() const;\n    virtual offset_t getDatastoreOffset() const;\n\nprotected:\n    virtual void createParams();\n};\n"
  },
  {
    "path": "patcher/stub/Stub64Data.h",
    "content": "#include <stdio.h>\n\nnamespace Stub64Data {\n\n    const unsigned char data[] = {\n0x48, 0xc7, 0xc0, 0x11,\n0x11, 0x11, 0x11, 0x48,\n0xc7, 0xc3, 0x22, 0x22,\n0x22, 0x22, 0xe8, 0x05,\n0x00, 0x00, 0x00, 0xe9,\n0x60, 0x56, 0x34, 0x12,\n0x48, 0x83, 0xc0, 0x13,\n0x4c, 0x8b, 0x3c, 0x24,\n0x49, 0x29, 0xc7, 0x4c,\n0x01, 0xfb, 0xe8, 0x53,\n0x00, 0x00, 0x00, 0x85,\n0xc0, 0x75, 0x01, 0xc3,\n0x48, 0x89, 0xc1, 0x49,\n0x89, 0xde, 0x48, 0x8b,\n0x1c, 0x24, 0xff, 0x15,\n0xed, 0xa1, 0x05, 0x00,\n0x48, 0x85, 0xc0, 0x4c,\n0x89, 0xf3, 0x75, 0x0b,\n0xe8, 0x3e, 0x00, 0x00,\n0x00, 0x85, 0xc0, 0x75,\n0xf7, 0xeb, 0xd3, 0x48,\n0x89, 0xc1, 0xe8, 0x23,\n0x00, 0x00, 0x00, 0x85,\n0xc0, 0x74, 0xc7, 0x48,\n0x89, 0xc2, 0xe8, 0x2e,\n0x00, 0x00, 0x00, 0x48,\n0x89, 0xc6, 0xe8, 0x0f,\n0x00, 0x00, 0x00, 0x85,\n0xc0, 0x75, 0x01, 0xc3,\n0x48, 0x85, 0xf6, 0x74,\n0x03, 0x48, 0x89, 0x30,\n0xeb, 0xd5, 0xe8, 0x08,\n0x00, 0x00, 0x00, 0x85,\n0xc0, 0x74, 0x03, 0x4c,\n0x01, 0xf8, 0xc3, 0x48,\n0x31, 0xc0, 0x8b, 0x03,\n0x48, 0x83, 0xc3, 0x04,\n0xc3, 0x53, 0x48, 0x83,\n0xec, 0x20, 0xff, 0x15,\n0xb4, 0x0f, 0x00, 0x00,\n0x48, 0x83, 0xc4, 0x20,\n0x5b, 0xc3\n    };\n\nDWORD pointers[] = {\n0x00,\n0x07,\n0x13,\n0x3a, \n0x9a\n    };\n\n    const size_t size = sizeof(data);\n\n};//Stub64Data\n"
  },
  {
    "path": "stub/hexf.cpp",
    "content": "#define _CRT_SECURE_NO_WARNINGS\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n    if (argc < 2) {\n        printf(\"No fileName supplied!\\n\");\n        return -1;\n    }\n    FILE *fp = fopen(argv[1], \"rb\");\n    if (fp == NULL) {\n        printf(\"Unable to open the file!\\n\");\n        return -1;\n    }\n    int brk = 4;\n    int i = 0;\n\n    char c = 0;\n    while(!feof(fp)) {\n        c = fgetc (fp);\n\n        if (i == brk) {\n            i = 0;\n            printf(\"\\n\");\n        }\n        i++;\n        printf(\"0x%2.2x, \", c & 0x0FF);\n    }\n    printf(\"0x90\\n\");\n    return 0;\n}\n\n"
  },
  {
    "path": "stub/stub32.asm",
    "content": "[bits 32]\nstart:\nLABEL_newEP:\n\tmov EAX, 11111111h ; new EP\nLABEL_dataRVA:\n\tmov EBX, 22222222h ; data RVA\n\tcall init\nafter_init:\nLABEL_oldEP:\n    jmp 12345678h ; oep\ninit:\n\tadd EAX, (after_init - start)\n\tmov EDI, [ESP]\n\tsub EDI, EAX ; ImageBase\n\tadd EBX, EDI\nload_lib:\n\tcall get_saved_rva\n\tTEST EAX, EAX\n\tJNZ SHORT load_next_lib\n\tRET\n\nload_next_lib:\n\tmov ECX, EAX\n\tpush ECX\nLABEL_LoadLibrary:\n\tMOV ESI, 22222222h\n\tADD ESI, EDI\n\tCALL [ESI] ; call LoadLibraryA\n\ttest EAX, EAX\n\tjnz load_function\n\t\nskip_functions:\t; if DLL not found, skip mapped <name><thunk>\n\tcall get_saved_value\n\ttest eax,eax\n\tjne skip_functions\n\tjmp load_lib\n\t\nload_function:\n\tmov ECX, EAX\n\tcall get_saved_rva\n\tTEST EAX, EAX\n\tJZ SHORT load_lib\n\t\n\tpush EAX\n\tpush ECX\nLABEL_GetProcAddress:\n\tMOV ESI, 22222222h\n\tADD ESI, EDI\n\tCALL DWORD NEAR [ESI] ; call GetProcAddress\n\tmov ESI, EAX ; ESI <- Handle\n\tcall get_saved_rva ; thunk to fill or to skip\n\tTEST EAX, EAX\t; is thunk empty?\n\tjne overwrite_thunk\n\tret ; malformed data, just finish...\n\noverwrite_thunk:\n\tTEST ESI, ESI ; is Handle Empty?\n\tje _end_load_function\n\tMOV [EAX], ESI\n_end_load_function:\n\tJMP SHORT load_function\n\t\nget_saved_rva:\n\tcall get_saved_value\n\ttest eax,eax\n\tjz _end_get_saved_rva\n\tADD EAX, EDI ; ImgBase\n_end_get_saved_rva:\n\tret\n\t\nget_saved_value:\n\tmov eax, dword [EBX]\n\tADD EBX, 0X4\n\tret\n;--------\n;Data:\ndd (LABEL_newEP - start)\ndd (LABEL_dataRVA - start)\ndd (LABEL_oldEP - start)\ndd (LABEL_LoadLibrary - start)\ndd (LABEL_GetProcAddress - start)\n"
  },
  {
    "path": "stub/stub64.asm",
    "content": "[bits 64]\nstart:\nLABEL_newEP:\n\tmov rax, 11111111h ; new EP\nLABEL_dataRVA:\n\tmov rbx, 22222222h ; data RVA\n\tcall init\nafter_init:\nLABEL_oldEP:\n    jmp 12345678h ; oep\ninit:\n\tadd rax, (after_init - start)\n\tmov r15, [rsp]\n\tsub r15, rax ;r15 -> ImageBase\n\tadd rbx, r15\nload_lib:\n\tcall get_saved_rva\n\tTEST EAX, EAX\n\tJNZ SHORT load_next_lib\n\tRET\n\nload_next_lib:\n\tmov rcx, rax\n\tmov r14,rbx\n\tmov rbx,[rsp]\nLABEL_LoadLibrary:\n\tCALL QWORD NEAR [RIP+0X5A1ED] ; call LoadLibraryA\n\ttest rax, rax\n\tmov rbx,r14\n\tjnz load_function\nskip_functions:\t; if DLL not found, skip mapped <name><thunk>\n\tcall get_saved_value\n\ttest eax,eax\n\tjne skip_functions\n\tjmp load_lib\n\t\nload_function:\n\tmov rcx, rax\n\tcall get_saved_rva\n\tTEST EAX, EAX\n\tJZ SHORT load_lib\n\n\tmov rdx, rax\n\tCALL getProc\n\tmov rsi, rax ; RSI <- Handle\n\tcall get_saved_rva ; thunk to fill or to skip\n\tTEST EAX, EAX\t; is thunk empty?\n\tjne overwrite_thunk\n\tret ; malformed data, just finish...\n\noverwrite_thunk:\n\tTEST rsi, rsi ; is Handle Empty?\n\tje _end_load_function\n\tMOV [rax], rsi\n_end_load_function:\n\tJMP SHORT load_function\n\t\nget_saved_rva:\n\tcall get_saved_value\n\ttest eax,eax\n\tjz _end_get_saved_rva\n\tADD rax, r15 ; ImgBase\n_end_get_saved_rva:\n\tret\n\t\nget_saved_value:\n\txor rax, rax\n\tmov eax, dword [rbx]\n\tADD rbx, 0X4\n\tret\n;>------\t\ngetProc:\n\tPUSH RBX\n\tSUB RSP, 0X20\nLABEL_GetProcAddress:\n\tCALL QWORD NEAR [RIP+0XFB4]\t;[KERNEL32.dll].GetProcAddress\n\tADD RSP, 0X20\n\tPOP RBX\n\tRET\n;<-------\n;--------\n;Data:\ndd (LABEL_newEP - start)\ndd (LABEL_dataRVA - start)\ndd (LABEL_oldEP - start)\ndd (LABEL_LoadLibrary - start)\ndd (LABEL_GetProcAddress - start)"
  }
]