eugen_nw
eugen_nw

Reputation: 159

Is it possible to setup unmanaged DLL to generate memory dump files?

I have a Console C# application that's calling into an unmanaged C DLL to perform calculations. The C DLL generates Access Violation exceptions at times and I want to capture the memory dumps. I use the code below to setup the C DLL to generate the memory dump files. My problem is that the SolverExceptionHandler function never gets called. Do I need to setup the memory dump files' generation in the C# .EXE or am I doing something wrong in the C code below?

#include <windows.h>
#include <minidumpapiset.h>
#include <errhandlingapi.h>
#include <ExtStruct.h>
#include <string.h>
#include <fileapi.h>
#include <processthreadsapi.h>
#include <stdio.h>


static const WCHAR MemoryDumpFileDirectory[] = L"\\MemoryDumpFiles";

LONG WINAPI SolverExceptionHandler(EXCEPTION_POINTERS* ExceptionInfo)
{
    printf("Entered SolverExceptionHandler\n");

    WCHAR memoryDumpFileName[MAX_PATH_LEN + 1];
    wcscpy_s(memoryDumpFileName, MAX_PATH_LEN, MemoryDumpFileDirectory);
    wcscat_s(memoryDumpFileName, MAX_PATH_LEN, L"\\");
    wcscat_s(memoryDumpFileName, MAX_PATH_LEN, L"DumpFileXXXXXX");

    HANDLE hFile = CreateFile(
        (LPCWSTR) memoryDumpFileName,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    MINIDUMP_EXCEPTION_INFORMATION mei;
    mei.ThreadId = GetCurrentThreadId();
    mei.ClientPointers = TRUE;
    mei.ExceptionPointers = ExceptionInfo;
    bool success = MiniDumpWriteDump(
        GetCurrentProcess(),
        GetCurrentProcessId(),
        hFile,
        MiniDumpNormal,
        &mei,
        NULL,
        NULL);

    wprintf(L"SolverExceptionHandler saved Memory Dump into the [%] file. Success: %s", memoryDumpFileName, success ? "True" : "False");

    return EXCEPTION_EXECUTE_HANDLER;
}

BOOL WINAPI DllMain(HINSTANCE hDllInstance, DWORD dwReason, LPVOID lpReserved)
{
    switch (dwReason)
    {
        case DLL_PROCESS_ATTACH:
            printf("Attaching the SolverExceptionHandler\n");
            SetLastError(0);
            SetUnhandledExceptionFilter(SolverExceptionHandler);
            printf("Did attach the SolverExceptionHandler. GetLastError: %d\n", GetLastError());
            break;
        default:
            break;
    }

    return TRUE;
}

Upvotes: 0

Views: 134

Answers (0)

Related Questions