views:

231

answers:

4

Would somebody please tell me whats wrong with this code I am just calling a Sleep function from the kernel32.dll What's wrong? I am using Visual Studio 2008. Any help would be grateful. Thank you very much.

__asm
{
    mov eax, 77e2ef66h
    push 9999
    call eax
}
+6  A: 

Where did you get that magic number, 77e2ef66h? Usually if you're calling Win32 API functions from inline assembler, you'd do something like:

__asm 
{ 
    push 9999 
    call Sleep
} 

Functions in Win32 do not have a fixed address (regardless of what your "DLL Export Viewer" might show). Functions are linked by name or ordinal at load time (by the Windows PE loader) and are not located at fixed addresses. In fact, the actual address of functions can change between versions of Windows, subreleases within the same version of Windows, from machine to machine, and even possibly from one run of your program to the next.

(Disclaimer: It's been a very long time since I've done this, so the details of the above code example are undoubtedly wrong, but I know that you definitely don't need to use magic numbers.)

Greg Hewgill
A: 

it's the function adress in the kernel32.dll

here you can see exactly what i mean http://www.freeimagehosting.net/uploads/091b0938d1.jpg

thank you

JoeyAbra
Avoid using a hard-coded function address: the address can change from one run to the next, or from one machine to the next. Instead, use the symbolic address ("Sleep") and let the dynamic linker do its job.
ChrisW
Welcome to Stack Overflow! I've amended my answer above. To comment on specific answers, use the "add comment" link below the answer, instead of adding a *new* answer.
Greg Hewgill
A: 

Yes you are right then the code would look like that

_asm
{
    push 999
    call dword ptr[Sleep]
}

but what if i'd like to use the register address, then my firstly posted code would not be wrong, would it?

Thank you

JoeyAbra
Your original code would be wrong. Function addresses are not constant in Windows.
Greg Hewgill
If you'd like to use the register address, then I think your code should be something like "mov eax,Sleep ... call eax"
ChrisW
A: 

I'd like to thank you all for your answers

The problem is that, what if I am using e.g. the gcc compiler to compile without .NET, then Sleep wouldn't be declared, right?

then I'd have to use the register address, right?

JoeyAbra
Sleep is a Win32 API function. It doesn't require .NET.Also, that is a comment, not an answer. I'd suggest making a comment to the answer that sparked this response and deleting this non-answer.
Judge Maygarden
Using MSVC (and, I guess, also when using gcc), `Sleep` is declared if you "#include <windows.h>" in your source file, and pass "Kernel32.lib" as one of the input libraries to the linker.
ChrisW