The MASM Forum Archive 2004 to 2012

General Forums => The Workshop => Topic started by: Mark Jones on February 15, 2006, 08:33:52 PM

Title: Console GetStdHandle & MemProof
Post by: Mark Jones on February 15, 2006, 08:33:52 PM
Hi, when testing a console app, each print macro calls StdOut which calls GetStdHandle. According to MemProof, the returned handles must be freed with CloseHandle because windows reserves memory for them. Is this any big concern?

Quote from: MACROS.ASM
    print MACRO arg1:REQ,varname:VARARG      ;; display zero terminated string
        invoke StdOut,reparg(arg1)
        ; hStdOut not freed
      IFNB <varname>
        invoke StdOut,chr$(varname)
        ; hStdOut not freed
      ENDIF
    ENDM

Quote from: OllyDbg
00405004  /$  55              PUSH EBP
00405005  |.  8BEC           MOV EBP,ESP
00405007  |.  83C4 F4       ADD ESP,-0C
0040500A  |.  6A F5          PUSH -0B                                  ; /DevType = STD_OUTPUT_HANDLE
0040500C  |.  E8 25010000   CALL <JMP.&kernel32.GetStdHandle>        ; \GetStdHandle
00405011  |.  8945 FC       MOV [LOCAL.1],EAX
00405014  |.  FF75 08       PUSH [ARG.1]                           ;  App.00406640
00405017  |.  E8 DC000000   CALL TT.004050F8
0040501C  |.  8945 F4       MOV [LOCAL.3],EAX
0040501F  |.  6A 00          PUSH 0                                     ; /pOverlapped = NULL
00405021  |.  8D45 F8       LEA EAX,[LOCAL.2]                    ; |
00405024  |.  50              PUSH EAX                                  ; |pBytesWritten = NULL
00405025  |.  FF75 F4       PUSH [LOCAL.3]                        ; |nBytesToWrite = B0952D04 (2962566404.)
00405028  |.  FF75 08       PUSH [ARG.1]                            ; |Buffer = TT.00406640
0040502B  |.  FF75 FC       PUSH [LOCAL.1]                        ; |hFile = 7C90E64E
0040502E  |.  E8 27010000   CALL <JMP.&kernel32.WriteFile>  ; \WriteFile
00405033  |.  8B45 F8       MOV EAX,[LOCAL.2]
00405036  |.  C9              LEAVE                                        ; Handle is not freed
00405037  \.  C2 0400       RETN 4
Title: Re: Console GetStdHandle & MemProof
Post by: arafel on February 15, 2006, 09:23:45 PM
imho MemProof is wrong here.

GetStdHandle doesn't allocate any new handles, but instead returns an existing one. It' shouldn't be freed.
Title: Re: Console GetStdHandle & MemProof
Post by: MichaelW on February 16, 2006, 02:31:51 AM

http://www.old.masmforum.com/viewtopic.php?t=889


Title: Re: Console GetStdHandle & MemProof
Post by: Tedd on February 16, 2006, 12:56:16 PM
If you're going to do a lot of printing then it's probably an idea to GetStdHandle once at the start and store the result. Then close it once you've finished.
Of course, ExitProcess will cause handles owned by the process to be closed anyway, but it's good manners to close them yourself.