Nov 252014
 

What’s ResourceDigger?

Wrote a utility (long back) for displaying resources from binary files, recently did some modifications as well. We know visual studio does provide a similar functionality but this one’s better with respect to viewing resources. You can view as many resource files as you like (haven’t put a limit). You can drag and drop folders or binaries into the application to get them loaded. Loads up any binary as long LoadLibrary succeeds. Quite useful for a quick view of resources in a binary file, will add editing of resources in the next version of this tool. Hope this helps.

Here is a screenshot of how the tool looks…

ResourceDigger: Application Screenshot

How to use ResourceDigger

Easy to use. Just drag and drop a folder or a bunch of executables. Or…
To load an executable press Ctrl + L or Load Exe toolbar button

ResourceDigger: Load Executable

To load a folder press Ctrl +D, or Scan Folder toolbar button. Select “Load Sub Directories” if you want to recurse into sub-directories.

ResourceDigger: Load a folder of resources

What features are supported in ResourceDigger

Some of the features supported by the application…

  • Viewing animated gifs, normal gifs, pngs, jpegs, bmps, HTML files, manifest files.
  • Display group icons, cursors with detailed description of each of them… See screenshot…
    ResourceDigger: Icon Group Display
  • Friendly display of accelerator table, a good way to know all the shortcuts provided by an application…
    ResourceDigger: Accelerator Resource
  • Friendly display of string table…
    ResourceDigger: String table resource
  • Displays resources in all available languages
    ResourceDigger: Multi Languages Resource
    ResourceDigger: Multi Language Dialog Resource
  • Animated view of AVI file. With a toolbar to control frames in the AVI file.
    ResourceDigger: Version Resource
  • Version display… (there are few issues, I’m working on them)
    image
  • Clear view of registry resources…
    ResourceDigger: Registry Resource
  • Toolbar resource view…
    ResourceDigger: Toolbar Resource
  • Menu resource display…
    ResourceDigger: Menu Resource
  • Hex display of custom resources…
    ResourceDigger: Hex display of unknown resources

Known Issues

  • Hangs up if you give a folder with a humungous list of binaries.
  • This is not multithreaded so just be patient until resources finish loading.

Tips

Press ‘*’ on a particular node to expand all its child nodes.

Download Link (rename from .Jpg to .exe)

Do let me know your suggestions…

Oct 142014
 

Introduction to MiniDumpWriteDump

In this post, let me show you some sample code to create a full memory dump of any given process using the Windows API MiniDumpWriteDump.

Creating Full Memory Dumps using MiniDumpWriteDump

Here’s some sample code to create a full memory dump of any given process. Just call WriteFullDump(hProcessHandle). This process handle must have PROCESS_QUERY_INFORMATION and PROCESS_VM_READ access to the process. If handle information is to be collected then PROCESS_DUP_HANDLE access is also required.

Please test out before production use. Just some quick code that I was writing up for a customer.

#include <tchar.h>
#include <windows.h>
#include <DbgHelp.h>

using namespace std;

#pragma comment (lib, "dbghelp.lib")

void WriteFullDump(HANDLE hProc)
{
   const DWORD Flags = MiniDumpWithFullMemory |
   MiniDumpWithFullMemoryInfo |
   MiniDumpWithHandleData |
   MiniDumpWithUnloadedModules |
   MiniDumpWithThreadInfo;

   HANDLE hFile = CreateFile(_T("F:\\main.dmp"), GENERIC_ALL, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
   if (!hFile)
   {
     std::cerr << _T("Failed to write dump: Invalid dump file");
   }
   else
   {
     BOOL Result = MiniDumpWriteDump( hProc,
                                      GetProcessId(hProc),
                                      hFile,
                                      (MINIDUMP_TYPE)Flags,
                                      nullptr,
                                      nullptr,
                                      nullptr );

     CloseHandle(hFile);

     if (!Result)
     {
        std::cerr << _T("Looks like an error: MiniDumpWriteDump failed") ;
     }
   }// End if

   return;
}

Significance of MiniDumpWriteDump flags

What gets into a process’ memory dump is determined by the flags we pass in to MiniDumpWriteDump API. The code that I’ve given produces the biggest dumps possible for a process. The output dump file in this case will have the entire process’ memory, modules, registers, thread information, unloaded module information, and process handle related information.

For our case we’ve given these five flags, this will just basically copy everything from a process’ virtual address space into a dump. Comment out any flags if you’re not interested in that information, for e.g. if you don’t need information on the handles in a process just comment out: MiniDumpWithHandleData.

MiniDumpWithFullMemory |
MiniDumpWithFullMemoryInfo |
MiniDumpWithHandleData |
MiniDumpWithUnloadedModules |
MiniDumpWithThreadInfo;

References

http://msdn.microsoft.com/en-us/library/windows/desktop/ms680360(v=vs.85).aspx

Oct 082013
 

Map Network Drive Dialog

This how the map network drive dialog look like. So how do we show this dialog programmatically?

Map Network Drive

Map Network Drive Dialog

 

Programmatically invoking Map Network Drive dialog

The windows API’s for showing this dialog is: WNetConnectionDialog and WNetConnectionDialog1. I’ve demonstrated both WNetConnectionDialog and WNetConnectionDialog1 in this code snippet. WNetConnectionDialog is a simple API which takes a window handle and a DWORD. While WNetConnectionDialog1 is an API which provides few more parameters along with the flexibility to set up different options. Here’s the code…

#pragma comment(lib, "Mpr.lib")
void PrvMapNetworkDrive(LPTSTR lptszNetworkPath)
{
    CONNECTDLGSTRUCT condlg = { 0 };
    condlg.cbStructure = sizeof(condlg);
    condlg.hwndOwner = GetConsoleWindow();
    condlg.dwFlags =  CONNDLG_USE_MRU;

    NETRESOURCE nr = { 0 };
    nr.dwScope = RESOURCE_GLOBALNET;
    nr.dwType = RESOURCETYPE_DISK;
    nr.lpRemoteName = lptszNetworkPath;
    nr.dwDisplayType = RESOURCEDISPLAYTYPE_DOMAIN;

    condlg.lpConnRes = &nr;

    const int RetVal = WNetConnectionDialog1(&condlg);
    //const int RetVal = WNetConnectionDialog(GetConsoleWindow(), RESOURCETYPE_DISK);

    switch(RetVal)
    {
    case ERROR_INVALID_PARAMETER:
        cerr << "Error: invalid parameter";
        break;
    case ERROR_BAD_DEV_TYPE:
        cerr << "Error: Bad device type";
        break;
    case ERROR_BUSY:
        cerr << "Error: Busy";
        break;
    case ERROR_NO_NETWORK:
        cerr << "Error: No network";
        break;
    case ERROR_NOT_ENOUGH_MEMORY:
        cerr << "Error: Not enough memory";
        break;
    case ERROR_EXTENDED_ERROR:
        {
            DWORD Err = 0;
            TCHAR ErrBuf[MAX_PATH] = {0};
            TCHAR NameBuf[MAX_PATH] = {0};
            WNetGetLastError(&Err, ErrBuf, MAX_PATH, NameBuf, MAX_PATH);
            cerr << "Error: " << ErrBuf;
        }
        break;
    case NO_ERROR:
        cout << "No error";
        break;
    default:
        break;
    };// End switch
}// End PrvMapNetworkDrive

I’ve added basic error checks, you’ll have to test this out properly before production usage.

Sep 182013
 

In this blog post I’ll be demonstrating different API’s and techniques used to retrieve size of a file. I haven’t tested this much, you might want to add parameter integrity check etc., also probably better error checks. Use this code at your own risk.

  1. Using GetFileSizeEx
  2. Using _wstat64
  3. Using GetFileInformationByHandleEx
  4. Using FindFirstFileW
  5. Using fseek and ftell
 
Method 1: Using GetFileSizeEx

Here is a short code snippet to get size of a file using the Windows API GetFileSizeEx. Wrote this for a friend, so thought this will be useful for others as well.

Windows Store apps:  GetFileSizeEx is not supported. Use GetFileInformationByHandleEx.

__int64 PrvGetFileSize(const wchar_t* path)
{
    HANDLE hFile = ::CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
    if(hFile == INVALID_HANDLE_VALUE)
    {
        printf("Failed to open file: %S, error: %lu", path, GetLastError());
        return -1;
    }

    LARGE_INTEGER li = { 0 };
    if(GetFileSizeEx(hFile, &li) == 0)
    {
        printf("Failed to get file size: %lu", GetLastError());
        CloseHandle(hFile);
        return -1;
    }

    CloseHandle(hFile);

    return li.QuadPart;
}
 
Method 2: Using _wstat64
__int64 PrvStat64(const wchar_t* path)
{
    struct _stat64 flstat = {0};
    const int rv = _wstat64( path, &flstat );

    // Check if _stat64 call worked
    if( rv != 0 )
    {
        perror( "Problem getting information" );
        switch (errno)
        {
            case ENOENT:
                printf("File %S not found.\n", path);
                return -1;
            case EINVAL:
                printf("Invalid parameter to _stat.\n");
                return -1;
            default:
                /* Should never be reached. */
                printf("Unexpected error in _stat.\n");
                return -1;
        }// End switch
    }// End if

    return flstat.st_size;
}

 

Method 3: Using GetFileInformationByHandleEx
__int64 PrvGetFileInformationByHandleEx(const wchar_t* path)
{
    HANDLE hFile = ::CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
    if(hFile == INVALID_HANDLE_VALUE)
    {
        printf("Failed to open file: %S, error: %lu", path, GetLastError());
        return -1;
    }

    FILE_STANDARD_INFO finfo = {0};
    if(GetFileInformationByHandleEx (hFile, FileStandardInfo, &finfo, sizeof(finfo)) == 0)
    {
        printf("Failed to get file size: %lu", GetLastError());
        CloseHandle(hFile);
        return -1;
    }

    CloseHandle(hFile);

    return finfo.EndOfFile.QuadPart;
}
 
Method 4: Using FindFirstFile
__int64 PrvFindFirstFile(const wchar_t* path)
{
    WIN32_FIND_DATAW fdata = {0};
    HANDLE hFind = FindFirstFileW(path, &fdata);
    if (hFind == INVALID_HANDLE_VALUE) 
    {
        printf ("FindFirstFile failed (%d)\n", GetLastError());
        return -1;
    } 

    ULONGLONG Size = fdata.nFileSizeLow;
    Size |= (((__int64)fdata.nFileSizeHigh) << 32);

    FindClose(hFind);

    return Size;
}
 
Method 5: Using a combination of fseek and ftell
__int64 PrvSeekFTell(const wchar_t* path)
{
    FILE* file = NULL;
    errno_t err = _wfopen_s(&file, path, L"r");

    if(err)
    {
        printf("Error: Could not open file: %s", path);
        return  -1;
    }

    _fseeki64(file, 0, SEEK_SET); // Goto beginning
    _fseeki64(file, 0, SEEK_END); // Goto end
    const __int64 size = _ftelli64(file); // Tell position, i.e. size
    fclose(file);

    return size;
}
Sep 132013
 

Use io manipulator ‘unitbuf’ to turn off stream buffering and ‘nounitbuf’ to turn on stream buffering. If ‘unitbuf’ is on the stream object is flushed after every insertion else the stream is not force flushed. For e.g. endl triggers a flush in cases of ‘nounitbuf’.

Sample code:

fstream fstr( “c://Hello.txt” );

cout << unitbuf << "Buffering turned off";
cout << nounitbuf << "Buffering turned on";

Also note that ‘endl’ flushes stream buffer along with inserting a new line character.

Mar 052011
 

Using PickIconDlg Windows API

In windows if you have changed the icon of a shortcut file then you’ll know what the API PickIconDlg does. Basically this function will let you select any icon embedded as a resource in a .dll or .exe file for use in your application. Just select in the dialog the icon that you like and click ok. Here is a shot of the dialog, in my case I’ve selected devenv.exe and these are the icons embedded in the executable…

PickIcon dialog screenshot

So the code for invoking the PickIconDlg API is as follows…

int Index = 2;
const DWORD BuffSize = MAX_PATH*2;
TCHAR Path[BuffSize] = {_T("C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\IDE\\devenv.exe")};
const int Sel = PickIconDlg(GetSafeHwnd(), Path, BuffSize, &Index);
if(Sel)
{
 // The hinst parameter is assumed to have been initialized earlier.
 HMODULE hMod = ::LoadLibrary(Path);
 m_hIcon = ExtractIcon(hMod, Path, Index);
 // After some work destroy the icon
 FreeLibrary(hMod);
}

// Set the icon for this dialog using above extracted icon
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon 

Now see my dialog titlebar after executing this code snippet…

Dialog with new icon

Dialog with new icon

 

Have fun! 🙂

Feb 212011
 

Hmm so after a long time I’m back with a new post.

This time I came across a cool API called NtQueryObject. One purpose of the API is to find the name of object type it’s given. For example if you are passing a process handle this API will return “Process” as the string. The caveat of using this API is that it can be changed in the future. So be very careful with the signature of the function, cross check with the documentation before using. Use it at your own risk.

So let’s see the code, since API doesn’t have a lib associated with it we’ll have to use GetProcAddress to retrieve function address. The function signature of NtQueryObject looks like…

NTSTATUS NtQueryObject(__in_opt HANDLE Handle,
                        __in OBJECT_INFORMATION_CLASS ObjectInformationClass,
                        __out_opt PVOID ObjectInformation,
                        __in ULONG ObjectInformationLength,
                        __out_opt PULONG ReturnLength );

The second parameter to the API can be of two types. The one type of interest for this case is PUBLIC_OBJECT_TYPE_INFORMATION. If we pass this type as second parameter then the API is expecting a PUBLIC_OBJECT_TYPE_INFORMATION as third parameter. The contents of the structure is as follows…

typedef struct __PUBLIC_OBJECT_TYPE_INFORMATION {
    UNICODE_STRING TypeName;
    ULONG Reserved [22];    // reserved for internal use
} PUBLIC_OBJECT_TYPE_INFORMATION, *PPUBLIC_OBJECT_TYPE_INFORMATION;

The first member in the structure is the one that returns the string, only issue we’ll have to allocate this in special manner. Please have a look in the below function to see how I’ve allocated memory for this structure.

void GetHandleTypeName(HANDLE hHandle, CString&amp;amp;amp; TypeName)
{
 typedef NTSTATUS (NTAPI *NtQueryObjectPtr)(HANDLE Handle,
                   OBJECT_INFORMATION_CLASS ObjectInformationClass,
          PVOID ObjectInformation,
          ULONG ObjectInformationLength,
          PULONG ReturnLength);

HMODULE hMod = LoadLibrary(_T("NtDll.dll"));
 NtQueryObjectPtr QueryObj = (NtQueryObjectPtr)::GetProcAddress(hMod, "NtQueryObject");
 ASSERT(QueryObj);

ULONG OutSize = 0;
 NTSTATUS NtStatus = QueryObj(hHandle, ObjectTypeInformation, NULL, 0, &amp;amp;amp;OutSize);
 PPUBLIC_OBJECT_TYPE_INFORMATION TypeInfo = (PPUBLIC_OBJECT_TYPE_INFORMATION)calloc(1, OutSize);
 ULONG InSize = OutSize;
 NtStatus = QueryObj(hHandle, ObjectTypeInformation, TypeInfo, InSize, &amp;amp;amp;OutSize);
 TypeName = TypeInfo->TypeName.Buffer;
 free(TypeInfo);
}
// This is how we invoke the function note: GetCurrentProcess() call.
CString cs;
GetHandleTypeName(GetCurrentProcess(), cs);
MessageBox(cs);
Jul 202010
 

If you are creating a dialog with style WS_CHILD then make sure you also have DS_CONTROL  and DS_CONTROLPARENT enabled for the dialog.

The reason being that the dialog at a time is a control (embedded inside another window) and a control parent (housing other controls). If these styles are not specified calls to GetWindowRect and then a subsequent ScreenToClient will return top co-ordinates in negative leading to some confusion.

Feb 122010
 

It’s quite handy to show the standard windows open with dialog, which lists all installed applications along with a browse button. In Windows XP there is no straight forward way of doing this.

In Windows Vista onwards Microsoft has provided a shell API for this purpose. It’s called SHOpenWithDialog.

Some sample code (couldn’t test this though since I’m on XP at home)…

OPENASINFO Info = { 0 };
Info.oaifInFlags = OAIF_EXEC | OAIF_ALLOW_REGISTRATION;
SHOpenWithDialog(NULL, &amp;Info);

A screenshot of the dialog in XP…

Open with dialog

Open with dialog

Dec 222009
 

Recently a user asked this question in MSDN forums. He had MBCS enabled for his application and also wanted to enable unicode characters in a particular edit control. Note MFC only create unicode controls if UNICODE is defined in project settings.

So in order to explicitly create controls that support UNICODE characters we use the ‘W’ functions. For example: for our user he should use “CreateWindowW” function. Note the last ‘W’ in the function. ANSI windows are created by calling “CreateWindowA” function (this also means that we can explicitly create a non-unicode control).

Also make sure you use only UNICODE API’s for a control created in this manner. For e.g. always call GetWindowTextW instead of GetWindowTextA. Never use MFC on such a control if it’s not created by MFC framework, I mean don’t call CWnd::Attach on this control. Mainly because MFC is operating in non-unicode environment but our control is a UNICODE one.

Now once such a control is created you can paste characters of different languages, for e.g. Chinese, Japanese, etc even though the application is not a UNICODE supporting one.