Cheat Engine Forum Index Cheat Engine
The Official Site of Cheat Engine
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 


[VB 6.0 Expert Developers' Tip] How to unload DLL silently

 
Post new topic   Reply to topic    Cheat Engine Forum Index -> General programming
View previous topic :: View next topic  
Author Message
Buggy
Advanced Cheater
Reputation: 0

Joined: 04 Jan 2008
Posts: 72
Location: Republic of Korea (South Korea)

PostPosted: Wed Apr 09, 2008 2:18 am    Post subject: [VB 6.0 Expert Developers' Tip] How to unload DLL silently Reply with quote

Windows is exporting function LoadLibrary() and FreeLibrary() to load and unload DLL freely.
In NT Windows, this functions call ntdll.dll::LdrLoadDll/LdrUnloadDll inside, this function finally send loaded or unloaded to DLLMain()

I made DLL under source below and tested. (Visual C++ 6.0)

Code:
#include <windows.h>

BOOL CALLBACK DllMain(HINSTANCE hInstDLL, DWORD dwReason, LPVOID lpReserved)
{
 DWORD TID = 0;
 HANDLE hThread = NULL;

 if(dwReason == DLL_PROCESS_ATTACH)
 {
  MessageBox(NULL, "DLL loaded"DllMain()", MB_OK | MB_ICONINFORMATION);
 } else if(dwReason == DLL_PROCESS_DETACH)
 {
  MessageBox(NULL, "DLL unloaded", "DllMain()", MB_OK | MB_ICONINFORMATION);
 }

 return TRUE;
}


and I made a program that loads that DLL in Visual Basic.

Code:
Private Declare Function LoadLibrary Lib "kernel32.dll" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As Long
Private Declare Function FreeLibrary Lib "kernel32.dll" (ByVal hLibModule As Long) As Long

Private Sub Form_Load()
    Dim hLib As Long
    hLib = LoadLibrary("TrickIt.dll")
    If hLib = 0& Then
        MsgBox "DLL loading failed", vbCritical, "ERROR"
    Else
        FreeLibrary hLib
    End If
End Sub

and it worked fine.

I will introduce with this tip how to unload DLL silently. and we can do like this :

when process unloads, or when there is no DLLMain() DLL(entry point 0), then DLL will cannot check.

but unloading when process quits is not good way and it is puahahahahahahahaha so we have to fool DLL's entry point.

when Windows loads DLL, Windows saves information in PEB(Process Environment bLOCK).
In that point, it saves module list, too.

PEB looks like this :
Code:
nt!_PEB
   +0x000 InheritedAddressSpace : UChar
   +0x001 ReadImageFileExecOptions : UChar
   +0x002 BeingDebugged    : UChar
   +0x003 SpareBool        : UChar
   +0x004 Mutant           : Ptr32 Void
   +0x008 ImageBaseAddress : Ptr32 Void
   +0x00c Ldr              : Ptr32 _PEB_LDR_DATA

  ............


In field Ldr, PEB_LDR_DATA has this :
Code:
nt!_PEB_LDR_DATA
   +0x000 Length           : Uint4B
   +0x004 Initialized      : UChar
   +0x008 SsHandle         : Ptr32 Void
   +0x00c InLoadOrderModuleList : _LIST_ENTRY
   +0x014 InMemoryOrderModuleList : _LIST_ENTRY
   +0x01c InInitializationOrderModuleList : _LIST_ENTRY
   +0x024 EntryInProgress  : Ptr32 Void


LIST_ENTRY is a link list like under source below.

Code:
Private Type LIST_ENTRY
     pFlink As Long
     pBlink As Long
End Type


In that point, this link points LDR_MODULE, and it looks like this :
Code:
typedef struct _LDR_MODULE {



  LIST_ENTRY              InLoadOrderModuleList;
  LIST_ENTRY              InMemoryOrderModuleList;
  LIST_ENTRY              InInitializationOrderModuleList;
  PVOID                   BaseAddress;
  PVOID                   EntryPoint;
  ULONG                   SizeOfImage;
  UNICODE_STRING          FullDllName;
  UNICODE_STRING          BaseDllName;
  ULONG                   Flags;
  SHORT                   LoadCount;
  SHORT                   TlsIndex;
  LIST_ENTRY              HashTableEntry;
  ULONG                   TimeDateStamp;



} LDR_MODULE, *PLDR_MODULE;



We can know where entry point address saved in.

when we code we may code like this :

Code:
Private Declare Function ZwQueryInformationProcess Lib "ntdll.dll" ( _
    ByVal ProcessHandle As Long, _
    ByVal ProcessInformationClass As Long, _
    ProcessInformation As Any, _
    ByVal ProcessInformationLength As Long, _
    ReturnLength As Long _
) As Long

Private Declare Function LoadLibrary Lib "kernel32.dll" Alias "LoadLibraryA" ( _
    ByVal lpLibFileName As String _
) As Long

Private Declare Function FreeLibrary Lib "kernel32.dll" (ByVal hLibModule As Long) As Long

Private Declare Function NtCurrentTeb Lib "ntdll" () As Long

Private Declare Function IsBadReadPtr Lib "kernel32.dll" ( _
    ByRef lp As Any, _
    ByVal ucb As Long _
) As Long

Private Declare Sub RtlMoveMemory Lib "kernel32.dll" ( _
    ByRef Destination As Any, _
    ByRef Source As Any, _
    ByVal Length As Long _
)

Private Declare Function VirtualProtect Lib "kernel32.dll" ( _
    ByRef lpAddress As Any, _
    ByVal dwSize As Long, _
    ByVal flNewProtect As Long, _
    ByRef lpflOldProtect As Long _
) As Long

Private Type LIST_ENTRY
    Flink As Long
    Blink As Long
End Type

Private Type UNICODE_STRING
    Length As Integer           ' bytes
    MaximumLength As Integer    ' bytes
    pwBuffer As Long
End Type

Private Type LDR_MODULE
    InLoadOrderModuleList As LIST_ENTRY
    InMemoryOrderModuleList As LIST_ENTRY
    InInitializationOrderModuleList As LIST_ENTRY
    BaseAddress As Long
    EntryPoint As Long
    SizeOfImage As Long
    FullDllName As UNICODE_STRING
    BaseDllName As UNICODE_STRING
    Flags As Long
    LoadCount As Integer
    TlsIndex As Integer
    HashTableEntry As LIST_ENTRY
    TimeDateStamp As Long
End Type

Private Type PROCESS_BASIC_INFORMATION
    Reserved1 As Long
    PebBaseAddress As Long
    Reserved2(1) As Long
    UniqueProcessId As Long
    Reserved3 As Long
End Type

Private Const PAGE_READWRITE& = &H4

Private Sub Form_Load()
    Dim hLib As Long

    hLib = LoadLibrary("TrickIt.dll")
    If hLib = 0& Then
        MsgBox "DLL loading failed", vbCritical, "ERROR"
        Exit Sub
    End If

    ' Get PEB Address
    Dim pPeb   As Long
    pPeb = GetPEBAddress()     ' Get PEB Address
    If pPeb = 0 Then 'When it isn't valid (NULL)
        MsgBox "Could not get PEB Address.", vbExclamation, "Unexcepted Error"
        ' Message ERROR
        Exit Sub
        ' End
    End If

    ' +0x00c Ldr _PEB_LDR_DATA
    Dim ppLdr   As Long, pLdr   As Long
    ppLdr = pPeb + &HC& 'get PEB_LDR_DATA
    ' if it isn't' valid message error
    If IsBadReadPtr(ByVal ppLdr, 4) Then _
        MsgBox "PEB_LDR_DATA may be invalid.", vbExclamation, "Unexcepted Error": Exit Sub
    RtlMoveMemory pLdr, ByVal ppLdr, 4

    ' PEB_LDR_DATA has information like this
    ' +0x014 InMemoryOrderModuleList : _LIST_ENTRY

    Dim pModule As Long, CurrentModule As LDR_MODULE, _
        sBuffer As String, DllName As String, TempModule As LDR_MODULE, Dummy As Long

    RtlMoveMemory pModule, ByVal pLdr + &HC&, 4
    ' get pointer (pModule -> LDR_MODULE's pointer)

    'get LDR_MODULE.
    RtlMoveMemory CurrentModule, ByVal pModule, Len(CurrentModule)

    Do
        If CurrentModule.BaseAddress = hLib Then
            CurrentModule.EntryPoint = 0&
            RtlMoveMemory ByVal pModule, CurrentModule, Len(CurrentModule)

            FreeLibrary hLib
            MsgBox "did it message dll message?", vbExclamation, "kkkk"
        End If

        pModule = CurrentModule.InLoadOrderModuleList.Blink
        RtlMoveMemory CurrentModule, ByVal CurrentModule.InLoadOrderModuleList.Blink, Len(CurrentModule)
        'open next thing
        If CurrentModule.BaseAddress = App.hInstance Then Exit Do
        'loop while next thing is empty
    Loop
End Sub

Private Function GetPEBAddress() As Long
    On Error GoTo NotSupported
    Dim pbi As PROCESS_BASIC_INFORMATION, Dummy As Long
    If ZwQueryInformationProcess(-1&, 0&, pbi, Len(pbi), Dummy) = 0 Then
        GetPEBAddress = pbi.PebBaseAddress
    Else
        GetPEBAddress = GetPEBAddressinXP
    End If
NotSupported:
End Function

Private Function GetPEBAddressinXP() As Long
    On Error GoTo NotSupported 'Windows 9X/Me will occures error
    Dim pTeb As Long, ppPeb As Long
    pTeb = NtCurrentTeb 'get TEB
    On Error Resume Next ' on error ignore
    If pTeb = 0 Then Exit Function 'if it has invalid TEB, run away this procedure
    ' +0x030 ProcessEnvironmentBlock : _PEB
    ppPeb = pTeb + &H30&
    'check IsValid
    If IsBadReadPtr(ByVal ppPeb, 4) Then Exit Function
    ' returns PEB
    RtlMoveMemory GetPEBAddress, ByVal ppPeb, 4
NotSupported:
End Function


wow I felt my self while i'm writing this topic i have very stupid english level --

_________________

[img]
<a><img></a>[/img]
iroo sooo hooooot
Back to top
View user's profile Send private message
Trow
Grandmaster Cheater
Reputation: 2

Joined: 17 Aug 2006
Posts: 957

PostPosted: Wed Apr 09, 2008 3:18 am    Post subject: Reply with quote

may you please explain this before i go on: do DLLs not unload silently by default?
_________________
Get kidnapped often.
Back to top
View user's profile Send private message
Buggy
Advanced Cheater
Reputation: 0

Joined: 04 Jan 2008
Posts: 72
Location: Republic of Korea (South Korea)

PostPosted: Wed Apr 09, 2008 3:20 am    Post subject: Reply with quote

blland wrote:
may you please explain this before i go on: do DLLs not unload silently by default?


Like I said it is detected.

_________________

[img]
<a><img></a>[/img]
iroo sooo hooooot
Back to top
View user's profile Send private message
Trow
Grandmaster Cheater
Reputation: 2

Joined: 17 Aug 2006
Posts: 957

PostPosted: Wed Apr 09, 2008 3:33 am    Post subject: Reply with quote

Buggy wrote:
blland wrote:
may you please explain this before i go on: do DLLs not unload silently by default?


Like I said it is detected.


oh sorry. i apologize

_________________
Get kidnapped often.
Back to top
View user's profile Send private message
samuri25404
Grandmaster Cheater
Reputation: 7

Joined: 04 May 2007
Posts: 955
Location: Why do you care?

PostPosted: Wed Apr 09, 2008 2:22 pm    Post subject: Reply with quote

Sorry if this is a nooby question or something, but why does it matter whether or not you unload quietly?

What's done is done, right?

_________________
Wiccaan wrote:

Oh jeez, watchout I'm a bias person! Locked.


Auto Assembly Tuts:
In Depth Tutorial on AA
Extended
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    Cheat Engine Forum Index -> General programming All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


Powered by phpBB © 2001, 2005 phpBB Group

CE Wiki   IRC (#CEF)   Twitter
Third party websites