The MASM Forum Archive 2004 to 2012

General Forums => The Campus => Topic started by: DeadlyVermilion on August 22, 2010, 02:08:51 PM

Title: Translating Invoke With GetProcAddress
Post by: DeadlyVermilion on August 22, 2010, 02:08:51 PM
Hey there people, I'm trying to learn how to call API's Dynamically to reduce the amount I have declared.
So I am having problems trying to push an addr

This is the info of what I am trying to push.

LOCAL sinfo: STARTUPINFO

invoke GetProcAddress, xKernel32, addr lpszZeroMemory
mov xZeroMemory, eax
push sizeof STARTUPINFO
lea eax, sinfo
push eax
Call xZeroMemory


Can somebody please tell me why this crashes? I have tried debugging in OllyDebug and I know that it is due to this call on xZeroMemory, I also know it has something to do with my pushing sinfo.

Any help to resolve this problem will be warmly thanked.
Title: Re: Translating Invoke With GetProcAddress
Post by: ragdog on August 22, 2010, 02:43:21 PM
I cannot get with your source by Getprocadress no return value
Now have i look in the kernel32.dll and this have no ZeroMemory

(http://img121.imageshack.us/img121/3118/unbenannthl.png)
Title: Re: Translating Invoke With GetProcAddress
Post by: DeadlyVermilion on August 22, 2010, 02:50:16 PM
Sorry, I don't understand what your trying to say. Please tell me more?
Title: Re: Translating Invoke With GetProcAddress
Post by: ragdog on August 22, 2010, 03:01:38 PM
I have look in the kernel32.dll and cannot find the zeromemory api
This can you see in my screenshot

And your code by getprocadress  is the return value  NULL

You can check it

invoke LoadLibrary,CTEXT ("kernel32.dll")
mov xKernel32,eax
invoke GetProcAddress, eax, CTEXT ("ZeroMemory")
.if eax
   mov xZeromemory,eax

.else
        invoke MessageBox,0,CTEXT ("Cannot get procedur adress from zeromemory"),0,MB_OK
.endif

Use RtlZeroMemory

I hope now have you this understanding
Title: Re: Translating Invoke With GetProcAddress
Post by: Yuri on August 22, 2010, 03:03:07 PM
Actually the function is named RtlZeroMemory.
Title: Re: Translating Invoke With GetProcAddress
Post by: DeadlyVermilion on August 22, 2010, 03:28:19 PM
I am using RtlZeroMemory, Sorry I forgot to put that down. Can someone please tell me what is wrong with my code though?
Title: Re: Translating Invoke With GetProcAddress
Post by: dedndave on August 22, 2010, 03:50:09 PM
ZeroMemory and RtlZeroMemory are macros, i believe
getting a proc address to a macro may not work so well   :P
you can check for an error condition after the GetProcAddress call, then use GetLastError, to debug it

can you attach code that is a bit more complete so that we can see xKernel32 and lpszZeroMemory?
i can assume that xZeroMemory is defined as a dword
Title: Re: Translating Invoke With GetProcAddress
Post by: ragdog on August 22, 2010, 03:50:24 PM
I think this works


LOCAL sinfo: STARTUPINFO

.data?
xKernel32 dd ?
xZeroMemory dd ?

.code
invoke LoadLibrary,CTEXT ("kernel32.dll")
.if eax
      mov xKernel32,eax
   invoke GetProcAddress, eax, CTEXT ("RtlZeroMemory")
      .if eax
           mov [xZeroMemory], eax

          push sizeof STARTUPINFO
           lea eax,sinfo
          push  eax
          Call [xZeroMemory]
        .else
             invoke MessageBox,0,CTEXT("Cannot Get procedur adress from RTLZeroMem"),0,MB_OK
      .endif
      invoke FreeLibrary,xKernel32
  .else
     invoke MessageBox,0,CTEXT("Cannot Load dll."),0,MB_OK
.endif


@dedndave

RTLZeroMemory if a macro? :eek

Title: Re: Translating Invoke With GetProcAddress
Post by: dedndave on August 22, 2010, 04:13:25 PM
well - according to msdn
but, i just made an exe - it looks like a proc, to me   :P

Deadly - ignore my previous post - lol

http://msdn.microsoft.com/en-us/library/aa366920%28VS.85%29.aspx

QuoteThis macro is defined as the RtlZeroMemory macro. For more information, see Winbase.h and Winnt.h.

the sentance, alone, makes no sense   :lol
Title: Re: Translating Invoke With GetProcAddress
Post by: Twister on August 22, 2010, 04:17:06 PM
include \masm32\include\masm32rt.inc

Main proto

.data

    strMsvcrt DB "msvcrt.dll",0
    strMemset DB "memset",0

.code

Main proc
    LOCAL sinfo:STARTUPINFO
    LOCAL ptr_memset:DWORD

    .if FUNC(GetProcAddress, FUNC(LoadLibrary, offset strMsvcrt), offset strMemset)
        mov ptr_memset, eax
       
        push sizeof sinfo
        push 0
        lea eax, sinfo
        push eax
        call ptr_memset    ; memset ( void * ptr, int value, size_t num )
       
    .endif

    invoke ExitProcess, 0
Main endp
   
end Main
Title: Re: Translating Invoke With GetProcAddress
Post by: dedndave on August 22, 2010, 04:49:23 PM
i think i would use GetModuleHandle instead of LoadLibrary, no ?
        INCLUDE \masm32\include\masm32rt.inc

        .DATA

szKernel32  db 'kernel32.dll',0
szRtlZeroM  db 'RtlZeroMemory',0

        .CODE

_main   PROC

        LOCAL   sinfo:STARTUPINFO

        INVOKE  GetModuleHandle,offset szKernel32
        INVOKE  GetProcAddress,eax,offset szRtlZeroM
        push    sizeof sinfo
        lea     edx,sinfo
        push    edx
        call    eax

        INVOKE  ExitProcess,0

_main   ENDP

        END     _main
Title: Re: Translating Invoke With GetProcAddress
Post by: Twister on August 22, 2010, 05:00:21 PM
I used LoadLibrary because you need to load the library into your program. It returns the Library Base address after it has been located and loaded successfully.

You are using GetModuleHandle incorrectly. :wink
GetModuleHandle Function - Retrieves a module handle for the specified module. The module must have been loaded by the calling process.

Opps, didn't notice you were using kernel32. thought you were using msvcrt :lol
Title: Re: Translating Invoke With GetProcAddress
Post by: dedndave on August 22, 2010, 05:01:16 PM
it's kernel32 - already loaded   :bg
Title: Re: Translating Invoke With GetProcAddress
Post by: Twister on August 22, 2010, 05:02:01 PM
I used the CRT function memset from msvcrt.dll.  I find it quicker. :P
Title: Re: Translating Invoke With GetProcAddress
Post by: hutch-- on August 22, 2010, 05:03:27 PM
Vermilion,

The usual process when dynamically calling a function from a DLL is to call LoadLibrary(), check the return value to ensure it loaded corectly then call GetProcAddress() and test its return value. If the value is OK you can then call the function you are after as long as you know the correct argumnets to pass to it.

When you are finished with the function, use FreeLibrary() to release it and recover memory.
Title: Re: Translating Invoke With GetProcAddress
Post by: dedndave on August 22, 2010, 05:15:50 PM
maybe i am wrong, but i thought kernel32 was already loaded - and didn't require being Free'ed

Edgar ?  Erol ?
somebody back me up - lol
Title: Re: Translating Invoke With GetProcAddress
Post by: donkey on August 22, 2010, 05:36:22 PM
Quote from: dedndave on August 22, 2010, 04:13:25 PM
well - according to msdn
but, i just made an exe - it looks like a proc, to me   :P

Deadly - ignore my previous post - lol

http://msdn.microsoft.com/en-us/library/aa366920%28VS.85%29.aspx

QuoteThis macro is defined as the RtlZeroMemory macro. For more information, see Winbase.h and Winnt.h.

the sentance, alone, makes no sense   :lol

Though it exists as an export in ntdll, it is generally not used directly, in C++  it is a macro wrapping the memset function. Actually I think all of the Rtl memory macros are just wrappers for various C library functions even though they are available as part of the native API.

Quote from: dedndave on August 22, 2010, 05:15:50 PM
maybe i am wrong, but i thought kernel32 was already loaded - and didn't require being Free'ed

Edgar ?  Erol ?
somebody back me up - lol

Works either way, you can just use invoke GetModuleHandle, "kernel32.dll" and do not free the handle it returns. You can use LoadLibrary as well though in that case freeing the handle is necessary since the reference count was incremented. Kernel32 is always loaded and always loaded first.
Title: Re: Translating Invoke With GetProcAddress
Post by: Twister on August 22, 2010, 08:28:44 PM
Kernel32 is always loaded up, dave. you were right, and I was wrong. I thought it said "msvcrt.dll"; that is why I said you use GetModuleHandle incorrectly. It was a mistake on my part dave.

I would also like to add that ntdll.dll is always the first library to be loaded.
Title: Re: Translating Invoke With GetProcAddress
Post by: MichaelW on August 22, 2010, 11:23:15 PM
"Kernel32 is always loaded" seems to me to imply that this happens automatically for any EXE. If I assemble and link this source as a console app:

    .486
    .model flat, stdcall
    option casemap :none
    include \masm32\include\kernel32.inc
    includelib \masm32\lib\kernel32.lib
    .data
        xx dd 0
    .code
    ;invoke ExitProcess, 0
start:
    lea ebx, xx
    mov ecx, 100000000
    .WHILE ecx
        xchg eax, [ebx]
        dec ecx
    .ENDW
    ret
end start


I get an EXE with no imports, and which when run does not open a console. If I uncomment the statement that invokes ExitProcess, then the EXE shows one import, and runs normally.

Edit: The attachment contains both versions.

Title: Re: Translating Invoke With GetProcAddress
Post by: Twister on August 22, 2010, 11:37:56 PM
MichaelW,

Kernel32 is always loaded with an executable file.  Could you upload your assembled program here?  I just recently deleted my MASM32 package, so I can't assemble it myself.
Title: Re: Translating Invoke With GetProcAddress
Post by: dedndave on August 22, 2010, 11:47:28 PM
Michael
it seems to me that any win32 app has ExitProcess, unless it never exits   :P
i don't know how you'd write any kind of an app without using some kernel32 proc
but, i suppose the linker doesn't pull it in unless it is called
if you wanted to write ROMable code, for example (although - not supposed to do that per license - lol)
i have used older versions of MASM/LINK to create ROMable code - just haven't had a need to, recently
it is a bit odd that no console is created
it seems logical that the kernel would be responsible for loading the EXE and determining how to run it
Title: Re: Translating Invoke With GetProcAddress
Post by: MichaelW on August 22, 2010, 11:49:36 PM
Quote from: GTX on August 22, 2010, 11:37:56 PM
Kernel32 is always loaded.

How do you know this? Why does my test app run only if it contains a reference to a kernel32.dll function? Why does my test app run only if a dump of the EXE shows the name kernel32.dll?
Title: Re: Translating Invoke With GetProcAddress
Post by: Twister on August 22, 2010, 11:59:49 PM
Here is a program with no include or includelib directives used.

Debugger: process C:\Users\GTX\Desktop\wild_berries.exe has started
Debugger: loaded C:\Windows\system32\ntdll.dll
Debugger: loaded C:\Windows\system32\kernel32.dll
Debugger: loaded C:\Windows\system32\KernelBase.dll
Debugger: loaded C:\Windows\system32\apphelp.dll
Debugger: unloaded C:\Windows\system32\apphelp.dll
Title: Re: Translating Invoke With GetProcAddress
Post by: ecube on August 23, 2010, 12:01:54 AM
MichaelW kernel32.dll and ntdll.dll are automatically loaded in every processes address space, and I don't think you "have" to import a function from kernel32 for it to run but rather have atleast 1 import period.


start:
invoke MessageBox,0,NULL,NULL,MB_OK
ret
end start


should compile and run fine(even though it  may crash at the end)
Title: Re: Translating Invoke With GetProcAddress
Post by: Twister on August 23, 2010, 12:04:14 AM
I don't think you can put a null for the caption string for the MessageBox Function. I think it requires you to put it, or it will error.
Title: Re: Translating Invoke With GetProcAddress
Post by: ecube on August 23, 2010, 12:08:49 AM
Quote from: GTX on August 23, 2010, 12:04:14 AM
I don't think you can put a null for the caption string for the MessageBox Function. I think it requires you to put it, or it will error.

you can, I just tested the above, works fine and no kernel32 imports obviously, only user32
Title: Re: Translating Invoke With GetProcAddress
Post by: donkey on August 23, 2010, 12:11:59 AM
Quote from: MichaelW on August 22, 2010, 11:49:36 PM
Quote from: GTX on August 22, 2010, 11:37:56 PM
Kernel32 is always loaded.

How do you know this? Why does my test app run only if it contains a reference to a kernel32.dll function? Why does my test app run only if a dump of the EXE shows the name kernel32.dll?


Well, I guess it should say Kernel32 is always loaded in Win32/64 programs. Only ntdll.dll is always loaded regardless of the platform, saw it in Raymond Chen's blog once but can't find it now. Anyway since the source of the discussion is a call to GetProcAddress, you can be 100% sure that Kernel32 is already loaded since that function is in that library.

Edgar
Title: Re: Translating Invoke With GetProcAddress
Post by: MichaelW on August 23, 2010, 12:14:50 AM
Quote from: E^cube on August 23, 2010, 12:01:54 AM
MichaelW kernel32.dll and ntdll.dll are automatically loaded in every processes address space, and I don't think you "have" to import a function from kernel32 for it to run but rather have at least 1 import period.

Yes, thank you. A single reference to a user32.dll function is sufficient for my test app to run normally, without the dump showing the name kernel32.dll.
Title: Re: Translating Invoke With GetProcAddress
Post by: donkey on August 23, 2010, 12:30:31 AM
Quote from: MichaelW on August 23, 2010, 12:14:50 AM
Quote from: E^cube on August 23, 2010, 12:01:54 AM
MichaelW kernel32.dll and ntdll.dll are automatically loaded in every processes address space, and I don't think you "have" to import a function from kernel32 for it to run but rather have at least 1 import period.

Yes, thank you. A single reference to a user32.dll function is sufficient for my test app to run normally, without the dump showing the name kernel32.dll.


Ran the following program:

.data

.code
Start:
invoke user32.dll:MessageBoxA,0,"hello",0,0
ret


(http://a.imageshack.us/img44/2057/kern32.jpg)

The following load order was displayed in my GoP program:

1: NTDLL.DLL
2: KERNEL32.DLL
...
25: USER32.DLL
etc...


I think you would be hard pressed to find any function that does not have at least one dependency in Kernel32.
Title: Re: Translating Invoke With GetProcAddress
Post by: Twister on August 23, 2010, 12:59:43 AM
If you have Windows 7 32-bit this will run for you. Sorry everyone else. :P

^ I would make it more global, but hutch would kill me.

It uses absolutely no imports.
Title: Re: Translating Invoke With GetProcAddress
Post by: bomz on August 23, 2010, 01:07:36 AM
I don't well understand what are talking about
http://forum.codenet.ru/showthread.php?p=172896
This topic refers to the fact that MSDN GetProcAddress article have mistake.
Title: Re: Translating Invoke With GetProcAddress
Post by: Twister on August 23, 2010, 01:09:43 AM
I can't read Russian. :(
Title: Re: Translating Invoke With GetProcAddress
Post by: bomz on August 23, 2010, 01:12:57 AM
http://translate.google.ru/?hl=ru#
I can't help you quickly, because I don't understand sence of C code. I trying. Reading just now
In this code authors correct mistake
Quote
typedef  HRESULT (__stdcall*MYPROC)(LPUNKNOWN, LPCSTR, LPCSTR, DWORD, LPBINDSTATUSCALLBACK);
int main(int argc, char* argv[])
{
    MYPROC ProcAdd(NULL);
    HMODULE hLib = LoadLibrary(TEXT("urlmon.dll"));
    HRESULT hr (0);
    if (hLib)
    {
        ProcAdd = (MYPROC) GetProcAddress(hLib, "URLDownloadToFileA");
        if (ProcAdd) hr = ProcAdd(NULL, "http://www.google.com", "C:\\123.htm", 0, NULL);
        FreeLibrary(hLib);
    }   
    return hr;
}

Quote
not just the correct signature function that is referenced by a pointer and therefore you had an error stack pointer
????????????
Title: Re: Translating Invoke With GetProcAddress
Post by: Twister on August 23, 2010, 01:19:15 AM
All that does it get the address to "URLDownloadToFile" and calls it. I'm not sure what you don't get from that small piece of code.
Title: Re: Translating Invoke With GetProcAddress
Post by: Yuri on August 23, 2010, 01:56:12 AM
In that thread, nobody is talking about an MSDN error. The problem was first the wrong number of parameters for URLDownloadToFile and then the wrong calling convention for it (cdecl instead of stdcall).
Title: Re: Translating Invoke With GetProcAddress
Post by: donkey on August 23, 2010, 02:33:12 AM
Quote from: Yuri on August 23, 2010, 01:56:12 AM
In that thread, nobody is talking about an MSDN error. The problem was first the wrong number of parameters for URLDownloadToFile and then the wrong calling convention for it (cdecl instead of stdcall).

Not sure about the calling convention, it is listed as STDAPI in the headers which resolves to STDCALL, but having tested the function in a quick and dirty way:

PrintDec(esp)
invoke urlmon.dll:URLDownloadToFileA,0,0,0,0,0
PrintDec(esp)

it yeilds:

Line 29: esp = 1245020
Line 31: esp = 1245020

Which indicates that it is a STDCALL function and that it does have 5 parameters as indicated at MSDN and in urlmon.h

Edgar
Title: Re: Translating Invoke With GetProcAddress
Post by: Yuri on August 23, 2010, 03:39:54 AM
Quote from: donkey on August 23, 2010, 02:33:12 AM
Which indicates that it is a STDCALL function

Yes, exactly, but in that topic it was at first declared as cdecl. In fact, no convention was specified, but in C and C++ it defaults to cdecl, as far as I know.
Title: Re: Translating Invoke With GetProcAddress
Post by: donkey on August 23, 2010, 03:49:00 AM
Quote from: Yuri on August 23, 2010, 03:39:54 AM
Quote from: donkey on August 23, 2010, 02:33:12 AM
Which indicates that it is a STDCALL function

Yes, exactly, but in that topic it was at first declared as cdecl. In fact, no convention was specified, but in C and C++ it defaults to cdecl, as far as I know.

Not sure how it first appeared but the only docs I have show it returns an HRESULT which by definition is StdCall.
Title: Re: Translating Invoke With GetProcAddress
Post by: Yuri on August 23, 2010, 05:45:08 AM
Edgar, you are getting me wrong. What I am talking about is not MSDN or other MS docs, but the link that bomz gave a few posts ago: http://forum.codenet.ru/showthread.php?p=172896. There the topic starter first declared a cdecl function pointer with one parameter, but later assigned it to a pointer to URLDownloadToFile. Which, of course, is stdcall and takes 5 parameters, you are absolutely right about that. That is the creator of that topic on the Russian forum who was wrong, and also bomz when he wrote here:
Quote
This topic refers to the fact that MSDN GetProcAddress article have mistake.
Nobody in that topic says that the GetProcAddress article on MSDN has any mistakes.
Title: Re: Translating Invoke With GetProcAddress
Post by: donkey on August 23, 2010, 10:20:06 AM
Oh, I see now.
Title: Re: Translating Invoke With GetProcAddress
Post by: bomz on August 23, 2010, 10:48:42 AM
that article use frase something like that: msdn don't think about. I don't know how to translate it in english. "error" was bad translation

inaccuracy

this article and that article begin from the same frase
Hey there people, I'm trying to learn how to call API's Dynamically to reduce the amount I have declared.
Quote
Добрый день не могу разобрасться с ф-ей GetProcAddress делаю как в примере MSDN ничего не помогает вылазит ошибка:
http://translate.google.ru
Good afternoon, I can not deal with the function GetProcAddress do as in the example MSDN nothing helps climbs error:
Title: Re: Translating Invoke With GetProcAddress
Post by: Yuri on August 23, 2010, 12:22:21 PM
Quote from: bomz on August 23, 2010, 10:48:42 AM
that article use frase something like that: msdn don't think about. I don't know how to translate it in english. "error" was bad translation

Случайно не это имеете в виду?
Quote
ох не досмотрел MSDN
Это автор фразы не досмотрел как следует пример в MSDN. Поскольку в примере соглашение вызова указано (WINAPI == STDCALL):

typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);

Title: Re: Translating Invoke With GetProcAddress
Post by: bomz on August 23, 2010, 12:49:25 PM
ага. вот это. ну еще смешнее получилось.
Title: Re: Translating Invoke With GetProcAddress
Post by: hutch-- on August 24, 2010, 12:51:11 AM
Guys,

Tolerate me here, what does the content of an external site have to do with the API functions LoadLibrary(), GetProcAddress(), FreeLibrary() ?

The documentation and usage of these functions have been known for years and YES they are STDCALL.
Title: Re: Translating Invoke With GetProcAddress
Post by: Vortex on August 24, 2010, 06:56:49 PM
The application below without importing any function finds the address of kernel32.dll :


.386
.model flat,stdcall
option casemap:none

include     \masm32\include\windows.inc

szCmp       PROTO :DWORD,:DWORD
GetProcAddr PROTO :DWORD,:DWORD

prC         TYPEDEF PROTO C :VARARG
LoadLibrary EQU <pr1 PTR LoadLib>
printf      EQU <prC PTR __printf>

.data

LLibrary        db "LoadLibraryA",0
FreeLibrary     db "FreeLibrary",0
ExitProcess     db "ExitProcess",0
_printf         db "printf",0
msvcrt          db "msvcrt.dll",0
msg             db 'Kernel address = %X',0

LoadLib         db 0FFh,025h ; define a jump entry
                dd pLoadLib


__printf        db 0FFh,025h
                dd pprintf


.data?

pLoadLib        dd ?
pprintf         dd ?
hLib            dd ?
hKernel32       dd ?

.code

start:

; The code to get the base of kernel32
; may not work on every version of Windows

    mov     ecx,[esp]

@@:

    xor     edx,edx
    dec     ecx
    mov     dx,[ecx+03ch]
    test    dx,0f800h
    jnz     @b
    cmp     ecx,[ecx+edx+34h]
    jnz     @b

    mov     hKernel32,ecx

    invoke  GetProcAddr,hKernel32,ADDR LLibrary
    mov     pLoadLib,eax

    invoke  LoadLibrary,ADDR msvcrt
    mov     hLib,eax

    invoke  GetProcAddr,eax,ADDR _printf
    mov     pprintf,eax
   
    invoke  printf,ADDR msg,hKernel32

    invoke  GetProcAddr,hKernel32,ADDR FreeLibrary
    push    hLib
    call    eax
   
    invoke  GetProcAddr,hKernel32,ADDR ExitProcess

    push    0
    call    eax

include     GetProcAddr.inc
include     szCmp.inc

END start