Visual Studio C++ weird exception when calling CefBrowserHost::CreateBrowser - c++

I am using CEF3 (chrome embedded framework) in my win32 application, while I am running the application I get a weird error message -
I am coming from a C# development background, and here in C++ I don't see how I can inspect my error and figure out why it's complaining about my code.
How can I check the error message? If not - how you debug this kind of errors in Visual Studio?
This the code which triggering the error -
case WM_CREATE:
{
CefRefPtr<CefClient> clientHandler = new ClientHandler();
RECT rect;
GetClientRect(hWnd, &rect);
CefWindowInfo info;
info.SetAsChild(hWnd, rect);
// Browser initialization settings.
CefBrowserSettings settings;
// Create the new browser window object asynchronously.
std::string startupUrl = "http://www.google.com/";
CefBrowserHost::CreateBrowser(info, clientHandler, startupUrl, settings);
}
break;
I don't want help in CEF3 (but I will appreciate it) I just want to know how to debug this kind of errors in Visual Studio.

The Output window of the debugger tells you what exception was thrown.
Also, you can click "Break" in the dialog that appears and VS will take you to the line on which the exception was thrown. You'll see a yellow arrow to the left of the line.
Finally, if the exception is not fatal, you can catch it and ignore it:
try
{
...
}
catch (const SomeException&)
{
// do nothing
}

I had problems building in Release. The problem was that I didn't called CefInitialize at all.

Related

Visual studio - how to catch debug (break) after show message box

I have a situation like this. In my code, there are countless code blocks like this.
try
{
DoSomething();
}
catch( Ogre::Exception& e )//Yes, I'm using Ogre, but you get the idea :)
{
MessageBoxA( NULL, e.getFullDescription().c_str(), "An exception has occured!",
MB_OK | MB_ICONERROR | MB_TASKMODAL );
}
I don't want to put breakpoint at every catch block. So each time an exception is thrown, a message box show up - I click ok and program close.
What I want is after I click Ok on the message box, Visual studio catch debug in the message box thread and I can see what happens down there in the source code.
Note: I don't know if 'catch debug' is a proper word, when I say 'catch debug', I mean: activate 'Step into' (F11)/'Step over' (F10) feature of Debug mode --> A yellow arrowhead in the margin of a source appears. Maybe the right word is 'break'.
PS: in my situation, I can just use the 'Exception settings' (for VS older than 2015, check this post) to Break When Throw all C++ Exceptions. Then when any C++ exception is throw, my VS 2015 will break to let me see what happens. Yet, I still want to solve this question, maybe there are situations when it is not exception but just message box - then a skill to break after message box is shown is required.
You are underestimating the power of Exception Settings. It allows you to carefully filter out types of the exceptions that you want to intercept. Open Exception Settings window, uncheck "C++ Exceptions" checkbox, select "C++ Exceptions" item (so entire line is highlighted, this will also activate "+" button on toolbar), press "+" button (or use context menu entry) to add Ogre::Exception type to the list of exceptions, check Ogre::Exception checkbox so only it will be intercepted.
If you had used MessageBox macro instead of implicitly using MessageBoxA, then you could have done a macro redefine inserting a DebugBreak() afterwards.
I think what I would try at this point is to place a breakpoint at User32!MessageBoxA. This way you get a break before each message box is executed. Then you F10 that call, which will execute the message box, when you press OK it returns back to debugger and you can inspect your code.
Add comment as the solution:
In VS2017, you could use the new feature called "Using the New Exception Helper" under Tools->Options->Debugging. It could provide much more debugging information than previous version like breaking on the Line of Code or faster breaking for Unhandled Exceptions and others.
If you want to stop the execution right after you enter the catch block, you want to use a function like DebugBreak(). Here is a snippet that you can try:
try
{
throw out_of_range("hello, stackoverflow");
}
catch (exception& e)
{
// Exection wil stop here.
// You will see the exception thrown above in the Output console.
DebugBreak();
}
Note that it will also work on the Release builds, not only in Debug.
EDIT
If you want exactly that yellow arrow, you could use a dirty hack that is VERY, VERY BAD PRACTICE:
try
{
throw out_of_range("hello, stackoverflow");
}
catch (exception& e)
{
// Now you will get the yellow arrow.
// From here, you could acces the call stack console that VS provides.
// By the way, you could have also done that in the previous example.
int b[1];
b[1000] = 0;
}

CWinApp OpenDocumentFile "unsupported operation" error

Problem
I'm trying to open an MFC program that reads a Microsoft Access database (.mdb) and allows the user to view or modify the data. This is an existing program (and source code) given to me by a group in another lab where the program opens and works just fine.
In our lab, I have yet to see it load properly. When run, it pops up a dialog box that says, "Attempted an unsupported operation". Windows then offers me a chance to debug and such before it crashes.
Environment
In the other lab, they use Windows 7 and Microsoft Office 2010, and it works.
In our lab, I've tried Windows 7 with Office 2013 and Windows XP with Office 2010. The latter crashes without giving me the dialog box. I don't know if we have a Win7/MSO2010 machine.
The Function
I have the source code for the program. The solution file implies it was last developed in VS2010, which the computers I tested on had installed as well. Running it out of Visual Studio 2010 or straight from the executable yields the same results.
I have added additional debug dialog boxes to the code that narrow down the problem to this function call, which the code never gets past:
CwinApp:OpenDocumentFile(LPCTSTR lpszPathName)
The single string passed into the function is a path and filename for the MS Access database to be opened. It exists in a temporary directory created by another program. This is on a drive other than C, though I've tested some there, as well. Problems with programs related to this one often stem from files with "read only" status, but I continually check the temporary files created, and they are write-able.
Documentation
I found this information titled "Breaking Changes in Visual C++" for VS2010 through another SO question:
A new virtual function was added to the CDocTemplate class. This new virtual function is CDocTemplate::OpenDocumentFile. The previous version of OpenDocumentFile had two parameters. The new version has three parameters. To support the restart manager, any class derived from CDocTemplate must implement the version that has three parameters. For more information about the function, see CDocTemplate::OpenDocumentFile. The new parameter is bAddToMRU.
Code
I feel this might be the answer! But I don't have a strong idea of exactly what to change to get this to work. Here's where I stopped:
Program.cpp
CDocument* ProgramApp::OpenDocumentFile(LPCTSTR lpszFileName, BOOL bAddToLRU, BOOL bMakeVisible)
{
// Add specialized code here and/or call base class
// Debug messages added
CDocument* tempDoc;
AfxMessageBox(lpszFileName);
tempDoc = CWinApp::OpenDocumentFile(lpszFileName, bAddToMRU);
AfxMessageBox("Opened database!");
return tempDoc;
}
Program.h
class ProgramApp : public CWinApp
{
public:
...
virtual CDocument* OpenDocumentFile(LPCTSTR lpszFileName, BOOL bAddToMRU, BOOL bMakeVisible);
afxwin.h
class CWinApp : public CWinThread
{
...
virtual CDocument* OpenDocumentFile(LPCTSTR lpszFileName);
virtual CDocument* OpenDocumentFile(LPCTSTR lpszFileName, BOOL bAddToMRU);
Changing the Program.cpp call to be from a "Template" class caused errors, but I wouldn't be surprised if that's towards the answer. This solution looks similar, but I'm not sure exactly what to do.
My hope is that this problem has a simple solution that someone more knowledgeable can give me. I would be much appreciative, and additional context would help a lot.
Edit: Debugging
I drilled down into the Windows code to see what was precisely going wrong. It seemed too dense to understand, but a coworker and I may have clues based on it. The failure message happens here:
dlgdata.cpp
// Could be a windowless OCX
pSite = m_pDlgWnd->GetOldControlSite(nIDC);
if (pSite == NULL)
{
TRACE(traceAppMsg, 0, "Error: no data exchange control with ID 0x%04x.\n", nIDC);
ASSERT(FALSE);
AfxThrowNotSupportedException();
}
...Although we are seeing debugger issues here:
occcont.cpp
COleControlSiteOrWnd *pemp = new COleControlSiteOrWnd(hwndCtrl, pOccDlgInfo->m_pItemInfo[i].bAutoRadioButton);
ASSERT(IsWindow(pTemp->m_hWnd));
if (IsWindow(pTemp->m_hWnd))
{
hwndStart = pTemp->m_hWnd;
...
My coworker believes this could have little to do with the opening of this document as I suspected and more to do with objects/controls we don't have on our lab computers trying to be used for the program.
I have faced the same problem in opendocumentfile(), there was a control in CFormView class which i was not using so i commented it out but forget to delete from .rc file. Once i remove the control entry from .rc file the problem disappear.
there should be no control variable uninitialize , please check that also

MessageBox "Abnormal program termination" keeps my application running

...kind of. As illustrated by this extremely simplistic example,
very rarely (only once reported so far), it happens that one of my applications crashes this way. I want to terminate it as I normally do when an unspecific exception occurs. My strategy is to (low-level) log the problem, then terminate. The application is part of a subsystem and I want to (re)start it, if any problem is detected. It's built with C++-Builder 6 and runs on Windows (XP...7, also 8). I learned that an abort() most probably caused the error message. The application has a GUI, that's why a message box is shown instead of just making an (unblocking) output to stderr.
And as long as the message box isn't accepted by a user, my application keeps obviously running, for example it handles timers (the lifebeats in the above example increase) or inter-process messages, fully unaware about the problem.
After reading some answers to What is the easiest way to make a C++ program crash? and Difference between raise(SIGABRT) and abort() methods, I tried the following
void mySignalHandler(int sig)
{
// low-level error reporting here
exit(-1);
}
void __fastcall TForm1::FormCreate(TObject *Sender)
{
signal(SIGABRT, mySignalHandler);
// some more initialisation here
}
which lets my application terminate properly also if abort() or raise(SIGABRT) is called. (I also wish to prevent Windows from "searching for a solution of the problem".)
Is this (registering a signal handler for abort and calling exit there) reliable from your point of view? ...or at least something one can build upon?
In the C++Builder installation folder, check the following files:
source\cpprtl\Source\misc\errormsg.c - implementation of _ErrorMessage
source\cpprtl\Source\procses\abort.c - implementation of abort, which calls _ErrorMessage
source\cpprtl\Source\misc\assert.c - implementation of _assert, which calls _ErrorMessage
errormsg.c defines an undocumented _messagefunc function pointer that you can set to override the default behavior. Although it's undocumented and not declared in any header files, you can declare it as an extern and access it that way. Sample usage:
extern int (_RTLENTRY * _EXPDATA _messagefunc)(char *msg);
static int LogAndDie(char *msg)
{
LogMessageToSomeFile(msg);
exit(1);
return 0;
}
void InitializeErrorHandling()
{
_messagefunc = LogAndDie;
}
You might be able to use Windows Error Reporting to create a dump of the process, when an unhandled exception causes a termination. Then you can review the dump at your leisure and allow some parent-process or other watchdog to restart your process. If you chose this strategy, you would not try to deal with the failure in your code, but to allow it.
If you want to capture any program exit you should look at atexit(). If you want to capture all termination events then look at std::set_terminate(), if you want to caputure all unexpected exceptions then look at std::set_unexpected(). If you want to capture only abort() you can call signal() with the SIGABRT signal value. You can also wrap your code with try{your code}catch(...){custom event handler}.
I could do some tests, and I only can confirm that registering a SIGABRT signal handler is simply a NOOP.
I tried it with a very simple GUI application written with VS2008 Express. :
no framework, nor .NET but only Win API
one menu with Exit and Fatal
menu managed directly in WndProc
Fatal execute 1/0
Here are the result :
no special action => windows opens a MessageBox indicating a fatal error ...
signal handler for SIGABRT => same MessageBox
C++ try catch(...) => same MessageBox
SEH in WndProc : can intercept the error !
SEH around message loop : can intercept the error !
If I put bot SEH handlers, the most internal (WndProc) catches.
The good new for you is that if is enough to protect the message loop, and you do not have to go into every WndProc.
The bad new is that I do not know C++ builder and cannot say where to find the message loop.
Just to give you a clue, here is how I could protect the message loop in a WinAPI application :
__try {
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
__except (EXCEPTION_EXECUTE_HANDLER){
::MessageBox(NULL, _T("FATAL"), _T("MAIN"), MB_OK | MB_ICONERROR);
}
That way, I can see my own message box, but nothing else and if I comment my message box the application silently exits.
But ... as the message you show is not original Windows one, I suspect C++ builder to already have such an exception handler in its message loop.
Hope it helps ...

MFC assertion failed when debugging

I'm not familiar with MFC but currently I must continue a project that was written in MFC. Now I'm having trouble with the following line when debugging
m_hIcon = AfxGetApp()->LoadIcon (IDR_MAINFRAME);
It always stops after the error "Assertion Failed: at afxwin1.inl". If I put a breakpoint there I saw a NULL icon handle. I tried running in release mode and it worked just fine although the handle is still NULL. I've read this question but my program is not a static library. It's a program that use a dll to connect to a CAN bus device. And the resource IDR_MAINFRAME is already in the project. It contains the default MFC icons. How can I solve this problem?
I've tried debugging and see that pModuleState changes between the first load program name call and the second load icon call. The first call returns successfully because pModuleState points to an object that has valid handle. But in the icon load call, pModuleState points to some object contains NULL handle. I also tried putting AFX_MANAGE_STATE(AfxGetStaticModuleState( )); right above the LoadIcon() call but the problem still arises
I've known the cause of this problem
UINT __cdecl RunCPRead(LPVOID pParam)
{
CMyDlg *thisclass = (CMyDlg *)pParam;
while (thisclass->m_Start)
{
thisclass->GetData();
}
return 0;
}
AfxBeginThread(&RunCPRead, this, THREAD_PRIORITY_NORMAL, 0, 0, NULL);
After the GetData() call in RunCPRead, the control flows directly to CMyDlg's contructor although there's no object being created or copied
CMyDlg::CMyDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMyDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
and then fails at the assignment to m_hIcon with the error "access violation while reading". I've seen the disassembly, it was the line mov dword ptr [esi+90h], eax and it's inherently a write to memory.
I don't know why. How can I solve this?
The MFC code need the correct module handle to load the resource.
Please try to read Afx*G/S*etResourceHandle.
By default MFC uses the resource handle of the main application, not of the DLL. If you are making the call in the DLL then add this line at the start of the exported DLL function:
AFX_MANAGE_STATE(AfxGetStaticModuleState( ));
There is more information about this here:
http://msdn.microsoft.com/en-us/library/ba9d5yh5(v=vs.110).aspx
Assertion Errors in MFC usually happens when wrong settings are set.
go to project settings > linker > System and change subsystem to (/SUBSYSTEM:WINDOWS) this solution solved my own problem.

How do I make Visual Studio pause after executing a console application in debug mode?

I have a collection of Boost unit tests I want to run as a console application.
When I'm working on the project and I run the tests I would like to be able to debug the tests, and I would like to have the console stay open after the tests run.
I see that if I run in release mode the console window stays up after the program exits, but in debug mode this is not the case.
I do not want to add 'system("pause");' or any other hacks like reading a character to my program. I just want to make Visual Studio pause after running the tests with debugging like it would if I were running in release mode. I would also like it if the output of tests were captured in one of Visual Studio's output windows, but that also seems to be harder than it should be.
How can I do this?
Try to run the application with the Ctrl + F5 combination.
http://connect.microsoft.com/VisualStudio/feedback/details/540969/missing-press-any-key-to-continue-when-lauching-with-ctrl-f5
In the older versions it would default to the console subsystem even if you selected "empty project", but not in 2010, so you have to set it manually. To do this select the project in the solution explorer on the right or left (probably is already selected so you don't have to worry about this). Then select "project" from the menu bar drop down menus, then select "project_name properties" > "configuration properties" > "linker" > "system" and set the first property, the drop down "subsystem" property to "console (/SUBSYSTEM:CONSOLE)". The console window should now stay open after execution as usual.
Boost test offers the following usage recommendations for Visual Studio that would enable you to run the unit tests automatically at the end of compilation and capture the output into the build window.
The nice side effect of this trick is it enable you to treat test failures as compilation errors. "...you could jump through these errors using usual keyboard shortcuts/mouse clicks you use for compilation error analysis..."
Set a breakpoint on the last line of code.
I just copied from http://social.msdn.microsoft.com/forums/en-US/Vsexpressvc/thread/1555ce45-8313-4669-a31e-b95b5d28c787/?prof=required:
The following works for me :-)
/////////////////////////////////////////////////////////////////////////////////////
Here is another reason the console may disappear. And the solution:
With the new Visual Studio 2010 you might see this behavior even when you use Ctrl + F5 aka "start without debugging". This is most likely because you created an "empty project" instead of a "Win32 console application". If you create the project as a "Win32 console application" you can disregard this as it does not apply.
In the older versions it would default to the console subsystem even if you selected "empty project", but not in Visual Studio 2010, so you have to set it manually. To do this select the project in the solution explorer on the right or left (probably is already selected so you don't have to worry about this).
Then select "project" from the menu bar drop down menus, then select "project_name properties" → "configuration properties" → "linker" → "system" and set the first property, the drop down "subsystem" property to "console (/SUBSYSTEM:CONSOLE)". The console window should now stay open after execution as usual.
/////////////////////////////////////////////////////////////////////////////////////
If it is a console application, use Ctrl + F5.
In Boost.Test there is the --auto_start_dbg parameter for breaking into the debugger when a test fails (on an exception or on an assertion failure). For some reason it doesn't work for me.
See http://www.boost.org/doc/libs/1_40_0/libs/test/doc/html/utf/usage-recommendations/dot-net-specific.html
For this reason I have created my custom test_observer that will break into the debugger when there is an assertion failure or an exception. This is enabled on debug builds when we are running under a debugger.
In one of the source files of my unit test EXE file I have added this code:
#ifdef _DEBUG
#include <boost/test/framework.hpp>
#include <boost/test/test_observer.hpp>
struct BoostUnitTestCrtBreakpointInDebug: boost::unit_test::test_observer
{
BoostUnitTestCrtBreakpointInDebug()
{
boost::unit_test::framework::register_observer(*this);
}
virtual ~BoostUnitTestCrtBreakpointInDebug()
{
boost::unit_test::framework::deregister_observer(*this);
}
virtual void assertion_result( bool passed /* passed */ )
{
if (!passed)
BreakIfInDebugger();
}
virtual void exception_caught( boost::execution_exception const& )
{
BreakIfInDebugger();
}
void BreakIfInDebugger()
{
if (IsDebuggerPresent())
{
/**
* Hello, I know you are here staring at the debugger :)
*
* If you got here then there is an exception in your unit
* test code. Walk the call stack to find the actual cause.
*/
_CrtDbgBreak();
}
}
};
BOOST_GLOBAL_FIXTURE(BoostUnitTestCrtBreakpointInDebug);
#endif
You say you don't want to use the system("pause") hack. Why not?
If it's because you don't want the program to prompt when it's not being debugged, there's a way around that. This works for me:
void pause () {
system ("pause");
}
int main (int argc, char ** argv) {
// If "launched", then don't let the console close at the end until
// the user has seen the report.
// (See the MSDN ConGUI sample code)
//
do {
HANDLE hConsoleOutput = ::GetStdHandle (STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE == hConsoleOutput)
break;
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (0 == ::GetConsoleScreenBufferInfo (hConsoleOutput, &csbi))
break;
if (0 != csbi.dwCursorPosition.X)
break;
if (0 != csbi.dwCursorPosition.Y)
break;
if (csbi.dwSize.X <= 0)
break;
if (csbi.dwSize.Y <= 0)
break;
atexit (pause);
} while (0);
I just paste this code into each new console application I'm writing. If the program is being run from a command window, the cursor position won't be <0,0>, and it won't call atexit(). If it has been launched from you debugger (any debugger) the console cursor position will be <0,0> and the atexit() call will be executed.
I got the idea from a sample program that used to be in the MSDN library, but I think it's been deleted.
NOTE: The Microsoft Visual Studio implementation of the system() routine requires the COMSPEC environment variable to identify the command line interpreter. If this environment variable gets messed up -- for example, if you've got a problem in the Visual Studio project's debugging properties so that the environment variables aren't properly passed down when the program is launched -- then it will just fail silently.
It would actually be more effort, but you could just build in VS.Net, run it from the regular command line (cmd.exe), and then attach to the process after it starts running. This is probably not the solution you are looking for however.
Or you could use boost_test "Test Log Output."
http://www.boost.org/doc/libs/1_47_0/libs/test/doc/html/utf/user-guide/test-output/test-log.html
Then it won't matter whether the console window shows up at all AND your build logging can preserve the unit testing output as an artifact for examination on failed builds...
Adding the following line will do a simple MS-DOS pause displaying no message.
system("pause >nul | set /p \"=\"");
And there is no need to Ctrl+F5 (which will make your application run in Release Mode)
I would use a "wait"-command for a specific time (milliseconds) of your own choice. The application executes until the line you want to inspect and then continues after the time expired.
Include the <time.h> header:
clock_t wait;
wait = clock();
while (clock() <= (wait + 5000)) // Wait for 5 seconds and then continue
;
wait = 0;
You could also setup your executable as an external tool, and mark the tool for Use output window. That way the output of the tool will be visible within Visual Studio itself, not a separate window.
I start the app with F11 and get a breakpoint somewhere in unit_test_main.ipp (can be assembly code). I use shift-f11 (Step out) to run the unit test and get the next assembly instruction in the CRT (normally in mainCRTStartup()). I use F9 to set a breakpoint at that instruction.
On the next invocation, I can start the app with F5 and the app will break after running the tests, therefore giving me a chance to peek at the console window
Just use a logging library, like log4net, and have it log to a file appender.
Prompt for user input.
https://www.youtube.com/watch?v=NIGhjrWLWBo
shows how to do this for C++. For Node.js, this is taken right from the docs (and it works):
'use strict';
console.log('Hello world');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Press enter to continue...', (answer) => {
rl.close(); /* discard the answer */
});
Do a readline at the end (it's the "forma cochina", like we say in Colombia, but it works):
static void Main(string[] args)
{
.
.
.
String temp = Console.ReadLine();
}