GithubHelp home page GithubHelp logo

microsoft / detours Goto Github PK

View Code? Open in Web Editor NEW
4.9K 167.0 954.0 767 KB

Detours is a software package for monitoring and instrumenting API calls on Windows. It is distributed in source code form.

License: MIT License

Makefile 1.08% C++ 98.86% C 0.06%
hacktoberfest microsoft

detours's Introduction

Microsoft Research Detours Package

Detours is a software package for monitoring and instrumenting API calls on Windows. Detours has been used by many ISVs and is also used by product teams at Microsoft. Detours is now available under a standard open source license (MIT). This simplifies licensing for programmers using Detours and allows the community to support Detours using open source tools and processes.

Detours is compatible with the Windows NT family of operating systems: Windows NT, Windows XP, Windows Server 2003, Windows 7, Windows 8, and Windows 10. It cannot be used by Windows Store apps because Detours requires APIs not available to those applications. This repo contains the source code for version 4.0.1 of Detours.

For technical documentation on Detours, see the Detours Wiki. For directions on how to build and run samples, see the samples README.txt file.

Contributing

The Detours repository is where development is done. Here are some ways you can participate in the project:

Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Issues, questions, and feedback

Mailing list for announcements

The detours-announce mailing list is a low-traffic email list for important announcements about the project, such as the availability of new versions of Detours. To join it, send an email to [email protected] with a message body containing only the text SUBSCRIBE DETOURS-ANNOUNCE. To leave it, send an email to [email protected] with a message body containing only the text UNSUBSCRIBE DETOURS-ANNOUNCE.

License

Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the MIT License.

detours's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

detours's Issues

#error: Unknown architecture (x86, amd64, ia64, arm, arm64)

hello
I got this error but can`t find how to handle this

I also tried different status like,
Win 10 64bit VS 2017,VS 2015, VS 2012
Win 7 64bit VS 2015, VS 2012
Win 7 32bit VS 2015, VS 2012

but have same problem

I would appreciate it if you could help this problem

With Regards

Does detours need huge extra memory?

I use DetourCreateProcessWithDll to create my app process and find the process use 1.6g memory in win task-manager view. Normally, my app use 0.8g memory in win task-manager view.
It's confuse that i can only catch the 0.8g memory using (by hooking NtAllocateVirtualMemory and VirtualAlloc ) when use DetourCreateProcessWithDll.
I want to know what's the problem?

Not able to build x64 detours

So im trying to build the latest detours library in x64 to able to use it with a 64 bit dll.
Im running the VS 2017 x64 Tool, i navigated to the detours folder and wrote "SET DETOURS_TARGET_PROCESSOR=X64" -> Enter, after that i wrote "nmake" -> Enter.

Now i get a error that, cl.EXE and nmake.exe returned with code 0x2
Full log: https://pastebin.com/7ZXEHdTy

Doesn't work with Microsoft Teams

I created 64-bit lib, when I do injecting, every APIs call returned positive, but Teams.exe
never get injected, the 32-bit works with Zoom.

32bit Parent process is not able to load dll in 64bit process using DetourCreateProcessWithDllEx

On 64bit Windows, My 32bit Detouring DLL "intercept_32.dll" is loaded in 32-bit process "c:\Windows\SysWOW64\notepad.exe". I have detoured "CreateProcessW" API. When I select "Print" from Notepad's menu then "CreateProcessW" in my "intercept_32.dll" is called to launch 64bit process "c:\Windows\splwow64.exe". In detoured "CreateProcessW" if process is "splwow64", I call "DetourCreateProcessWithDllEx" and ask it to load a 64bit "intercept_64.dll" in "splwow64.exe". "splwow64.exe" starts but "intercept_64.dll" is not loaded in it.

Note:
On 64bit machine, "intercept_64.dll" is loaded in 64bit "explorer.exe" and if I launch "c:\Windows\splwow64.exe" from 64bit explorer (from Run) then "intercept_64.dll" gets loaded in it.

Can't read InetPton identifier in Detour creatwth.cpp

I have included the header file <Ws2tcpip.h> inside the creatwth.cpp and linked Ws2_32 library using #pragma comment(lib, "Ws2_32.lib")
However, when I call the function "InetPton", it's giving me the error " 'InetPton': identifier not found".

Can someone help me please !

vcpkg

Add Detours to vcpkg

detours.h error when included from C source file

As it contains some #ifdef __cplusplus, I think this should work for both C and C++.

However,

D:\something>cl /Idetours\src /c loader.c
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27025.1 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

loader.c
detours\src\detours.h(390): error C2071: '__C_ASSERT__': illegal storage class

Compiling as C++ resolves this, but this will cause other issues in other C source files.

The assertion was introduced in commit c238185#diff-c220cfbe825e51b1b1eecaaaf610b67cR390

iping sample fails to build with nmake x64

Run from the command line

set DETOURS_TARGET_PROCESSOR=X64
nmake

and get the error:

iping_d.obj : error LNK2001: unresolved external symbol _iping_ProxyFileInfo
....\bin.X64\cping.exe : fatal error LNK1120: 1 unresolved externals
...

"Rejecting IJW module" exception injecting into .net

When injecting any c++ dll via DetourCreateProcessWithDlls into a .net 2 executable that is configured with both .net 2 and .net 4 as supported runtimes, the clr throws exception code e0434352 (error "ERR: Rejecting IJW module built against v2.0.50727 because it could be loaded into another runtime in this process.") and the program terminates. The same exe will load just fine with detours if the useLegacyV2RuntimeActivationPolicy option is set to true in the .net exe's .config file. The clr function throwing the error and terminating the process is clr!PEFile::CheckForDisallowedInProcSxSLoadWorker and if that function is bypassed then the exe will load properly with detours. Other methods of injecting the same dll using createremotethread or queueapc do not cause any issue and the exe loads fine.

I assume the issue has to do with the IAT method of injecting the dll but I am having trouble pinpointing the exact reason or modification from detours causing the issue to see if it can be corrected.

This is easily reproduced with the detours withdll exe, simple32.dll and an appropriate .net app to inject into. I have attached a sample project. If you build it in release mode and run "withdll.exe /d:simple32.dll DotNetAppTest.exe" you should reproduce the crash.

DotNetAppTest.zip

Can't Seem To Make x64?

Hey Peeps,

I have VS2017 installed latest updates with the C++ tools installed.
I might be missing dependencies however when I open up the Developer Command Prompt and make the project it compiles fine for x86. I did try make all and it certainly tries but when it gets to x64 it seems to error out on:
iping_d.obj : error LNK2001: unresolved external symbol _iping_ProxyFileInfo
Would I be able to get any advice on this why it pops up when making for x64 and not x86 or am I being so stupid I'm not seeing what is wrong.

Remove unnecessary variable assignments

The variables “Helper” and “rlpDlls” are reset to a null pointer despite of the implementation detail that these variables are not accessed again after such a assignment at the end of corresponding functions.
How do you think about to avoid such statements?

DetourUpdateThread with non-pseudo current thread handle will freeze the thread.

When running the following code, detours will suspend the current thread, with no way of resuming it, possibly resulting in a process deadlock if this is done in DllMain.

HANDLE hThread = OpenThread(THREAD_SUSPEND_RESUME, false, GetCurrentThreadId());
DetoursUpdateThread(hThread);
// no code will execute after this point.

This is caused by https://github.com/microsoft/Detours/blob/master/src/detours.cpp#L1854 only checking against the pseudo-handle instead of also checking if the TID of the handle matches the current thread's.
This if check can be safely replaced by GetThreadId(hThread) == GetCurrentThreadId() to handle both real and pseudo handles to the current thread (although there might be a slight performance gain due to less API calls by still explicitly checking if it's a pseudo handle)

simple error with function "detour_skip_jmp" by Hook System function on Windows x64

hi,
function "detour_skip_jmp" does work for x86 api hook routine, but not ok for x64.
detours will not detect the inner function is a import vector or something after a long jmp.
So it does fail when hook a x64 function on that condition.

But also come up with a small patch for detour_skip_jmp.
https://cdn1.imggmi.com/uploads/2019/10/24/8a2798e183931867e343354ff3c746bd-full.png

x86_asm_code:
https://cdn1.imggmi.com/uploads/2019/10/24/7dfbcfd5408c4a327b871648f9cc3709-full.png

x64_asm_code:
https://cdn1.imggmi.com/uploads/2019/10/24/c8d92586582d0bc4b45e107f769ff9a6-full.png

Issue when re-setting instruction pointer after hook removal in AMD64 architecture

Hello,
Detours provides the very convenient capability to suspend other threads than the one doing the unhooking,
And will update the instruction pointer of these suspended threads if they happen to be executing a trampoline that is being removed.

The issue I am seeing happens on AMD64 architectures in a multithreaded environment.
Since the hooks are more direct in X86, I am almost certain that it cannot happen in X86. I have no idea about ARM architectures.

On AMD64 processors, the hooks jump to the following pattern “0xff 25 f2 ff ff ff”, i.e.
“jmp qword [rip-0xe]”, with “rip-0xe” containing the address of the function that we wish to call.

I observe that when Rip points to the instruction above in one of the suspended threads, and the hook is removed, Detours does not update Rip in the thread context.
Rip is only updated in the suspended thread context if it pointed to an instruction inside the trampoline being deleted.
Here, the “jmp qword [rip-0xe]” is not inside the trampoline, so no updating of Rip takes place.
But when the thread is resumed, the memory containing the instruction or address has been deleted or zeroed out by the unhooking thread --> there will be a crash.

Possible errors

Detours/src/detours.cpp

Lines 1761 to 1764 in edc8b07

if (cxt.DETOURS_EIP >= (DETOURS_EIP_TYPE)(ULONG_PTR)o->pTrampoline &&
cxt.DETOURS_EIP < (DETOURS_EIP_TYPE)((ULONG_PTR)o->pTrampoline
+ sizeof(o->pTrampoline))
) {

V568 It's odd that 'sizeof()' operator evaluates the size of a pointer to a class, but not the size of the 'o->pTrampoline' class object. detours.cpp 1763

Would someone knowledgeable with the code check the presence of the error in this code block?

There is a large number of PVS-Studio messages, but this one is on a (relatively) hot execution path.

List of all other High-priority messages:

V595 The 'o->pTrampoline' pointer was utilized before it was verified against nullptr. Check lines: 1802, 1805. detours.cpp 1802
V763 Parameter 'pEntry' is always rewritten in function body before being used. disasm.cpp 448
V763 Parameter 'pEntry' is always rewritten in function body before being used. disasm.cpp 592
V730 Not all members of a class are initialized inside the constructor. Consider inspecting: m_nSegmentOverride, m_lScratchExtra, m_pbScratchTarget, m_rbScratchDst. disasm.cpp 328
V595 The 'pcbData' pointer was utilized before it was verified against nullptr. Check lines: 549, 554. image.cpp 549
V568 It's odd that 'sizeof()' operator evaluates the size of a pointer to a class, but not the size of the 'piidDst' class object. image.cpp 1836
V512 A call of the 'memset' function will lead to underflow of the buffer 'piidDst'. image.cpp 1836
V512 A call of the 'memset' function will lead to underflow of the buffer 'piidDst'. image.cpp 1878

Feature: DetourFindRemotePayload and DetourFindRemotePayloadEx for remote process.

In my use-case, it's possible that a DLL gets injected and uninjected multiple times in the target process's lifetime. I want to add a payload to the target process for my DLL to check if it is in the target process rather than the injecting process which uses SetWindowsHookEx to ensure that the DLL is uninjected by the system if my process dies because the detour is used to transmit information to my application, so it is not useful (or cannot live at all) if my application is not running. SetWindowsHookEx requires that I need to load the DLL in the injecting process.

Since it's possible for the DLL to be uninjected, calling DetourCreateRemotePayload each time it needs to be injected will pollute the process with multiple copies of the magic payload. I cannot use a static boolean variable to track if the remote payload exists, because the case where the DLL gets injected or uninjected is either my process or the target process starting or closing (my process restarting would reset that boolean variable)

Currently, I would need to copy DetourFindPayload's implementation to my own code as well as using CreateToolhelp32Snapshot (or use ReadProcessMemory and read the module headers) to know if the payload already exists in the target process.

This should be a feature of Detours and the signature of the two functions should be the same than the in-process ones, except the void pointer returned is suitable for further reading or writing via ReadProcessMemory or WriteProcessMemory. This would have the side effect of allowing some sort of live configuration system for the detour, where the detour can just read configuration from the payload and the injector can write to it to dynamically change the behavior of the detour instead of having to establish another method of communication with the injector process (which would have been more complex for both parties).

Can't build the detours library because it can't see syelogd.cpp file

When I try to build the detours library the build fails with can't open file: syelogd.cpp inspite it is available in the folder it CDed to it.
Here is the log :

cd "D:\Silkroad bot\Detours-master"
cd "D:\Silkroad bot\Detours-master\src"
cl /W4 /WX /Zi /MT /Gy /Gm- /Zl /Od /DWIN32_LEAN_AND_MEAN /D_WIN32_WINNT=0x501 /Fd..\lib.X86\detours.pdb /Foobj.X86\ /c detours.cpp modules.cpp disasm.cpp image.cpp creatwth.cpp disolx86.cpp disolx64.cpp disolia64.cpp disolarm.cpp disolarm64.cpp 
detours.cpp
modules.cpp
disasm.cpp
image.cpp
creatwth.cpp
disolx86.cpp
disolx64.cpp
disolia64.cpp
disolarm.cpp
disolarm64.cpp
Generating Code...
	link /lib /out:..\lib.X86\detours.lib obj.X86\detours.obj      obj.X86\modules.obj      obj.X86\disasm.obj       obj.X86\image.obj        obj.X86\creatwth.obj     obj.X86\disolx86.obj     obj.X86\disolx64.obj     obj.X86\disolia64.obj    obj.X86\disolarm.obj     obj.X86\disolarm64.obj
Microsoft (R) Library Manager Version 14.16.27030.1
Copyright (C) Microsoft Corporation.  All rights reserved.

	copy detours.h ..\include\detours.h
        1 file(s) copied.
	copy detver.h ..\include\detver.h
        1 file(s) copied.
	cd "D:\Silkroad bot\Detours-master\samples"
	cd "D:\Silkroad bot\Detours-master\samples\syelog"
	copy syelog.h ..\..\include\syelog.h
        1 file(s) copied.
	cl /nologo /Zi /MT /Gm- /W4 /WX /Od /I..\..\include /Fdobj.X86\vc.pdb /Foobj.X86\ /c syelog.cpp 
syelog.cpp
	link /lib /nologo /out:..\..\lib.X86\syelog.lib obj.X86\syelog.obj
	cd ..\..\src
	nmake /nologo
	cd D:\Silkroad bot\Detours-master\samples\syelog
	cl /nologo /Zi /MT /Gm- /W4 /WX /Od /I..\..\include /Fdobj.X86\vc.pdb /Foobj.X86\ /c syelogd.cpp 
syelogd.cpp
c1xx: fatal error C1083: Cannot open source file: 'syelogd.cpp': No such file or directory

image

Distribute Detours on NuGet

Distributing Detours on NuGet would make acquiring, updating and using it much easier than storing third-party binaries and headers in our GitHub repository.

Bug in findfunc\extend.cpp

Extend.cpp is built into extend64.dll for x64, and extend86.dll for x86, but the code in extend.cpp references the dll without specifying the DETOURS_BITS in the dll name. The DetourFindFunction fails because of this.

static int WINAPI ExtendEntryPoint()
{
...
TrueTarget = (DWORD (WINAPI *)(DWORD)) DetourFindFunction("target.dll", "Target");
...
TrueHidden = (DWORD (WINAPI *)(DWORD)) DetourFindFunction("target.dll", "Hidden");
...
}

The 2 places should be changed to use the DETOURS_BITS as follows

TrueTarget = (DWORD (WINAPI *)(DWORD)) DetourFindFunction("target" **DETOURS_STRINGIFY(DETOURS_BITS)** ".dll", "Target");

TrueHidden = (DWORD (WINAPI *)(DWORD)) DetourFindFunction("target" **DETOURS_STRINGIFY(DETOURS_BITS)**  ".dll", "Hidden");

Update wiki with new information for debugging

Hi,
I am unsure how to contribute to the wiki since I do not have write access to it, but here is a suggestion for improvement of the FAQ page.

In the How can I debug the startup of my detour DLL? it only mentions Windbg, it is however possible to use Visual Studio too.

I suggest adding the following paragraph at the end.

It is also possible to debug child processes in Visual Studio by using the Microsoft Child Process Debugging Power Tool official extension.

NMAKE : fatal error U1077: 'if' : return '0x1'

I try to build the Detours Express 3.0.
I use the win10 system.

In the path C:\Program Files (x86)\Microsoft Research\Detours Express 3.0\src>
Try to command nmake.

How can I modify this fatal error U1077
The system return as below.
NMAKE : fatal error U1077: 'if' : return '0x1'
Stop.

Slow injection into Control-Flow-Guard-enabled program

Summary

Executing DetourCreateProcessWithDllW and WaitForSingleObject(process_handle) on a CFG-enabled program (such as cmd.exe, xcopy.exe, etc.) is much slower than doing so on a CFG-disabled program: ~120ms vs. ~7ms on my experiment.

Environment

  • Windows 10 Pro 1803 (Build 17134.376)
  • Visual Studio 2017 15.8.9
  • cl 19.15.26732.1 for x64

Repro Program

  • Extract slow-injection-cfg.zip into a folder under the work tree root.

  • nmake, cd bin, then repro

  • This program first executes DetourCreateProcessWithDllW on a CFG-disabled program (noop.exe) then do the same on a CFG-enabled program:

    ### ACTUAL RUN
    Running 100 times : C:\home\refs\Detours\slow-injection-cfg\bin\noop.exe
    ->   721.97 ms
    Running 100 times : C:\home\refs\Detours\slow-injection-cfg\bin\noop-cfg.exe
    -> 12895.74 ms
    

For convenience, I pushed the program at : https://github.com/asmichi/Detours/tree/slow-injection-into-cfg-program/slow-injection-cfg

DetourBinaryWrite doesn't handle .bss segments correctly

This type of segment has a data size in memory (SizeOfRawData > 0) but stores no data in the object file itself.
The problem occurs when Image::Write tries to write the segment to the file. A check needs to made for PointerToRawData == NULL

Can this detect when a external process creates (with CreateRemoteThread), suspends, and terminates threads?

I been working on a library that does just this, however it seems my current inplementation (a thread count system) seems to crash. Although it could be the loaded dll's check too since sometimes the dll's it finds gets some really jumbled up file names and paths despite running through GetModuleFileNameA/W (I do not remember if I am using the Unicode one or not as I provide A and W options of my library functions too).

Basically I want this sort of check to where it returns some values indicating from my library that someone is modifying the process externally and allow the process to handle the closing, possible report the user to a server in case of them trying to hack a game with some hack tool or w/e.

All my other functions work perfectly fine. Also I tend to keep this library closed source, although I do not have any sort of version control on it which is stupid in case of hdd crash. I should store it in a private GitLab or bitbucket repository 🤔.

I want to know this so that way I can get the idea why the thread stuff seems to not work.

DetourCreateProcessWithDllEx usage for both 32-bit & 64-bit processes

Today I tried to use detour in my sample application. What I did is,

  1. Created DLL which has to be loaded into target process and build 2 Dlls for both 32-bit & 64-bit. i.e. foo32.dll & foo64.dll
  2. I am using "withdll" sample provided in sample folder and compiled both 32-bit & 64-bit process.

According to the documentation "https://github.com/Microsoft/Detours/wiki/DetourCreateProcessWithDllEx", DetourCreateProcessWithDllEx (or) DetourCreateProcessWithDlls will pick up correct dll based on process i.e. either 32-bit or 64-bit process. But when I tried to pass the "foo32.dll" as parameter to the above function to hook to 64-bit winword process, it is failing saying it can't load.

When used the foo64.dll as parameter to 64-bit winword process, without issue, winword running fine.

could anybody please check is there anything I am missing?

Thanks,
Lakshman.

member.exe is detected as Trojan:Win32/Skeeyah.A!MTB by Windows Defender

Here it is in VirusTotal https://www.virustotal.com/gui/file/255d34ac5786570b9066e325cb8bb2bac34411650ebfbac0906d315c516d3397/summary

Some users of the Vortex mod manager program are discussing this problem here https://forums.nexusmods.com/index.php?/topic/7873523-vortex-v10-only-trojan-virus-in-memberexe/

The program is using a version of the exe built by this project https://github.com/Nexus-Mods/node-native-errors/blob/master/build_detours.js

The path to the file is .\Vortex\resources\app.asar.unpacked\node_modules\native-errors\Detours\bin.X64\member.exe

The download link for this program is here https://www.nexusmods.com/site/mods/1?tab=files

Access violation after return from hooked SetClipboardData function

I am using detours to intercept clipboard functions and the dll is loading fine. But after SetClipboardData function called multiple times, after returning from the function am getting access violation in RtlAllocateHeap().

What am actually doing is

  1. when SetClipboardData() called, if the call is from particular document, am calling Real SetClipboardData function with my own format and my own global handle (allocated using GlobalAlloc(2,32)) and return new handle.
  2. otherwise, calling Real SetClipboardData() with original parameters and return new handle.
  3. In GetClipboardData(), if again the document is in my list, I'll return original handle which was stored from previous SetClipboardData() call.

Could anybody please help me to find what I am doing wrong here?

Thanks.

The traceapi sample cannot detour a 32-bit child process from a 64-bit process

The traceapi sample cannot detour a 32-bit child process from a 64-bit process (and vice versa) since it calls DetourCreateProcessWithDllA/W instead of the 'Ex' versions in Mine_CreateProcessA/W (https://github.com/Microsoft/Detours/blob/master/samples/traceapi/_win32.cpp).

I believe that the intent here is to call the 'Ex' versions since the sample performs the DetourIsHelperProcess check in the DllMain.

Repro steps

NOTE: Please make sure to copy trcapi32.dll into bin.X64.

E:\home\refs\Detours\bin.X64>withdll.exe /d:trcapi64.dll cmd
withdll.exe: Starting: `cmd'
withdll.exe:   with `E:\home\refs\Detours\bin.X64\trcapi64.dll'
Microsoft Windows [Version 10.0.17134.48]
(c) 2018 Microsoft Corporation. All rights reserved.

E:\home\refs\Detours\bin.X64>c:\windows\SysWOW64\cmd
The system cannot execute the specified program.

Isn't there a possible deadlock issue with DetourUpdateThread and DetourTransactionCommit?

I notice that both DetourUpdateThread and DetourTransactionCommit use new and delete in their code. Assuming these eventually translate to calls to GlobalAlloc and GlobalFree, isn't it possible for deadlock to occur if a thread previously suspended by DetourUpdateThread currently holds a lock on the default heap? This could be avoided by having Detours allocate its own heap with CreateHeap and using that heap for all allocations that occur during a transaction.

detours.h error Unknown architecture (x86, amd64, ia64, arm, arm64)

when I include detours.h, report Unknown architecture (x86, amd64, ia64, arm, arm64) when compile.
after I add
#define X86
the compile report so many error

d:\detours\include\detours.h(267): error C2061: 语法错误: 标识符“DWORD”
1>d:\detours\include\detours.h(268): error C2061: 语法错误: 标识符“Data2”
1>d:\detours\include\detours.h(268): error C2059: 语法错误:“;”
1>d:\detours\include\detours.h(269): error C2061: 语法错误: 标识符“Data3”
1>d:\detours\include\detours.h(269): error C2059: 语法错误:“;”
1>d:\detours\include\detours.h(270): error C2061: 语法错误: 标识符“Data4”
1>d:\detours\include\detours.h(270): error C2059: 语法错误:“;”
1>d:\detours\include\detours.h(270): error C2059: 语法错误:“[”
1>d:\detours\include\detours.h(271): error C2059: 语法错误:“}”
1>d:\detours\include\detours.h(312): error C2061: 语法错误: 标识符“DETOUR_EXE_RESTORE_GUID”
1>d:\detours\include\detours.h(312): error C2059: 语法错误:“;”
...................
but the detours/sample are compiled ok.i do not know why~
I use win7 VS2017

I would appreciate it if you could help this problem

With Regards

Hooking works for Windows 10 users, but not for Windows 7

Code:

bool redirect(bool enable, void **function, void *redirection)
{
	if(DetourTransactionBegin() != NO_ERROR)
	{
		return false;
	}

	if(DetourUpdateThread(GetCurrentThread()) != NO_ERROR)
	{
		return false;
	}

	if((enable? DetourAttach:DetourDetach)(function, redirection) != NO_ERROR)
	{
		return false;
	}

	if(DetourTransactionCommit() == NO_ERROR)
	{
		return true;
	}

	DetourTransactionAbort();

	return false;
}

typedef int(__stdcall *IsCorrectItem_t)(int);
IsCorrectItem_t g_real_IsCorrectItem = reinterpret_cast<IsCorrectItem_t>(0x005D4A2B);

int __stdcall hooked_IsCorrectItem(int nItemID)
{
	return 0;
}

// inside my function
detours::redirect(true, reinterpret_cast<void **>(&g_real_IsCashItem), hooked_IsCorrectItem);

This seems to be perfectly fine on Windows 10, but on Windows 7 it simply doesn't work. I installed the static Detours library through vcpkg.

Question - Releases

Will there actually a formal source code release on GitHub (i.e. under the 'Releases' area) for this new iteration of Detours?

Add minimal sample for detouring malloc

It would be great if there was a minimal sample which intercepts malloc and shows how to run code before and after the original malloc. In the sample it could be just a printf of the requested size and (after malloc did run) the obtained memory address.

I would find this especially useful as the FAQ has an entry on malloc.

bug in DetourAttach, after invoke it return ERROR_ACCESS_DENIED

call DetourAttach failed, then I modified the following code of DetourAttachEx Function:
DWORD v7 = GetCurrentProcessId();
HANDLE hProcess = OpenProcess(0x1F0FFF, 0, v7);
if (!VirtualProtectEx(hProcess, pbTarget, cbTarget, PAGE_EXECUTE_READWRITE, &dwOld)) {
error = GetLastError();
DETOUR_BREAK();
goto fail;
}

and it worked!

sn.exe not found

Window 10
VS2017 15.8.9
SDK 10.0.17763.0
VC++ 15.8 v14.15

git clone https://github.com/Microsoft/Detours.git
cd Detours
nmake

Got an error:

if not exist ..\..\bin.X64\key.snk sn -k ..\..\bin.X64\key.snk
'sn' is not recognized as an internal or external command,
operable program or batch file.
NMAKE : fatal error U1077: 'if' : return code '0x1'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX64\x64\nmake.exe"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX64\x64\nmake.exe"' : return code '0x2'
Stop.

DetourCreateProcessWithDllsW with LPCWSTR dll names

Hello Detours Team,

currently, it is not possible to call DetourCreateProcessWithDllsW with wide character dll names, because DetourCreateProcessWithDllsW uses LPCSTR and StringCchLengthA to count the dll name length. Please change the DetourCreateProcessWithDllsW, so that it can consume wide chars for dll names respectively.

Thank you!

BOOL WINAPI DetourCreateProcessWithDllsW(_In_opt_ LPCWSTR lpApplicationName,

Ununderstandable documents (wiki)

There is a link to simple file in Home page in wiki, and there is no example in simple sample page, it has a link to home page again. There are four technical section which need to read by developers new to detours, but those sections give no information on how to get started with Detours.

Please improve the wiki, provide a useful example showing How to get started with Detours

Compiling Detours on MinGW

I'm pretty close to getting this to work. I had to remove some MSVC-specific cruft from the header file to work around some duplicated typedefs when _MSVC_VER is undefined.

The only remaining sticking point is dealing with SEH calls. MinGW does not port these, and I'm unsure what the workaround might be.

For reference, these are the errors:

detours.cpp: In function 'bool detour_is_imported(PBYTE, PBYTE)':
detours.cpp:44:5: error: '__try' was not declared in this scope
     __try {
     ^~~~~
detours.cpp:68:5: error: '__except' was not declared in this scope
     __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
     ^~~~~~~~
detours.cpp:68:5: note: suggested alternative: 'accept'
     __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
     ^~~~~~~~
     accept

I'm trying to compile under MinGW to support interoperability with Kotlin, which can only compile under MinGW. Although MinGW has some support for interoperability with binaries compiled under MSVC, there are still issues with undefined symbols if you go that route.

Has anyone successfully compiled Detours with MinGW? If so what was your workaround for this?

I don't understand the content of “disasm.cpp”, especially these flags and macro definitions, what are they used for?

// nFlagBits flags.                 
enum {
    DYNAMIC     = 0x1u,
    ADDRESS     = 0x2u,
    NOENLARGE   = 0x4u,
    RAX         = 0x8u,
};

// ModR/M Flags
enum {
    SIB         = 0x10u,
    RIP         = 0x20u,
    NOTSIB      = 0x0fu,
};
...
#define ENTRY_CopyBytes1Dynamic     1, 1, 0, 0, DYNAMIC, &CDetourDis::CopyBytes
#define ENTRY_CopyBytes2            2, 2, 0, 0, 0, &CDetourDis::CopyBytes
#define ENTRY_CopyBytes2Jump        ENTRY_DataIgnored &CDetourDis::CopyBytesJump
#define ENTRY_CopyBytes2CantJump    2, 2, 0, 1, NOENLARGE, &CDetourDis::CopyBytes
#define ENTRY_CopyBytes2Dynamic     2, 2, 0, 0, DYNAMIC, &CDetourDis::CopyBytes
#define ENTRY_CopyBytes3            3, 3, 0, 0, 0, &CDetourDis::CopyBytes
#define ENTRY_CopyBytes3Dynamic     3, 3, 0, 0, DYNAMIC, &CDetourDis::CopyBytes
#define ENTRY_CopyBytes3Or5         5, 3, 0, 0, 0, &CDetourDis::CopyBytes
...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.