.NET Profiler enter/leave function hooks does not get called in case of exception - c++

I am building a .Net Profiler for some custom requirement.
I want to hook at Enter and Leave for some specific methods. To achieve this, I have tried below two approaches.
IL Rewrite - I am able to inject the custom code at both the places. It is successfully getting injected and calling the custom code. I am also able to get the input arguments, 'this' and return value. Injecting at the Enter is not much difficult. However, it's complex to inject at Leave as there could be return at multiple places in a method. I have to inject the code at every place where return statement is written.
It's bit complex but somewhat doable. But, if there any exception, the execution is not reaching to return statement and hence my injected code is not getting invoked.
Subscribe to Enter/Leave through SetEnterLeaveFunctionHooks2 in ICorProfilerInfo2 as per the sample code given here.
In both the cases, hook at the Leave is not getting invoked in case of exception in the method.
How to handle this? I want a return value in all the scenarios. In case of an exception, I should know there is an exception; I will consider as 'No return value'. Probably, I may need exception details as well.
Below is a sample method. I want to hook at Enter and Leave for GetString method. It has multiple returns. I am able to capture the return value in a normal scenario. But in case of exception, execution stops immediately and due to that the hook at return is not getting invoked.
public int GetInt()
{
//int retVal = 10;
int retVal = 1010;
//throw new Exception("test");
return retVal;
}
public string GetString()
{
var retunValue = "Return string ";
if (GetInt() > 100)
{
retunValue += " inside IF > 100";
return retunValue;
}
return retunValue + " at last return";
}

To get the exception notification when using IL re-writing, you need to inject a try-finally or try-catch-throw. Since the ret instruction is not valid within a try block, you will need to replace them with a leave instruction that branches to an instruction after the inserted exception handler and return from there.
Another option is to include COR_PRF_MONITOR_EXCEPTIONS in your call to SetEventMask and listen on the ExceptionUnwindFunctionEnter and ExceptionUnwindFunctionLeave callbacks. These callbacks don't include the thrown exception however. You could track the exception from ExceptionThrown, but this may be misleading when an exception leaves a filter block as the runtime will treat it as returning false and continue with the previous exception, but IIRC, there is no callback to indicate when this happens.

Related

Using assert in main program logic of production code

Suppose I have this in a custom Stack implementation:
void Pop (Stack & s) {
assert (!isEmpty(s));
// implementation details of popping omitted
}
Suppose I want to catch bad client uses like popping an empty stack. "Assert" is great until you compile the production version and disable it via the NDEBUG flag. What's the most professional way of dying gracefully if you detect an unrecoverable error, assuming that you are going to turn off assertions eventually?
Yes, I know there are a bunch of options: use "exit"; change the function to return a C-like error code; use C++ exception handling; just ignore the offending operation (make bad calls into a no-op); implement a personal version assert called something else that won't get turned off, etc.
What the "most pro" thing to do here? I just want to die quickly, with a helpful message.
For fun, I created a vector instance from the standard library and popped it empty. This caused a seg fault, which might be acceptable for the standard library, but I want to catch and report such a problem before dying.
It is often used self defined assert macro with logging in production code. For example,
#define MYCOMPANY_ASSERT_FATAL(expression, msg, ret_val) if (!expression){ logger.fatal(msg); return ret_val;}
#define MYCOMPANY_ASSERT_WARN(...) .....
#define MYCOMPANY_ASSERT_ERROR(...) .....
Basically, the severity level of the error which should be regarded as exiting or messaging or so is dependent on your application program context layer. In short, some_lib_func() couldn't decide to exit an own process in most cases. That's why some_lib_func() should propagate the error information to caller. For example,
// library or middle module func couldn't decide to handle own application process, so after only logging return to caller
bool read_csv(double& val) {
double val = 0;
bool ret = parse_csv_from_file(val);
MYCOMPANY_ASSERT_ERROR(ret, "failed to parse_csv_from_file", false);
// return to caller with logging and error info(true/false here)
....
....
}
// application layer and need to handle for error which should be continue or message for user..
bool show_weather_in_foreign_country() {
bool ret = read_csv();
if (!ret) {
show_error_message();
}
// in this case read_csv error is trivial and you want to continue to process with proper message
...
}
In this case, showing weather is considered as trivial process in your application and you don't want to exit a whole application if error, so after showing a appropriate message and continue to process. In the other hand, another case below is critical, despite using the same function of read_csv.
// application layer and need to handle for error which should be continue or message for user..
bool send_your_account_balance_in_securiities_to_your_wife() {
double val = 0;
bool ret = read_csv(val);
MYCOMPANY_ASSERT_FATAL(ret, "critical in my account balance", false);
// in this application context, the failure of read_csv is critical and never continue to process
// and return to caller. Caller should probably exit an own application
send_email_your_wife(val);
// if send 0$ with some kind of mistake to you wife, she might die or kill you ...
...
}
Therefore, preparing some of defined macro for propagating error and logging is so useful and make your code simple and safe, and then you need to use them properly depending on your application contexts.

Setting up setCharging for Linea Pro device in Swift

I want to set up the Linea Pro to charge the phone if the phone's battery gets low and I'm having a tough time mainly because all the examples are shown in objective-C still and not in Swift.
The manual says:
#param enabled TRUE to enable charging, FALSE to disable/stop it
#param error pointer to NSError object, where error information is stored in case function fails. You can pass nil if you don't want that information
#return TRUE if function succeeded, FALSE otherwise
*/
and the code provided is the following:
-(BOOL)setCharging:(BOOL)enabled error:(NSError **)error;
So in Swift I first tried this:
self.scanner.setCharging = true
but that gives me the following error:
Cannot assign to property: 'setCharging' is a method
So I tried this:
self.scanner.setCharging(true)
which gives me this error:
Call can throw, but it is not marked with 'try' and the error is not handled
Interesting because apparently I have to build it in a function called "setCharging" I think, but I have no idea what and how it wants me to set up the try and catch to, and quite frankly where am I opposed to get this information from?
I think it should be along these lines or something, but I'm not clear on the specifics :
func setCharging(_ enabled: Bool) throws -> Bool {
do {
try
//something goes here I'm not sure what
} catch {
//and then maybe something here on that to do with error
print("some error")
}
}
The answer was provided to me by the manufacturer. It is unnecessary to create a function with the same name as the API, APIs can be called anywhere in the code with the exception of handling error. So in this case I just have this directly in my code not in a function and it just works. (Since I have my scanner.connect code inside a viewWillAppear block, the code to start charging was too early to be called in there, so I placed it inside of a viewDidAppear block).
The following is the code:
do{
try self.scanner.setCharging(true)
}catch let error as NSError{
NSLog("Operation \(error as Error)")
}

Regex for JavaScript source

XPages application fails with following stack trace:
com.ibm.jscript.InterpretException: Script interpreter error, line=30, col=43: 'component' is null
at com.ibm.jscript.ASTTree.ASTMember.interpret(ASTMember.java:153)
at com.ibm.jscript.ASTTree.ASTCall.interpret(ASTCall.java:88)
at com.ibm.jscript.ASTTree.ASTBlock.interpret(ASTBlock.java:100)
at com.ibm.jscript.ASTTree.ASTIf.interpret(ASTIf.java:85)
at com.ibm.jscript.ASTTree.ASTBlock.interpret(ASTBlock.java:100)
at com.ibm.jscript.ASTTree.ASTIf.interpret(ASTIf.java:85)
at com.ibm.jscript.ASTTree.ASTBlock.interpret(ASTBlock.java:100)
at com.ibm.jscript.ASTTree.ASTTry.interpret(ASTTry.java:109)
at com.ibm.jscript.ASTTree.ASTIf.interpret(ASTIf.java:85)
at com.ibm.jscript.ASTTree.ASTProgram.interpret(ASTProgram.java:119)
at com.ibm.jscript.ASTTree.ASTProgram.interpretEx(ASTProgram.java:139)
From this I know, that there is problem with variable "component" nested inside hierarchy of blocks:
if -> try -> { -> if -> { -> if -> { -> method call with invalid argument.
I don't know what to look for exactly, search for "component" yields too many results.
What regex should I use to find the right spot based on code hierarchy?
In this case I see a good chance that you have not put all your SSJS code into try/catch blocks. The bad news: searching the cause of this error is extremely cumbersome as close to all SSJS blocks may be the root cause of this error.
For that reason I placed my own rule (and ignore it every now and then) to put EVERY SSJS block into a try/catch like this:
try {
// ... do fancy stuff here
} catch (e) {
print(e.toString());
}
The toString() call is used for some special cases where the error object appears to no automatically convert into an object that can be handled by the print method.
If it is the case, you have not put all SSJS blocks into a try/catch, this is exactly the right time to do so and keep that coding pattern for the future. It really helps every now and then ;-)
Instead of printStackTrace and toString() , you could just say print(e), which will output only the error message(should be the same as e.message). The error object if passed to a java routine, you could get the error line.
variable "component" nested inside hierarchy of blocks ==> We have made this working without issues.

How to terminate a program when it crashes? (which should just fail a unit test instead of getting stuck forever)

Our unit tests fire off child processes, and sometimes these child processes crash. When this happens, a Windows Error Reporting dialog pops up, and the process stays alive until this is manually dismissed. This of course prevents the unit tests from ever terminating.
How can this be avoided?
Here's an example dialog in Win7 with the usual settings:
If I disable the AeDebug registry key, the JIT debugging option goes away:
If I disable checking for solutions (the only thing I seem to have control over via the control panel), it looks like this, but still appears and still stops the program from dying until the user presses something. WerAddExcludedApplication is documented to also have this effect.
A summary from the answers by jdehaan and Eric Brown, as well as this question (see also this question):
N.B. These solutions may affect other error reporting as well, e.g. failure to load a DLL or open a file.
Option 1: Disable globally
Works globally on the entire user account or machine, which can be both a benefit and a drawback.
Set [HKLM|HKCU]\Software\Microsoft\Windows\Windows Error Reporting\DontShowUI to 1.
More info: WER settings.
Option 2: Disable for the application
Requires modification to the crashing program, described in documentation as best practice, unsuitable for a library function.
Call SetErrorMode: SetErrorMode(SetErrorMode(0) | SEM_NOGPFAULTERRORBOX); (or with SEM_FAILCRITICALERRORS). More info: Disabling the program crash dialog (explains the odd arrangement of calls).
Option 2a: Disable for a function:
Requires modification to the crashing program, requires Windows 7/2008 R2 (desktop apps only) or higher, described in documenation as preferred to SetErrorMode, suitable for a thread-safe library function.
Call and reset SetThreadErrorMode:
DWORD OldThreadErrorMode = 0;
SetThreadErrorMode(SEM_FAILCRITICALERRORS,& OldThreadErrorMode);
…
SetThreadErrorMode (z_OldThreadErrorMode, NULL);
More info: not much available?
Option 3: Specify a handler
Requires modification to the crashing program.
Use SetUnhandledExceptionFilter to set your own structured exception handler that simply exits, probably with reporting and possibly an attempt at clean-up.
Option 4: Catch as an exception
Requires modification to the crashing program. For .NET applications only.
Wrap all code into a global try/catch block. Specify the HandleProcessCorruptedStateExceptionsAttribute and possibly also the SecurityCriticalAttribute on the method catching the exceptions. More info: Handling corrupted state exceptions
Note: this might not catch crashes caused by the Managed Debugging Assistants; if so, these also need to be disabled in the application.
Option 5: Stop the reporting process
Works globally on the entire user account, but only for a controlled duration.
Kill the Windows Error Reporting process whenever it shows up:
var werKiller = new Thread(() =>
{
while (true)
{
foreach (var proc in Process.GetProcessesByName("WerFault"))
proc.Kill();
Thread.Sleep(3000);
}
});
werKiller.IsBackground = true;
werKiller.Start();
This is still not completely bullet-proof though, because a console application may crash via a different error message, apparently displayed by an internal function called NtRaiseHardError:
The only solution is to catch all exceptions at a very high level (for each thread) and terminate the application properly (or perform another action).
This is the only way to prevent the exception from escaping your app and activating WER.
Addition:
If the exception is something you do not except to happen you can use an AssertNoThrow(NUnit) or alike in another Unit Test framework to enclose the code firing the child processes. This way you would also get it into your Unit test report. This is in my opinion the cleanest possible solution I can think of.
Addition2:
As the comments below show, I was mistaken: you cannot always catch the asynchronous exceptions, it depends on what the environment allows. In .NET some exceptions are prevented from being caught, what makes my idea worthless in this case...
For .NET: There are complicated workarounds involving the use of AppDomains, leading to an unload of an AppDomain instead of a crash of the whole application. Too bad...
http://www.bluebytesoftware.com/blog/PermaLink,guid,223970c3-e1cc-4b09-9d61-99e8c5fae470.aspx
http://www.develop.com/media/pdfs/developments_archive/AppDomains.pdf
EDIT:
I finally got it. With .NET 4.0 You can add the HandleProcessCorruptedStateExceptions attribute from System.Runtime.ExceptionServices to the method containing the try/catch block. This really worked! Maybe not recommended but works.
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;
namespace ExceptionCatching
{
public class Test
{
public void StackOverflow()
{
StackOverflow();
}
public void CustomException()
{
throw new Exception();
}
public unsafe void AccessViolation()
{
byte b = *(byte*)(8762765876);
}
}
class Program
{
[HandleProcessCorruptedStateExceptions]
static void Main(string[] args)
{
Test test = new Test();
try {
//test.StackOverflow();
test.AccessViolation();
//test.CustomException();
}
catch
{
Console.WriteLine("Caught.");
}
Console.WriteLine("End of program");
}
}
}
Try setting
HKCU\Software\Microsoft\Windows\Windows Error Reporting\DontShowUI
to 1. (You can also set the same key in HKLM, but you need admin privs to do that.)
This should prevent WER from showing any UI.

Exception handling aware of execution flow

Edit:
For personn interested in a cleaner way to implemenent that, have a look to that answer.
In my job I often need to use third-made API to access remote system.
For instance to create a request and send it to the remote system:
#include "external_lib.h"
void SendRequest(UserRequest user_request)
{
try
{
external_lib::Request my_request;
my_request.SetPrice(user_request.price);
my_request.SetVolume(user_request.quantity);
my_request.SetVisibleVolume(user_request.quantity);
my_request.SetReference(user_request.instrument);
my_request.SetUserID(user_request.user_name);
my_request.SetUserPassword(user_request.user_name);
// Meny other member affectations ...
}
catch(external_lib::out_of_range_error& e)
{
// Price , volume ????
}
catch(external_lib::error_t& e)
{
// Here I need to tell the user what was going wrong
}
}
Each lib's setter do checks the values that the end user has provided, and may thow an exception when the user does not comply with remote system needs. For instance a specific user may be disallowed to send a too big volume. That's an example, and actually many times users tries does not comply: no long valid instrument, the prices is out of the limit, etc, etc.
Conseqently, our end user need an explicit error message to tell him what to modify in its request to get a second chance to compose a valid request. I have to provide hiim such hints
Whatever , external lib's exceptions (mostly) never specifies which field is the source
of aborting the request.
What is the best way, according to you, to handle those exceptions?
My first try at handling those exceptions was to "wrap" the Request class with mine. Each setters are then wrapped in a method which does only one thing : a try/catch block. The catch block then throws a new exceptions of mine : my_out_of_range_volume, or my_out_of_range_price depending on the setter. For instance SetVolume() will be wrapped this way:
My_Request::SetVolume(const int volume)
{
try
{
m_Request.SetVolume(volume);
}
catch(external_lib::out_range_error& e)
{
throw my_out_of_range_volume(volume, e);
}
}
What do you think of it? What do you think about the exception handling overhead it implies? ... :/
Well the question is open, I need new idea to get rid of that lib constraints!
If there really are a lot of methods you need to call, you could cut down on the code using a reflection library, by creating just one method to do the calling and exception handling, and passing in the name of the method/property to call/set as an argument. You'd still have the same amount of try/catch calls, but the code would be simpler and you'd already know the name of the method that failed.
Alternatively, depending on the type of exception object that they throw back, it may contain stack information or you could use another library to walk the stack trace to get the name of the last method that it failed on. This depends on the platform you're using.
I always prefer a wrapper whenever I'm using third party library.
It allows me to define my own exception handling mechanism avoiding users of my class to know about external library.
Also, if later the third party changes the exception handling to return codes then my users need not be affected.
But rather than throwing the exception back to my users I would implement the error codes. Something like this:
class MyRequest
{
enum RequestErrorCode
{
PRICE_OUT_OF_LIMIT,
VOLUME_OUT_OF_LIMIT,
...
...
...
};
bool SetPrice(const int price , RequestErrorCode& ErrorCode_out);
...
private:
external_lib::Request mRequest;
};
bool MyRequest::SetPrice(const int price , RequestErrorCode& ErrorCode_out)
{
bool bReturn = true;
try
{
bReturn = mRequest.SetPrice(price);
}
catch(external_lib::out_of_range_error& e)
{
ErrorCode_out = PRICE_OUT_OF_LIMIT;
bReturn = false;
}
return bReturn;
}
bool SendRequest(UserRequest user_request)
{
MyRequest my_request;
MyRequest::RequestErrorCode anErrorCode;
bool bReturn = my_request.SetPrice(user_request.price, anErrorCode);
if( false == bReturn)
{
//Get the error code and process
//ex:PRICE_OUT_OF_LIMIT
}
}
I think in this case I might dare a macro. Something like (not tested, backslashes omitted):
#define SET( ins, setfun, value, msg )
try {
ins.setfun( value );
}
catch( external::error & ) {
throw my_explanation( msg, value );
}
and in use:
Instrument i;
SET( i, SetExpiry, "01-01-2010", "Invalid expiry date" );
SET( i, SetPeriod, 6, "Period out of range" );
You get the idea.
Although this is not really the answer you are looking for, but i think that your external lib, or you usage of it, somehow abuses exceptions. An exception should not be used to alter the general process flow. If it is the general case, that the input does not match the specification, than it is up to your app to valid the parameter before passing it to the external lib. Exceptions should only be thrown if an "exceptional" case occurrs, and i think whenever it comes to doing something with user input, you usually have to deal with everything and not rely on 'the user has to provide the correct data, otherwise we handle it with exceptions'.
nevertheless, an alternative to Neil's suggestions could be using boost::lambda, if you want to avoid macros.
In your first version, you could report the number of operations that succeeded provided the SetXXX functions return some value. You could also keep a counter (which increases after every SetXXX call in that try block) to note what all calls succeeded and based on that counter value, return an appropriate error message.
The major problem with validating each and every step is, in a real-time system -- you are probably introducing too much latency.
Otherwise, your second option looks like the only way. Now, if you have to write a wrapper for every library function and why not add the validation logic, if you can, instead of making the actual call to the said library? This IMO, is more efficient.