Intel pin tool cannot catch thrown exceptions - exception

I am now learning Intel pin, I write the following codes in main function of my pintool.
try
{
throw std::exception("test daniel");
}
catch (std::exception& e)
{
printf(e.what());
}
Run it( pin.exe -t Test.dll -- calc.exe), but it just crashed, this is definitely due to an uncaught exception.
But I wonder why my "catch" code failed.
Anyone know the reason, or how to catch exception in pintool?

Here is how thrown exceptions should be catched in a pintool, assuming you have all the mandatory compile options. It should be noted that this simple pintool does not do anything beside catching exceptions thrown by pin or the tool (not the application).
You will note that the registration of the exception handler function occures before the PIN_StartProgram() function, otherwise exceptions will be ignored.
Finally, although it is not mentioned in the documentation, I would expect that exceptions thrown after the call to PIN_AddInternalExceptionHandler() and before PIN_StartProgram() be not catched by the handler. I would instead expect the handler to catch exceptions thrown after PIN_StartProgram(), but again, it is not mentioned in the documentation.
//-------------------------------------main.cpp--------------------------------
#include "pin.h"
#include <iostream>
EXCEPT_HANDLING_RESULT ExceptionHandler(THREADID tid, EXCEPTION_INFO *pExceptInfo, PHYSICAL_CONTEXT *pPhysCtxt, VOID *v)
{
EXCEPTION_CODE c = PIN_GetExceptionCode(pExceptInfo);
EXCEPTION_CLASS cl = PIN_GetExceptionClass(c);
std::cout << "Exception class " << cl;
std::cout << PIN_ExceptionToString(pExceptInfo);
return EHR_UNHANDLED ;
}
VOID test(TRACE trace, VOID * v)
{
// throw your exception here
}
int main(int argc, char *argv[])
{
// Initialize PIN library. This was apparently missing in your tool ?
PIN_InitSymbols();
if( PIN_Init(argc,argv) )
{
return Usage();
}
// Register here your exception handler function
PIN_AddInternalExceptionHandler(ExceptionHandler,NULL);
//register your instrumentation function
TRACE_AddInstrumentFunction(test,null);
// Start the program, never returns...
PIN_StartProgram();
return 0;
}

Related

C++Winrt how to throw and handle exception without terminating program

I have following code
IAsyncOperation<bool> trythiswork()
{
bool contentFound{ false };
try
{
auto result = co_await someAsyncFunc();
winrt::check_bool(result)
if (result)
{
contentFound = true;
}
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
}
co_return contentFound;
}
When the result is false, it fails and throws but catch goes to fail fast and program terminates. How does log function terminate the program? Isn't it supposed to only log the exception? I assumed that I am handling this exception so program won't crash but it is crashing.
So how to throw and catch so that program does not terminate? I do want to throw. And also catch and preferably log the exception as well.
Thanks
The issue can be reproduced using the following code:
IAsyncOperation<bool> someAsyncFunc() { co_return false; }
IAsyncOperation<bool> trythiswork()
{
auto contentFound { false };
try
{
auto result = co_await someAsyncFunc();
winrt::check_bool(result);
// throw std::bad_alloc {};
contentFound = true;
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
}
co_return contentFound;
}
int main()
{
init_apartment();
auto result = trythiswork().get();
}
As it turns out, everything works as advertised, even if not as intended. When running the code with a debugger attached you will see the following debug output:
The exception %s (0x [trythiswork]
Not very helpful, but it shows that logging itself works. This is followed up by something like
FailFast(1) tid(b230) 8007023E {Application Error}
causing the process to terminate. The WIL only recognizes exceptions of type std::exception, wil::ResultException, and Platform::Exception^. When it handles an unrecognized exception type it will terminate the process by default. This can be verified by commenting out the call to check_bool and instead throwing a standard exception (such as std::bad_alloc). This produces a program that will log exception details, but continue to execute.
The behavior can be customized by registering a callback for custom exception types, giving clients control over translating between custom exception types and HRESULT values. This is useful in cases where WIL needs to interoperate with external library code that uses its own exception types.
For C++/WinRT exception types (based on hresult_error) the WIL already provides error handling helpers that can be enabled (see Integrating with C++/WinRT). To opt into this all you need to do is to #include <wil/cppwinrt.h> before any C++/WinRT headers. When using precompiled headers that's where the #include directive should go.
With that change, the program now works as desired: It logs exception information for exceptions that originate from C++/WinRT, and continues to execute after the exception has been handled.

difference kernel exception handling and programming language exception handling

I don't understand how c++, java or others high level languages that support exception handling work???
I know that if I write an application will be run in user mode and if it rises an exception like zero division, the system call an interrupt routine in kernel mode or use my try/catch block???
what I want to say is:
when I write simple code in c++ for example like this:
#include <iostream>
using namespace std;
double divide(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = divide(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
and compile it, I'm getting an software with inside an exception routine.
I mean, during execution code CPU will try to do x/y and will raise an exception. Now, in this case who handles this error:
1) process un user mode pass the workflow to an exception routine that I write
Or
2) System switch in kernel mode and throw a trap for running an interrupt routine.
I don't understand what is the specific steps that system like linux or windows use to solve an exception???

dlsym function return type

i am loading libslabhidtouart.so file using dlopen() without any error but when i am calling a function using dlsym() ,I got no such process error
here is my code
int main(int argc, char **argv)
{
typedef unsigned int DWORD;
typedef unsigned short WORD;
typedef int HID_UART_STATUS;
void *handle;
HID_UART_STATUS (*cosine)( DWORD*,WORD,WORD);
//typedef void (*simple_demo_function)(void);
char *error;
handle = dlopen("libslabhidtouart.so.1.0", RTLD_NOW);
if (!handle) {
fprintf(stderr, " %s\n", dlerror());
getchar();
exit(EXIT_FAILURE);
}
dlerror(); /* Clear any existing error */
/* Writing: cosine = (double (*)(double)) dlsym(handle, "cos");
would seem more natural, but the C99 standard leaves
casting from "void *" to a function pointer undefined.
The assignment used below is the POSIX.1-2003 (Technical
Corrigendum 1) workaround; see the Rationale for the
POSIX specification of dlsym(). */
*(void **) (&cosine) = dlsym(handle, "HidUart_GetNumDevices");
if ((error = dlerror()) != NULL) {
fprintf(stderr, " %s\n", error);
getchar();
exit(EXIT_FAILURE);
}
getchar();
dlclose(handle);
exit(EXIT_SUCCESS);
return 0;
}
/**** return type of function HidUart_GetNumDevices is int,so is there any casting problem or my method signature is wrong or what else plz guide me,i am no good at c .
I also got strange "No such process" errors, yet already directly upon a dlopen() call within OpenSSL:
2675996:error:25066067:lib(37):func(102):reason(103):dso_dlfcn.c:187:filename(./engine_pkcs11.dll): No such process
It turned out that the referenced DLL (or .so file) exists, but has a dependency on some other library (cygp11-2.dll in my case) that could not be resolved in the context of the application's process (taking into account its PATH environment variable setting). In this case, use ldd (or cygcheck.exe if applicable) to see if all dependencies are correctly resolved.
So the "no such process" error message returned by dlerror() can be quite misleading.

WinRt. UnhandledException handler. StackTrace is null

I have a project on WinForms with this code:
AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
private void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{ }
The e.ExceptionObject contains full StackTrace.
In Win Store project:
this.UnhandledException += (s, e) =>{
{
MarkedUp.AnalyticClient.LogLastChanceException(e);
};
e.Exception.StackTrace is null.
Both exceptions were generated by this code:
int a=0;
....
try
{
int i = 1 / a;
}
catch (Exception exp)
{
throw;
}
Any Ideas?
The reference on MSDN suggests that this is a limitation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.application.unhandledexception
A notable limitation is that the UnhandledException event arguments don’t contain as much detail as the original exception as propagated from app code. Whenever possible, if the app requires specific processing of a certain exception, it’s always better to catch the exception as it propagates, because more detail will be available then. The UnhandledException event arguments expose an exception object through the Exception property. However, the type, message, and stack trace of this exception object are not guaranteed to match those of the original exception that was raised. The event arguments do expose a Message property. In most cases, this will contain the message of the originally raised exception.
Are you running the solution in Debug mode? There seems to be happening something in the App.g.i.cs file when you run the solution in Debug mode. When I run your sample in Release mode the stacktrace is available in the UnhandledException event.
In my test solution it breaks first here:
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
#endif
And after that one it goes to the UnhandledException handler that I have defined in the app.xaml.cs file. In Debug the stacktrace is gone, in Release mode the stacktrace and the exception details are there.

Catching boost::exception for logging

I'm using Boost for some in-house codes. In main(), I would like to catch and log all boost::exceptions before exiting the program.
How do I catch boost::exceptions and retrieve the exception information as a string, for logging?
I recommend that you take a look at boost::diagnostic_information.
Here is an example for you. It is by no means complete and will take some customization to get it to do exactly what you want.
void main()
{
try
{
// Your code that can throw.
}
catch (const boost::exception& ex)
{
// Output some debug information.
std::cerr << boost::diagnostic_information(ex) << std::endl;
// Here we can choose to perform some graceful-shutdown activities,
// and/or rethrow the exception, triggering a call to std::terminate().
throw; // Rethrow.
}
catch (const std::exception& ex)
{
// Let's do the same for std::exception just for comparison.
std::cerr << ex.what() << std::endl;
throw; // Rethrow.
}
}
Where you will probably need to customize this:
Rethrowing in the main will trigger a std::terminate(). You might want to perform some tasks that more gracefully shutdown your code.
std::cerr might not be a great place to send this sort of information for you. Perhaps you want to log it to file. Or perhaps you might want to redirect std::cerr to a file.
Your code may have a chance of throwing something that is not a boost::exception or a std::exception. Maybe you want a catch all for that: catch (...)
Keep in mind that this is try-catch block only comes into play on the main thread of your application. You will have to do something similar in the entrypoints of any other threads that might throw an exception that is not handled.
This is no replacement for proper exception handling throughout your entire application.