首页 > 解决方案 > 注入的 dll C++ 访问冲突错误

问题描述

所以最近我制作了自己的 dll 注入器,以便能够通过在其中注入调试 dll 来调试我的其他应用程序;接口使用 c++/cli,代码使用 c++。

我在一个C++ 控制台应用程序项目上测试了我在这个项目中使用的相同代码,它没有任何问题。

注入发生在Init.cpp文件内部,本质上是获取表单下提供的dll路径,C:\\user\\documents\\debug.dll并检查是否存在。之后,它通过将名称(在本例myotherapp.exe中为 )作为参数传递来获取进程 ID。如果成功,则获取进程的句柄并将其存储在中g.h_process,继续在进程中分配可读/可写内存,然后将 dll 的路径写入该内存,最后使用LoadLibraryA在进程中加载​​ dll。

Init.cpp

void Injector::Init(void)
{
    Inject::Checks((char*)g.dll_path, g.procName);//checking for dll validity
}

bool Injector::Inject::Checks(char* dll_path, PCSTR procName)
{
    if (!Utils::file_exists(dll_path))
        return Utils::error("File does not exist.");
    Utils::successInput("Prepared DLL for injection");

    Utils::getProcId(procName, g.proc_id);
    if (!g.proc_id) {
        return Utils::error("Could not find specified process.");
    }

    g.h_process = OpenProcess(PROCESS_ALL_ACCESS, NULL, g.proc_id);
    if (!g.h_process) {
        return  Utils::error("Failed to open a handle to process");
    }

    g.allocatedMemory = VirtualAllocEx(g.h_process, nullptr, MAX_PATH, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);//mem_reserver reserve memory then commit memory to be able to write to that memory

    Allocate(g.allocatedMemory, dll_path);

    Llib();

    Release(dll_path, g.allocatedMemory);
    return 0;
}

bool Injector::Inject::Allocate(void* allocatedMemory, char* dll_path)
{
    if (!allocatedMemory)
        return Utils::error("Failed to allocate memory");

    if (!WriteProcessMemory(g.h_process, g.allocatedMemory, g.dll_path, MAX_PATH, nullptr))
        return Utils::error("Failed to write process");
    return true;
}

bool Injector::Inject::Llib() {
    HANDLE h_thread = CreateRemoteThread(g.h_process, nullptr, NULL, LPTHREAD_START_ROUTINE(LoadLibraryA), g.allocatedMemory, NULL, nullptr);
    if (!h_thread)
        return Utils::error("Failed to create remote thread");
    return true;
}

bool Injector::Inject::Release(PCSTR dll_path, void* allocatedMemory)
{
    CloseHandle(g.h_process);
    VirtualFreeEx(g.h_process, allocatedMemory, NULL, MEM_RELEASE);
    return true;
}

g.debug只是一个标志,它告诉我们控制台是否启用。在只包含全局变量的globals.hpp中找到。您还可以在此处Utils检查命名空间。

错误:

我在这里遇到的问题是,每当我将我的 DLL 注入进程时,我的注入器工作正常,没有错误,但是当我将 vs 附加到我想注入的进程时我得到一个Access Violation错误,进程退出并出现错误代码。

我不明白,我看不到我在哪里访问无效内存。

提前致谢。

标签: c++windows

解决方案


推荐阅读