Click here to Skip to main content
15,881,089 members
Articles / Programming Languages / C++
Article

Inside the maze of DLLs - Part 1

Rate me:
Please Sign up or sign in to vote.
3.30/5 (20 votes)
24 Apr 2003CPOL7 min read 161K   2.9K   50   31
How to find imported/exported functions of applications in the DLLs in system.

Foreword

"They picked up various other people who wanted to get it over, as they went along, until they had absorbed all the persons in the maze. People who had given up all hopes of ever getting either in or out, or of ever seeing their home and friends again, plucked up courage at the sight of Harris and his party, and joined the procession, blessing him. Harris said he should judge there must have been twenty people, following him, in all; and one woman with a baby, who had been there all the morning, insisted on taking his arm, for fear of losing him. Harris kept on turning to the right, but it seemed a long way, and his cousin said he supposed it was a very big maze. "Oh, one of the largest in Europe," said Harris. "Yes, it must be," replied the cousin, "because we've walked a good two miles already.""
Three Men in a Boat. Jerome K. Jerome

What I really hate

What I really hate is to see "Unresolved external symbol referenced from module" or "E2268 Call to undefined function 'function' " on screen after fifteen minutes of compilation. It means that I had forgotten something relevant - to define a function or to add an obj or DLL in the project. Sometimes it means something unexpected, for example, incorrect changing in the project. When I encountered this, I tried to search, for such a function and almost always had problems with it. For example, it is possible to invoke Find File dialog and use "*.DLL" as a mask for the name of file and the function name as a text for searching. The example of this you can see on Figure 1.

Image 1

Figure 1. Find files

The search results are 603 in number. In this list are: DLLs that are imported as a function, exported it and even those DLLs that contain a function name as the text inside. But we need only one file from where function is exported. If even only one DLL is found, then the next step - is to look through it. Utility Impdef is a good application for this, but as for me not very comfortable because it is a console application. And at last, we use utility Implib for creating Lib-file that should be added in the project (let us remember that Microsoft lib is not the same thing as Borland lib).

Utility FindFunction

In my opinion, those three tasks (searching DLL, look through it and creating Lib-file) should be solved by one utility. This was my thought when I saw E2268 compiler message. And it is an idea of FindFunction. On the next figure, you can see the main form of FindFunction.

Image 2

Figure 2. FindFunction

FindFunction does search at 50% quickly then Find Files and in the result, we have only one file (sometimes it may be two or three). Using FindFunction, we can find functions in EXE-files as well as in DLL-files. Check "File extension:" (EXE or/and DLL) for this. It seems to be funny, but we never find any exported function in the EXE-file created by Visual C++, but EXEs created by C++ Builder can have exported function. After end of search, we can select one of the names by clicking and go to another page (Explore DLL/EXE). Figure 3 illustrates the second page of application.

Image 3

Figure 3. FindFunction (second page)

And last step - creating lib-file. For this, let us push "Create Lib" button and select a target path by Save Dialog. FindFunction invokes Borland's Implib.exe and lib will be created. If you need only exe of FindFunction, it is time to stop reading and go here.

How it works

FindFunction performs three subtasks:

  • searching DLL
  • looking through DLL
  • creating lib file

For searching, it is very important to examine all directories including subdirectories on the target path. It can be achieved by recursive search through directories. Let us imagine function that is looking for file in the directory and when it finds another directory, it calls self to continue searching inside that directory which was found. Win32 API has the following functions: FindFirstFile, FindNextFile, FindClose, that can help to do this work. FindFirstFile opens handle for searching. FindNextFile does search, finding one file for one call. And when FindNextFile can't find next file, FindClose closes handle for search. For example:

void RecursiveSearch(AnsiString Funct,AnsiString PathFind)
{
bool next;
HANDLE FileSearching;
WIN32_FIND_DATA FindFileData;
AnsiString temp;

/* Add slash to path if it absent */
if(PathFind[PathFind.Length()]!= '\\')PathFind+="\\";

/* search for any file */
temp=PathFind+"*.*";
/*open handle */
FileSearching=FindFirstFile(
    temp.c_str(),    // pointer to name of file to search for
    &FindFileData     // pointer to returned information
   );

if(next=(FileSearching  != INVALID_HANDLE_VALUE))
    do
     {
/*call self  if find directory*/
     if((FILE_ATTRIBUTE_DIRECTORY & FindFileData.dwFileAttributes) &&
        strcmp(FindFileData.cFileName,".") &&
           strcmp(FindFileData.cFileName,".."))
                RecursiveSearch (Funct,PathFind+FindFileData.cFileName,TypeSch);

                 if(IsItWhatIWant(FindFileData.cFileName))DoSomething();

                next=FindNextFile(
          FileSearching,    // handle to search
    &FindFileData     // pointer to structure for data on found file
   ); /* do search */

/*do not freeze form till search continuing*/ 
     Application->ProcessMessages();
     }while(next);

    FindClose(FileSearching);
/*Search in the subdir - end*/

return;
}

FindFunction puts all exported and imported functions of DLL in the window on the right side of the form. This window is a Rich Edit control and it simplifies printing, saving and finding information. How to browse inside DLL or EXE? Any Win32 DLL or EXE should have special PE-format. Some structures of this format are declared in the winnt.h. Declarations in winnt.h are a very compressed story about PE-format. In the end of the article, I've put some links where you can find detailed info about these structures. It is very suitable to use File Mapping for working with files that have special format. The common definition: memory-mapped files offer a special memory management feature to access files on disk in the same way they access virtual memory of process - through pointers. So we can browse inside file using pointers, i.e., we can use pointers to structure from winnt.h setting aside that it is a file. Really it is a file but file that is mapped in the process memory. Now when a DLL is found and successfully browsed, we only need to add references to the DLL in the project. So lib-file should be created for this. No need to reinvent the wheel - let us use Implib. ShellExecute Win32 API function or CreateProcess can run Implib and pass strings that specify parameters. For ShellExecute:

HINSTANCE ImpLibInstance=ShellExecute(
    GetDesktopWindow(),    /* handle to parent window */
    NULL,    /* pointer to string that specifies operation to perform*/
    "c:\\MyFolder\\implib.exe",     /* pointer to path and filename */
    "\"c:\\mylib\\kern"  \"c:\\WinNT\\system32\\kernel32.dll\"",  
/* pointer  to executable-file parameters*/
    "C:\\",    /* pointer to string that specifies default directory*/
    SW_HIDE     /* whether file is shown when opened*/
   );

This way implib will be executed from c:\MyFolder directory. So it is almost the same if next string will be put in the Start->Run dialog:

c:\MyFolder\implib.exe "c:\mylib\kern" "c:\WinNT\system32\kernel32.dll"

The quotes are extremely useful if directory path contains spaces. In another case, Windows reports you about error. The source code of FindFunction can be download from here.

The roads to Minataur

Using FindFirstFile, FindNextFile, FindClose in Win98

The main problem of using these Win32 API functions in Windows 98 is that it searches files by short name. So if you use "*.dll" as mask for search, the result can't be that you want. For example, you have file with name: c:\MyDirectory\NoPEFormat.dllabc. The extension of short name of this file will be .dll but it is not really a DLL. Next code does not work properly in Windows98:

FileSearching=FindFirstFile( "c:\\MyDirectory\\*.dll", &FindFileData );

For example, next file c:\MyDirectory\NoPEFormat.dllabc will be found as DLL. The solution is to use"*.dll" as mask and compare last four characters of long file name with ".dll"

Incorrect file format

During debugging, I have some crashes of the application. Every time when I saw fpl.dll in the Status Bar, the program had exception. fpl.dll is my library and I never had problems with it before. I noted that fpl.dll was found in the Windows temporary directory and its size was lesser than real. The file had incorrect format and it was surprising for me. When my program walked inside of fpl.dll maze, it met incorrect reference to non-existent parts of library. To avoid this problem, it is possible to use IsBadCodePtr, IsBadReadPtr, IsBadWritePtr and IsBadStringPtr Win32 API functions. Another idea is a try-catch block, so exception can be controlled.

Early versions of Implib

I noted that early (for example, from BCB3) versions of Implib was not always correctly working with my application. The problem is the path to Implib. Early versions work with short path. Solution is simple - using GetShortPathName Win32 API function and call ShellExecute using this name.

Links

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Ukraine Ukraine
I am C++ Builder developer.
I am interesting in WMI, Shell, some deep
COM interface. Beside these I am Brainbench
Win32 API Master.
Now I very like Microsoft .NET and C#. I made some firsts OPOS drivers for Ukrainian fiscal printers.

Comments and Discussions

 
Generalproblem with dll Pin
dnqhung10-Jun-04 1:26
dnqhung10-Jun-04 1:26 
GeneralRe: problem with dll Pin
Vladimir Afanasyev10-Jun-04 2:12
Vladimir Afanasyev10-Jun-04 2:12 
QuestionHow to handle return type of DLLs? Pin
JigarThakkar9-Dec-03 1:12
JigarThakkar9-Dec-03 1:12 
AnswerRe: How to handle return type of DLLs? Pin
Vladimir Afanasyev9-Dec-03 22:03
Vladimir Afanasyev9-Dec-03 22:03 
Hi Jigar,
I hope that follow reference helps you:
How to Call lstrcpy to Receive LPSTR Returned from Other APIs
http://support.microsoft.com/default.aspx?scid=kb;fr;f78304
Best Regards,
Vladimir.
GeneralRe: How to handle return type of DLLs? Pin
JigarThakkar9-Dec-03 22:43
JigarThakkar9-Dec-03 22:43 
GeneralRe: How to handle return type of DLLs? Pin
JigarThakkar14-Dec-03 23:24
JigarThakkar14-Dec-03 23:24 
GeneralRe: How to handle return type of DLLs? Pin
Vladimir Afanasyev15-Dec-03 2:55
Vladimir Afanasyev15-Dec-03 2:55 
GeneralRe: How to handle return type of DLLs? Pin
JigarThakkar15-Dec-03 23:26
JigarThakkar15-Dec-03 23:26 
GeneralGreat work Vladimir!! Pin
Nik Vogiatzis1-Dec-03 13:38
Nik Vogiatzis1-Dec-03 13:38 
GeneralRe: Great work Vladimir!! Pin
Vladimir Afanasyev1-Dec-03 20:57
Vladimir Afanasyev1-Dec-03 20:57 
GeneralOf A Theoretical Interest Only Pin
YoSilver23-May-03 1:51
YoSilver23-May-03 1:51 
GeneralRe: Of A Theoretical Interest Only Pin
Vladimir Afanasyev25-May-03 21:54
Vladimir Afanasyev25-May-03 21:54 
GeneralDid not get an executable file. Pin
WREY25-Apr-03 14:20
WREY25-Apr-03 14:20 
GeneralRe: Did not get an executable file. Pin
Vladimir Afanasyev28-Apr-03 20:45
Vladimir Afanasyev28-Apr-03 20:45 
GeneralThank you for a valuable tool! Pin
Terry D'Silva15-Apr-03 5:55
sussTerry D'Silva15-Apr-03 5:55 
QuestionWhat the hell? Pin
Keithsw14-Apr-03 11:37
Keithsw14-Apr-03 11:37 
AnswerRe: What the hell? Pin
Vladimir Afanasyev14-Apr-03 20:22
Vladimir Afanasyev14-Apr-03 20:22 
GeneralRe: What the hell? Pin
WREY15-Apr-03 21:42
WREY15-Apr-03 21:42 
GeneralKeep it easy Pin
Vladimir Afanasyev15-Apr-03 22:38
Vladimir Afanasyev15-Apr-03 22:38 
GeneralRe: Keep it easy Pin
WREY18-Apr-03 2:07
WREY18-Apr-03 2:07 
GeneralRe: Keep it easy Pin
Chris Maunder25-Apr-03 4:34
cofounderChris Maunder25-Apr-03 4:34 
GeneralRe: Keep it easy Pin
Vladimir Afanasyev25-Apr-03 6:30
Vladimir Afanasyev25-Apr-03 6:30 
GeneralCreate LIB with MS Pin
ChrLipp10-Apr-03 21:39
ChrLipp10-Apr-03 21:39 
GeneralRe: Create LIB with MS Pin
Vladimir Afanasyev11-Apr-03 1:23
Vladimir Afanasyev11-Apr-03 1:23 
GeneralRe: Create LIB with MS Pin
Anonymous25-Apr-03 13:41
Anonymous25-Apr-03 13:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.