kambi
kambi

Reputation: 3433

Recoverying from exceptions

In our application (c++) we load 3rd party DLLs using LoadLibrary. Sometimes these DLLs cause exceptions, such as "Access violation reading location 0x00000000..".

Is it possible to recover from such an exception, for example using try & catch or some other mechanism? in other world, is that possible to create a sandbox within the same process that withstand such events?

Thank you

Upvotes: 0

Views: 1432

Answers (6)

Laurent Couvidou
Laurent Couvidou

Reputation: 33698

The people behind Runtime-Compiled C++ are using a thing called Structured Exception Handling for their DLL crash-handling routines. Dig into their website or ask them if you want some code samples.

According to the MSDN, the /EHa switch enables "C++ exception handling with structured exception handling exceptions". So if you're using the msvc compiler, you might want to try this.

Upvotes: 1

fat_lor_troll
fat_lor_troll

Reputation: 88

In Windows, with VisualStudio compiler, may use SEH mechanism.

__try
{
  char* ptr = 0;
  char val = *ptr;
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
{
  std::cout<<"AV"<<std::endl;
}

Use option /EHa.

Upvotes: 2

AlexTheo
AlexTheo

Reputation: 4184

It is not possible in c++ if, it is not possible throws a crossmodules exceptions anymore in any case you will have a memory corruption in your application so you have to find out what is going wrong in your dll. You can check the reason you cant throw exception from dll here: http://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL

Upvotes: 1

JTeagle
JTeagle

Reputation: 2196

You could try a different type of exception handler:

__try
{
    // Code that might cause an access violation goes here. 

}
__except (EXCEPTION_EXECUTE_HANDLER)
{
    int code = _exception_code();

}

Beware though, such handlers can't be used in any routine where C++ objects need stack unwinding as the compiler will warn you (irritatingly).

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258648

You can try the /EH flag - http://msdn.microsoft.com/en-us/library/1deeycx5%28v=vs.80%29.aspx - in Visual Studio, but access violation exceptions most likely mean you're doing something very wrong. I'd let the program crash and try to solve the exception, rather than catching it.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182865

No. It's not. A DLL has unrestricted access to the process context that calls it. You need to run untrustable DLLs in their own process context.

Upvotes: 4

Related Questions