Under what circumstances does Internet Explorer fail to properly unload an ActiveX control? - c++

I'm running into a perplexing problem with an ActiveX control I'm writing - sometimes, Internet Explorer appears to fail to properly unload the control on process shutdown. This results in the control instance's destructor not being called.
The control is written in C++, uses ATL and it's compiled using Visual Studio 2005. The control instance's destructor is always called when the user browses away from the page the control is embedded in - the problem only occurs when the browser is closed.
When I run IE under a debugger, I don't see anything unusual - the debugger doesn't catch any exceptions, access violations or assertion failures, but the problem is still there - I can set a breakpoint in the control's destructor and it's never hit when I close the broswer.
In addition, when I load a simple HTML page that embeds multiple instances of the control I don't see the problem. The problem only appears to happen when the control is instantiated from our web application, which inserts tags dynamically into the web page - of course, not knowing what causes this problem, I don't know whether this bit of information is relevant or not, but it does seem to indicate that this might be an IE problem, since it's data dependent.
When I run the simple test case under the debugger, I can set a breakpoint in the control's destructor and it's hit every time. I believe this rules out a problem with the control itself (say, an error that would prevent the destructor from ever being called, like an interface leak.)
I do most of my testing with IE 6, but I've seen the problem occur on IE 7, as well. I haven't tested IE 8.
My working hypothesis right now is that there's something in the dynamic HTML code that causes the browser to leak an interface on the ActiveX control. So far, I haven't been able to produce a good test case that reproduces this outside of the application, and the application is a bit too large to make a good test case.
I was hoping that someone might be able to provide insight into possible IE bugs that are known to cause this kind of behavior. The answer provided below, by the way, is too general - I'm looking for a specific set of circumstances that is known to cause this. Surely someone out there has seen this before.

To debug a problem in COM with C++ where an object's (C++) destructor is not being called, the best approach is to focus on how the COM object's refcounts are being incremented or decremented. What is probably happening is that somebody is incrementing the refcount one too many times, and then not decrementing it the same number of times. This leads to the object not being freed.
It is possible that your dynamic HTML is simply showing up a bug in IE, which doesn't happen if you use a static page.
If there is a bug in IE, the trick would be to figure out what causes the bug to appear, and what you can do to trick IE into releasing your COM object properly (like, making the HTML go away).

Another approach - add cleanup code to your DllMain function (adding that function if it doesn't already exist). Then regardless of reference counts (and reference count errors), when your DLL is unloaded you can clean yourself up:
BOOL WINAPI DllMain(HINSTANCE, DWORD dwReason, LPVOID) {
if (dwReason == DLL_PROCESS_DETACH) {
CleanUpAnyObjectsStillAlive();
}
}
Oh, and a word of warning - don't take too long doing your cleanup - if you do, I can't promise the process shutdown won't kill you anyway.

I have the same problem, but only on a specific computer.
This computer also has a problem with the Flash ActiveX, that remains alive after closing the tab.
My guess is that the problem is not with your code. Do you have that problem on other computers?

Related

Windows has generated a breakpoint

I'm debugging my C++ Win32 program in VS2010 and I always get "Windows has triggered a breakpoint in program.exe".
I've double-checked, triple-checked, and quadruple-checked the code. I can't find any reason it should be happening. But it happens at the same point each time so there must be something.
There is quite a lot of code involved (constructors, destructors, window messages, memory allocation and deallocation, etc...) so it's quite difficult to put something concrete here, but at the same time I understand that without the code you can't really do much to give an explanation.
Basically at the click of a button, a window is shown which shows an image. If a certain condition is met, I send a WM_DESTROY to that window and delete the variable which triggers the destructor which calls Release() on my LPPICTURE, and the freed variable gets set to NULL.
Then, when the user clicks the button again, it tries to dynamically allocate a new instance (in the exact same way it did previously), and that's where the breakpoint is generated. AFAIK (and I've been trying to debug this for over an hour now), the constructor doesn't even start. It seems to be breaking inside the new() function for dynamic memory allocation.
As far as I can tell, it breaks on return HeapAlloc(_crtheap, 0, size ? size : 1); which is line 54 or malloc.c
What's weird is that when I run the exe outside of VS2010, everything continues fine. The program doesn't crash, and it continues to work as expected!
It's difficult to diagnose without seeing the code, but based on your description, it sounds like heap corruption. My guess is that HeapAlloc detected corruption and generated a int 3 which will essentially trigger a breakpoint in the debugger. My advice is to review all of your object allocations/deallocations and make sure that you aren't stepping on memory that you have not allocated (or that has already been freed).
Also, you mentioned that you are sending a WM_DESTROY message explicitly. Typically, you want to let Windows generate the WM_DESTROY message for you, either by calling DestroyWindow, or by sending WM_CLOSE to the window and letting DefWindowProc call DestroyWindow for you. This may be unrelated to your issue, but just FYI.
In my experience when that happens you have heap correction/invalid pointer usage. The breakpoint occurs at the point where the fault is detected. This is almost never the actual failure - the problem occurred earlier. Those types of breakpoint occur only with a debugger present. Many times the corruption is not fatal or even is fixed by some other action.
In any event you should consider appverifier to see if it can find the problem. Be sure to use the heap checking options.
i think the problem is if your debugging inside visual studio you must put the needed files (in this case the image you are talking about) files in a certain directory in the debug folder ,the program crashes (while being debugged) because it does not find the file therefore when you run the exe outside of VS2010 it doesnt crash

What exactly does a debugger do?

I've stumbled onto a very interesting issue where a function (has to deal with the Windows clipboard) in my app only works properly when a breakpoint is hit inside the function. This got me wondering, what exactly does the debugger do (VS2008, C++) when it hits a breakpoint?
Without directly answering your question (since I suspect the debugger's internal workings may not really be the problem), I'll offer two possible reasons this might occur that I've seen before:
First, your program does pause when it hits a breakpoint, and often that delay is enough time for something to happen (perhaps in another thread or another process) that has to happen before your function will work. One easy way to verify this is to add a pause for a few seconds beforehand and run the program normally. If that works, you'll have to look for a more reliable way of finding the problem.
Second, Visual Studio has historically (I'm not certain about 2008) over-allocated memory when running in debug mode. So, for example, if you have an array of int[10] allocated, it should, by rights, get 40 bytes of memory, but Visual Studio might give it 44 or more, presumably in case you have an out-of-bounds error. Of course, if you DO have an out-of-bounds error, this over-allocation might make it appear to be working anyway.
Typically, for software breakpoints, the debugger places an interrupt instruction at the location you set the breakpoint at. This transfers control of the program to the debugger's interrupt handler, and from there you're in a world where the debugger can decide what to do (present you with a command prompt, print the stack and continue, what have you.)
On a related note, "This works in the debugger but not when I run without a breakpoint" suggests to me that you have a race condition. So if your app is multithreaded, consider examining your locking discipline.
It might be a timing / thread synchronization issue. Do you do any multimedia or multithreading stuff in your program?
The reason your app only works properly when a breakpoint is hit might be that you have some watches with side effects still in your watch list from previous debugging sessions. When you hit the break point, the watch is executed and your program behaves differently.
http://en.wikipedia.org/wiki/Debugger
A debugger essentially allows you to step through your source code and examine how the code is working. If you set a breakpoint, and run in debug mode, your code will pause at that break point and allow you to step into the code. This has some distinct advantages. First, you can see what the status of your variables are in memory. Second, it allows you to make sure your code is doing what you expect it to do without having to do a whole ton of print statements. And, third, it let's you make sure the logic is working the way you expect it to work.
Edit: A debugger is one of the more valuable tools in my development toolbox, and I'd recommend that you learn and understand how to use the tool to improve your development process.
I'd recommend reading the Wikipedia article for more information.
The debugger just halts execution of your program when it hits a breakpoint. If your program is working okay when it hits the breakpoint, but doesn't work without the breakpoint, that would indicate to me that you have a race condition or another threading issue in your code. The breakpoint is stopping the execution of your code, perhaps allowing another process to complete normally?
It stops the program counter for your process (the one you are debugging), and shows the current value of your variables, and uses the value of your variables at the moment to calculate expressions.
You must take into account, that if you edit some variable value when you hit a breakpoint, you are altering your process state, so it may behave differently.
Debugging is possible because the compiler inserts debugging information (such as function names, variable names, etc) into your executable. Its possible not to include this information.
Debuggers sometimes change the way the program behaves in order to work properly.
I'm not sure about Visual Studio but in Eclipse for example. Java classes are not loaded the same when ran inside the IDE and when ran outside of it.
You may also be having a race condition and the debugger stops one of the threads so when you continue the program flow it's at the right conditions.
More info on the program might help.
On Windows there is another difference caused by the debugger. When your program is launched by the debugger, Windows will use a different memory manager (heap manager to be exact) for your program. Instead of the default heap manager your program will now get the debug heap manager, which differs in the following points:
it initializes allocated memory to a pattern (0xCDCDCDCD comes to mind but I could be wrong)
it fills freed memory with another pattern
it overallocates heap allocations (like a previous answer mentioned)
All in all it changes the memory use patterns of your program so if you have a memory thrashing bug somewhere its behavior might change.
Two useful tricks:
Use PageHeap to catch memory accesses beyond the end of allocated blocks
Build using the /RTCsu (older Visual C++ compilers: /GX) switch. This will initialize the memory for all your local variables to a nonzero bit pattern and will also throw a runtime error when an unitialized local variable is accessed.

Application crashes says : Access violation reading location

My application crashes after running for around 18 hours. I am not able to debug the point in the code where it actually crashes. I checked the call stack- it does not provide any information as such. The last few calls in the call stack are greyed out-meaning I cannot see the code of that part-they all belong to MFC libraries.
However, I get this 'MicroSoft Visual Studio' pop-up when it crashes which says :
Unhandled exception at 0x7c809e8a in NIMCAsst.exe: 0xC0000005:
Access violation reading location 0x154c6000.
Could the above information be useful to understand where it is crashing.Is there any software that could tell me a particular memory address is held by which variable in the code.
If you can't catch the exception sometimes you just have to go through your code line by line, very unpleasant but I'd put money on it being your code not in MFC (always is with my bugs). Check how you're using memory and what you're passing into the MFC functions extra carefully.
Probably the crash is caused by a buffer overflow or other type of memory corruption. This has overwritten some part of the stack holding the return address which has made the debugger unable to reconstruct the stack trace correctly. Or, that the code that caused the crash, you do not have correct sybols for (if the stack trace shows a module name, this would be the case).
My first guess would be to examine the code calling the code that crashed for possible issues that might have caused it. Do you get any other exceptions or error conditions before the crash? Maybe you are ignoring an error return? Did you try using the Debug Heap? What about adplus? Application verifier to turn on heap checks?
Other possibilities include to run a tool like pclint over the code to check for obvious issues of memory use. Are you using threads? Maybe there is a race condition. The list could go on forever really.
The above information only tells you which memory was accessed illegally.
You can use exception handling to narrow down the place where the problem occurs, but then you need at least an idea in which corner to seek.
You say that you're seeing the call stack, that suggests you're using a debugger. The source code of MFC is available (but perhaps not with all vc++ editions), so in principle one can trace through it. Which VC++ version are you using?
The fact that the bug takes so long to occur suggests that it is memory corruption. Some other function writes to a location that it doesn't own. This works a long time, but finally the function alters a pointer that MCF needs, and after a while MFC accesses the pointer and you are notified.
Sometimes, the 'location' can be recognized as data, in which case you have a hint. F.e. if the error said:
Access violation reading location 0x31323334
you'd recognize this as a part of an ASCII string "1234", and this might lead you to the culprit.
As Patrick says, it's almost definitely your code giving MFC invalid values. One guess would be you're passing in an incorrect length so the library is reading too far. But there are really a multitude of possible causes.
Is the crash clearly reproducible?
If yes, Use Logfiles! You should use a logfile and add a number statements that just log the source file/line number passed. Start with a few statements at the entrypoint (main event handler) and the most common execution paths. After the crash inspect the last entry in the logfile. Then add new entries down the path/paths that must have been passed etc. Usually after a few iterations of this work you will find the point of failure. In case of your long wait time the log file might become huge and each iteration will take another 18 hours. You may need to add some technique of rotating log files etc. But with this technique i was able to find some comparable bugs.
Some more questions:
Is your app multithreaded?
Does it use any arrays not managed by stl or comparable containers (does it use C-Strings, C/C++-Arrays etc)?
Try attaching a debugger to the process and have the debugger break on access violations.
If this isnt possible then we use a tool called "User mode process dumper" to create a memory dump of the process at the point where the access violation happened. You can find this for download here:
http://www.microsoft.com/downloads/details.aspx?FamilyID=E089CA41-6A87-40C8-BF69-28AC08570B7E&displaylang=en
How it works: You configure rules on a per-process (or optionally system-wide) basis, and have the tool create either a minidump or a full dump at the point where it detects any one of a list of exceptions - one of them being an access violation. After the dump has been made the application continues as normal (and so if the access violation is unhandled, you will then see this dialog).
Note that ALL access violations in your process are captured - even those that are then later handled, also a full dump can create a while to create depending on the amount of memory the application is using (10-20 seconds for a process consuming 100-200 MB of private memory). For this reason it's probably not a good idea to enable it system-wide.
You should then be able to analyse the dump using tools like WinDbg (http://www.microsoft.com/whdc/devtools/debugging/default.mspx) to figure out what happened - in most cases you will find that you only need a minidump, not a full dump (however if your application doesnt use much memory then there arent really many drawbacks of having a full dump other than the size of the dump and the time it takes to create the dump).
Finally, be warned that debugging access violations using WinDbg can be a fairly involed and complex process - if you can get a stack trace another way then you might want to try that first.
This is the cause of possible memory leak, there are various blogs could teach on checking for memory leaks in application, you simply make observations on Physical Memory of the process from Windows Task Manager, you could find at some stage where memory keep increasing & run out of memory. You can also try running with windbg tool to identify memory leaks in your code. I havent used this tool just giving some heads up on this.
This question is pretty old, and I've had the same problem,
but I've quickly solved it - it's all about threads:
First, note that updating GUI can only be done at the Main Thread.
My problem was that I've tried to handle GUI from a Worker Thread (and not a Main Thread) and i've got the same error: 0xC0000005.
I've solved it by posting a message (which is executed at the Main Thread) - and the problem was solved:
typedef enum {
WM_UPDATE_GUI
}WM_MY_MSG
// register function callback to a message
BEGIN_MESSAGE_MAP(CMyDlg, CDlgBase)
ON_MESSAGE(WM_UPDATE_GUI, OnUpdateGui)
END_MESSAGE_MAP()
// For this example - function that is not invoked in the Main Thread:
void CMyDlg::OnTimer()
{
CString str_to_GUI("send me to gui"); // send string to gui
// Update_GUI(str_to_GUI); // crashed
::PostMessage(hWnd, MyMsg::WM_UPDATE_GUI, (WPARAM)&str_to_GUI, 0);
}
HRESULT CMyDlg::OnUpdateGui(WPARAM wParam, LPARAM lParam)
{
CString str = *(CString*)wParam; // get the string from the posted message
Update_GUI(str);
return S_OK;
}

debug stack overflow in windows?

So I'm trying to debug this strange problem where a process ends without calling some destructors...
In the VS (2005) debugger, I hit 'Break all' and look around in the call stacks of the threads of the misteriously disappearing process, when I see this:
smells like SO http://img6.imageshack.us/img6/7628/95434880.jpg
This definitely looks like a SO in the making, which would explain why the process runs to its happy place without packing its suitcase first.
The problem is, the VS debugger's call stack only shows what you can see in the image.
So my question is: how can I find where the infinite recursion call starts?
I read somewhere that in Linux you can attach a callback to the SIGSEGV handler and get more info on what's going on.
Is there anything similar on Windows?
To control what Windows does in case of an access violation (SIGSEGV-equivalent), call SetErrorMode (pass it parameter 0 to force a popup in case of errors, allowing you to attach to it with a debugger.)
However, based on the stack trace you have already obtained, attaching with a debugger on fault may yield no additional information. Either your stack has been corrupted, or the depth of recursion has exceeded the maximum number of frames displayable by VS. In the latter case, you may want to decrease the default stack size of the process (use the /F switch or equivalent option in the Project properties) in order to make the problem manifest itself sooner, and make sure that VS will display all frames. You may, alternatively, want to stick a breakpoint in std::basic_filebuf<>::flush() and walk through it until the destruction phase (or disable it until just prior to the destruction phase.)
Well, you know what thread the problem is on - it might be a simple matter of tracing through it from inception to see where it goes off into the weeds.
Another option is to use one of the debuggers in the Debugging Tools for Windows package - they may be able to show more than the VS debugger (maybe), even if they are generally more complex and difficult to use (actually maybe because of that).
That does look at first glance like an infinite recursion, you could try putting a breakpoint at the line before the one that terminates the process. Does it get there ok? If it does, you've got two fairly easy ways to go.
Either you just step forward and see which destructors get called and when it gets caught up. Or you could put a printf/OutputDebugString in every relevant objects destructor (ONly ones which are globals should need this). If the message is the first thing the destructor does, then the last message you see is from the destructor which hangs things up.
On the other hand, if it doesn't get to that breakpoint I originally mentioned, then can do something similar, but it will be more annoying since the program is still "doing stuff".
I wouldn't rule out there being such a handler in Windows, but I've never heard of it.
I think the traceback that you're showing may be bogus. If you broke into the process after some kind of corruption had already occurred, then the traceback isn't necessarily valid. However, if you're lucky the bottom of the stack trace still has some clues about what's going on.
Try putting Sleep() calls into selected functions in your source that might be involved in the recursion. That should give you a better chance of breaking into the process before the stack has completely overflowed.
I agree with Dan Breslau. Your stack is bogus. may be simply because you don't have the right symbols, though.
If a program simply disappears without the WER handling kicking in, it's usually an out of memory condition. Have you gone investigated that possibility ?

Debugging a crash after exiting? (After main returned)

This is a fairly involved bug, and I've tried looking around to find other sources of help, but for reasons I don't understand, "Program Crashes in Vista" is not the most helpful query.
The issue I'm having is that the program I'm working on - a graphical, multithreaded data visualization software that uses OpenGL and the Windows API - is crashing after WinMain() returns. I've tried stepping through the shutdown routine as well as looking at a stack trace, and the last bit of code that's not assembly is _crtExitProcess, where it crashes in the actual ExitProcess(0) call. After that, the stack trace shows kernel32.dll and four ntdll.dll, which is where it actually crashes.
This bug only occurs on Vista, and the same exact code when run on XP exits normally. I really can't think of anything that would help me debug this problem, and debugging this issue is something I've never really learned. Any help would be appreciated.
I've done a little digging around, and I've found a couple of posts around that suggest you're not the only one suffering from this:
http://developer.nvidia.com/forums/index.php?showtopic=318
http://objectmix.com/xml-soap/115379-problem-latest-ms-patches-msxml4-vista.html
Particularly, the second one is of interest, where Tom Chm mentions:
We believe we have identified the root
cause of our crash, and adding a
virtual destructor to our interface
class wrapper seems to resolve our
problem. But we would like to know the
exact cause of the crash to verify
that we didn't just sweep the actual
problem under the rug.
The problem may be with a destructor somewhere, or lack thereof. If you have a way of attaching a debugger and stepping through the shutdown process, it might be of help.
You might want to read through the whole thread and see if there's something you can learn. That is, if you haven't already found these posts in your searching, of course.
Sounds a little like a problem with a destructor.
Check for objects that are destroyed on shutdown. This will mainly be global or static objects. Look carefully at their destructors for a case of accessing something that is no longer valid. In a multi-threaded environment, it might be a race condition, where an object is destroyed while another thread is still using it.
Try writing a log as objects are destroyed. e.g.
SomeClass::~SomeClass()
{
WriteLog("Begin ~SomeClass()");
// do whatever
WriteLog("End ~SomeClass()");
}
WriteLog() should open the log file, write and then close the file to make sure the file is flushed. Using a Mutex or CriticalSection to avoid conflicts would be a good idea.
Looking at the log after a crash might give you some clues as to what is going on.