views:

290

answers:

2

Operating System: Windows XP 64 bit, SP2.

I have an unusual problem. I am porting some code from 32 bit to 64 bit. The 32 bit code works just fine. But when I call CreateThread() for the 64 bit version the call fails. I have three places where this fails. 2 call CreateThread(). 1 calls beginthreadex() which calls CreateThread().

All three calls fail with error code 0x3E6, "Invalid access to memory location".

The problem is all the input parameters are correct.

HANDLE  h;
DWORD   threadID;

h = CreateThread(0,            // default security
                 0,            // default stack size
                 myThreadFunc, // valid function to call
                 myParam,      // my param
                 0,            // no flags, start thread immediately
                 &threadID);

All three calls to CreateThread() are made from a DLL I've injected into the target program at the start of the program execution (this is before the program has got to the start of main()/WinMain()). If I call CreateThread() from the target program (same params) via say a menu, it works. Same parameters etc. Bizarre.

If I pass NULL instead of &threadID, it still fails.

If I pass NULL as myParam, it still fails.

I'm not calling CreateThread from inside DllMain(), so that isn't the problem. I'm confused and searching on Google etc hasn't shown any relevant answers.

If anyone has seen this before or has any ideas, please let me know.

Thanks for reading.

ANSWER

Short answer: Stack Frames on x64 need to be 16 byte aligned.

Longer answer: After much banging my head against the debugger wall and posting responses to the various suggestions (all of which helped in someway, prodding me to try new directions) I started exploring what-ifs about what was on the stack prior to calling CreateThread(). This proved to be a red-herring but it did lead to the solution.

Adding extra data to the stack changes the stack frame alignment. Sooner or later one of the tests gets you to 16 byte stack frame alignment. At that point the code worked. So I retraced my steps and started putting NULL data onto the stack rather than what I thought was the correct values (I had been pushing return addresses to fake up a call frame). It still worked - so the data isn't important, it must be the actual stack addresses.

I quickly realised it was 16 byte alignment for the stack. Previously I was only aware of 8 byte alignment for data. This microsoft document explains all the alignment requirements.

If the stackframe is not 16 byte aligned on x64 the compiler may put large (8 byte or more) data on the wrong alignment boundaries when it pushes data onto the stack.

Hence the problem I faced - the hooking code was called with a stack that was not aligned on a 16 byte boundary.

Quick summary of alignment requirements, expressed as size : alignment

  • 1 : 1
  • 2 : 2
  • 4 : 4
  • 8 : 8
  • 10 : 16
  • 16 : 16

Anything larger than 8 bytes is aligned on the next power of 2 boundary.

I think Microsoft's error code is a bit misleading. The initial STATUS_DATATYPE_MISALIGNMENT could be expressed as a STATUS_STACK_MISALIGNMENT which would be more helpful. But then turning STATUS_DATATYPE_MISALIGNMENT into ERROR_NOACCESS - that actually disguises and misleads as to what the problem is. Very unhelpful.

Thank you to everyone that posted suggestions. Even if I disagreed with the suggestions, they prompted me to test in a wide variety of directions (including the ones I disagreed with).

Written a more detailed description of the problem of datatype misalignment here: 64 bit porting gotcha #1! x64 Datatype misalignment.

+1  A: 

The only reason that 64bit would make a difference is that threading on 64bit requires 64bit aligned values. If threadID isn't 64bit aligned, you could cause this problem.


Ok, that idea's not it. Are you sure it's valid to call CreateThread before main/WinMain? It would explain why it works in a menu- because that's after main/WinMain.

In addition, I'd triple-check the lifetime of myParam. CreateThread returns (this I know from experience) long before the function you pass in is called.


Post the thread routine's code (or just a few lines).


It suddenly occurs to me: Are you sure that you're injecting your 64bit code into a 64bit process? Because if you had a 64bit CreateThread call and tried to inject that into a 32bit process running under WOW64, bad things could happen.


Starting to seriously run out of ideas. Does the compiler report any warnings?


Could the bug be due to a bug in the host program, rather than the DLL? There's some other code, such as loading a DLL if you used __declspec(import/export), that occurs before main/WinMain. If that DLLMain, for example, had a bug in it.

DeadMG
I've just re-tested this. On one of the calls threadID is 64 bit aligned. It still fails. threadID should not be an issue anyway as it is a DWORD value and the parameter pointing to it is a pointer (a 64 bit value).
Stephen Kellett
Alignment has a minimum of sizeof, but in some scenarios it must be extended. Many threading values must have an alignment of (address width). http://msdn.microsoft.com/en-us/library/ms684122(v=VS.85).aspxEdit: Didn't see that you re-tested it.
DeadMG
@Stephen - for a quick test try passing NULL for the thread ID pointer and see if the problem goes away.
Michael Burr
If threadID param is set to NULL rather than the address of threadID it still fails.
Stephen Kellett
myParam is valid. Absolutely sure. Its valid for the lifetime of the target application. It can't go out of scope or be deleted.Before main/winMain? I don't know. Its valid for 32 bit and I see no logical reason why it would not be for 64 bit. The WINAPI is letting me do more dangerous things than CreateThread without problems (such as loading my DLL to do the work I need to do). Thus I doubt that is the issue. I do wonder if Windows has added some extra security checks and it is those that are failing for me.
Stephen Kellett
No point posting the thread routine's code - it never gets called, hence why I'm trying to find out why the CreateThread() call fails. The routine will only ever get called if it succeeds. All functions are aligned 64 bits by the compiler, so that isn't the problem (and I have checked that in the debugger).
Stephen Kellett
@DeadMG. Yes I am injecting into a 64 bit process. You can't load a 64 bit DLL into a 32 bit process. Anyway, my injector checks the type of PE file beforehand and will refuse if you offer it a process that is 32 bit.
Stephen Kellett
@DeadMG. No compiler warnings. The same code works if called later on in the program lifetime.
Stephen Kellett
A: 

Try using _beginthread() or _beginthreadex() instead, you shouldn't be using CreateThread directly.

See this previous question.

Chris O
Chris, this is the wrong answer. I know if I should be using CreateThread of beginthreadex() and the answer is CreateThread(). If you read the question, you will see that eventually I answered the question itself (stack misalignment). Finally, calling beginthread() would still fail because as I indicate in the answer the stack is misaligned (and would still be misaligned by the time the call to CreateThread is made from the call to beginthread).
Stephen Kellett
Post your solution comment and set it as an answer then, so people can actually find it (and my comment still holds, don't use CreateThread, you can google why ;-)- Many thanks.
Chris O