Search code examples
c++exceptionportable-executableloadlibrary

Exception mechanism not working


I have a simple dll project, when dll is loaded it creates thread with code:

try
{
    throw std::exception("Not working");
}
catch (std::exception &err)
{
    printf("error %s\n", err.what());
}
catch (...)
{
    printf("unhandled\n");
}

But this code not working, it still telling me about unhandled exception Also I should say that problem in my loader I'm using own pe-mapper which loading dll without LoadLibrary So same code working in seperate exe or even with simple injection Obviously, for some reason the mechanism is broken, I solved the problems before, for example with fmath Question is what should I do to make exception mechanism working? What conditions does LoadLibrary for it?


Solution

  • Also I should say that problem in my loader I'm using own pe-mapper which loading dll without LoadLibrary

    this is exactly cause why any exception handlers will be not work in your code. you need only use LoadLibrary or LdrLoadDll for exception work. however even with LoadLibrary exist way load file from memory only - not from disk, but this is another story


    why ? you can ask. because RtlDispatchException - api which do exception dispatching - not unconditionally call exception handlers, but do many checks before this. it check are address of handler inside some DLL. if yes and this DLL have safe SEH - are handler address registered. if not in any DLL - are memory in where handler is in section (file mapping on win32 language) and are this section mapped as image (with SEC_IMAGE attribute) - otherwise this handler will be ignored. in case x64 - handlers at all not registred in TEB but in DLL section only (look RUNTIME_FUNCTION ). so system walk by list of DLL loaded for found handler address - look for RtlLookupFunctionEntry - so if your code will be not in DLL list sytem at all not found your handler.

    again exception handling not worked because and only because you not load your code with LoadLibrary