如何在不结束进程的情况下卸载该进程中的dll模块
EnablePrivilege(HANDLE hToken, LPCSTR szPrivName)
{
TOKEN_PRIVILEGES tkp;
LookupPrivilegeValue( NULL,szPrivName,&tkp.Privileges[0].Luid );//修改进程权限
tkp.PrivilegeCount=1;
tkp.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges( hToken,FALSE,&tkp,sizeof tkp,NULL,NULL );//通知系统修改进程权限
return( (GetLastError()==ERROR_SUCCESS) );
}
BOOL UnloadDll(DWORD dwPid, CString strDllName)
{
//获取宿主进程的句柄,注意那几个参数,不然会出错
HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD | /
PROCESS_VM_OPERATION | /
PROCESS_VM_WRITE,
FALSE, dwPid);
if(hProcess == NULL){
::MessageBox(NULL, "无法获取进程句柄", "错误", MB_OK | MB_ICONERROR);
return FALSE;
}
DWORD dwSize = 0;
DWORD dwWritten = 0;
DWORD dwHandle = 0;
dwSize = strDllName.GetLength() + 1;//dll的全路径名的长度,待会分配内存要用到的
//向宿主进程分配内存,返回一个指针
LPVOID lpBuf = VirtualAllocEx(hProcess, NULL, dwSize, MEM_COMMIT, PAGE_READWRITE);
//如果在宿主进程空间写失败就直接报错闪人
if( !WriteProcessMemory(hProcess, lpBuf, (LPVOID)strDllName.GetBuffer(dwSize), dwSize, &dwWritten)){
VirtualFreeEx(hProcess, lpBuf, dwSize, MEM_DECOMMIT);
CloseHandle(hProcess);
MessageBox(NULL, "在目标进程中写入失败", "错误", MB_OK | MB_ICONERROR);
return FALSE;
}
//获取GetModuleHandleA函数地址
LPVOID pFun = GetProcAddress(GetModuleHandle("Kernel32"), "GetModuleHandleA");
//在宿主进程中创建一个远程线程,线程函数为上面导出的GetModuleHandleA,参数为lpBuf指针,还
//记得我们获取的dll全路径不
HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pFun,
lpBuf, 0, NULL);
//如果创建线程失败,直接报错闪人
if(hThread == NULL){
CloseHandle(hProcess);
::MessageBox(NULL, "在目标进程创建远程线程失败", "错误", MB_OK | MB_ICONERROR);
return FALSE;
}
// 等待GetModuleHandle运行完毕
WaitForSingleObject(hThread, INFINITE);
// 获得GetModuleHandle的返回值
GetExitCodeThread(hThread, &dwHandle);
// 释放目标进程中申请的空间
VirtualFreeEx(hProcess, lpBuf, dwSize, MEM_DECOMMIT);
CloseHandle(hThread);
// 使目标进程调用FreeLibraryAndExit,卸载DLL,实际也可以用FreeLibrary,但是我发现前者好一点
pFun = GetProcAddress(GetModuleHandle("Kernel32"), "FreeLibraryAndExitThread");
hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pFun,
(LPVOID)dwHandle, 0, NULL);
// 等待FreeLibraryAndExitThread执行完毕
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
CloseHandle(hProcess);
return TRUE; //操作成功