Posts

Showing posts from 2010

memory leak detection notes (continuously updating)

Memory leak problem is very common, below is some my previous working notes: BoundsCheck BoundsCheck does not work well with mixed codes. Since my latest projects are almost all mixed, so, seldom used in my daily work. Visual studio Enable memory leak reporting There are two ways to enable memory leak check in VC, one is to define DEBUG_NEW macro, another is as below: 1: #define _CRTDBG_MAP_ALLOC 2: #include<stdlib.h> 3: #include<crtdbg.h> Then calling _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); when initializing your app. With the above changes, visual studio can dump memory block leak when quitting or between two snapshot via Windows API. For instance: c:\program files(x86)\microsoft visual studio\vc98\include\crtdbg.h(552) : {43} normal block at 0x00441C20, 40 bytes long. Data: < C > 08 02 43 00 16 00 00 00 00 00 00 00 00 00 00 00 Output mode The above output is one sample of block leak, in which, {43} is the heap block a...

c++/CLR/SEH/MFC/VEH exception notes (continuously updating)

SEH/VEH A new interesting topic is VEH (vector exception handler), which is introduced since windows XP. The difference is as below: Not like SEH, which is saved in the TEB, is popped as stack unwinds and only valid in the current thread; VEH is saved in the global heap, which is effective for the whole process; All VEH will be executed before SEH VEH only exists in the user-mode codes, SEH can be both user/kernel modes SEH is registered/revoked by the codes generated by compiler, VEH is registered/revoked by system API: AddVectoredExceptionhandler RemoveVectoredExceptionHandler The signature for VEH is: LONG CALLBACK VectorHandler(PEXCEPTION_POINTERS ExceptionInfo) C++/CLR/SEH exception relationship SEH exception means structured exception handler, CLR exception and C++ exception are two special SEH one, each has its own SEH code. C++ exception code is: 0xe06d7363 and CLR is 0xe0434f4d. C++ exception keywords are try/catch, SEH is __try/__except, MFC is the TRY/CATC...

Assembly loading strategy misc notes (continuously updated)

  Load from GAC Load from private path 1: < runtime > 2: < assemblyBinding xmlns ="urn:schemas-microsoft-com:asm.v1" > 3: < probing privatePath ="myPrivatePath" /> 4: </ assemblyBinding > 5: </ runtime > Change machine.config to load from anywhere globally on your machine Overwrite private path setting 1: < runtime > 2: < assemblyBinding xmlns ="urn:schemas-microsoft-com:asm.v1" > 3: < probing privatePath ="myPrivate" /> 4: < dependentAssembly > 5: < assemblyIdentity name ="MyAssemblyPath" 6: publicKeyToken ="abcd" 7: culture ="neutral" /> 8: < codebase href = "file://localhost/D:/Temp/DLL/MyAssembly.dll" > 9: <!--Redirection and codeBase policy for myAssembly.--> 10: </ dep...

CLR Exception Misc Notes(continuously updated)

  Different unhandled exception for WinForm and Console (from debugging .net app 2.0) for winform, if unhandled exception thrown from pool thread/background thread/ finalize thread, AppDomain.UnhandledException event will be called. For Console, main thread still runs, just as if you have handled them Unhandled exception dialogs shows while your app still running so, you app’s state may be changed, you cannot get the image when the exception is thrown, until you set external debugger to auto attach when it happens.    

Rebase your dlls to get more compact address space

  Generally, each dll loaded has a preferable starting address, which is determined by the compiler, by default, assigned by name. During the loading, if conflict occurs, loader will relocate them. So, if too many conflicts happens, it may cause starting performance problem.   In one of our product, we are using a bunch of 3rd binary packages from one company, the names follow the pattern “FO***”, for most of client machines, they seem to be the only libraries to be loaded into address space starting with that name. After watching the run-time address space of our distributed program, it seems that the compiler is not allocating compact enough address policy, there are several mega free spaces between two adjacent libraries. Since our product is memory extensive one, I manually rebased those dlls and it seems that dozens of 10M memory can be grouped into one 150M memory finally. So, some operations which caused out-of-memory exceptions now can work well. The basic step is ...

WinDbg debugging scenario (2) find clr gchandle leak

  !gchandleleak can search heap to get referenced handles, may have false positive. But if the number keeps increasing after each specific operation, then it may cause handle leaks. !do poi(handleValue) to see what is contained by the handle.   For most cases, PowerDbg can be used to automatically check the leakages.

Windbg Debugging Scenario (1): Finding un-disposed objects

  Use !finalizequeue to find all disposible objects, then use !gcroot to check whether they are orphan, then dump the orphaned objects, in most case, developers will define some private flags like _IsDisposed or _IsClosed, if already orphaned, should be true.   generally, the steps can be completed by PowerDbg scripts.

Windbg Debugging Misc Tips (Continuously Updating)

  Native .prefer_dml 1: a hidden command, enable marking language, showing hyperlinks in some commands, like lm, etc .exr -1 show last exception, for both native or managed “.symopt+0x40”:force debugger to load unmatched symbol files, like time-stamp mis-match. To disable, –0x40 .ocommand: execute command from the target trace, .command “Sa Windbg Cmd:” then, in the target program, debug output can be written: Trace.WriteLine(“sa Windbg Cmd: !mk;g;”); Managed Threads/Callstack/Frame !mk show both managed/native callstack !mframe/!mdv switch to managed frame or show variables for some frame, get frame index from !mk Exception/Breakpoints debug CLR start-up code: bu mscorwks!EEStartup “gu;.loadby sos mscorwks” !pe display exception object or most recent exception if no argument !soe –derived | –create | –create2 <typeName> [pseudo-register number for results] e.g, !soe –create System.OutOfMemoryException 1 !soe System.OutOfMemoryExcep...

VS Tips (Continuously updated)

Image
Special commands in Immediate/Watch windows c# temp variables defined in Immediate Window input “int tempVar = 0;” in the immediate window, then type $temp or @temp in Watch window, see what happens. Can be helpful combined with the usage of Conditional Breakpoints. VS can even create an object in immediate window, like Something s = new Something(); Time-measurement feature by conditional breakpoint set a trace point, and change the statement as below: {@clk }, {@clk=0 }, $FUNCTION on my 64-bit win7, time resolution is 10-6 second see what happens control var’s display suffix var,h: in watch window shows hex value var,nq: show string without escaped quotes, helpful when showing “\”” var,ac: force to evaluate the expression even if “implicit expression evaluation” is disabled in debug-general setting. May be helpful to watch some variables which has nasty side effect when auto evaluate expression, like properties watch objects out of scope: “Make Object Id”, then...

PowerDbg: a great module to write windbg script

Last week during the trip in Las Vegas, I learned something about PowerDbg, a PowerShell module which can automate windbg debugging. It is really a exciting tool and just what I have been searching for a long time. During the debugging, we may wish to analyze elements in a big array one by one, but manually doing so is too troublesome, for instance, one of the element is not disposed or one of the element's flag is not set correctly. In this case, if a script can help us do it automatically, it would be great. PowerShell is microsoft's new shell replacing the old WSH. It is strong typed and based on .net framework, can access all .net framework. It can also be integrated with windbg: Windbg works as debugging server, PowerDbg as remoting host, sends debugging commands to windbg, retrieves output, parses them and continues analysis. One sample is like: http://www.leeholmes.com/blog/2009/01/21/scripting-windbg-with-powershell / PowerDbg can be downloaded from: http://powerdbg.cod...

"Server Busy" and AfxOleInit

Recently, we had one problem of showing "Server Busy" dialog during the long time WaitHandle.WaitOne waiting, kind of annoying. After research work, found the reason. Maybe it is by design of Microsoft, to provide opportunities for calls to a com thread which is already blocked by any wait or sleep functions to deal the situation correctly, like retry or cancel. While, this may not be expected as most users do. The work-around is simple, since AfxOleInit() register a COleMessageFilter internally, which calls CoRegisterMessageFilter. So, we can just register it again and calling EnableBusy and EnableBusyDialog(FALSE). Another solution is to call OleInitialize or CoInitializeEx with apartment thread model instead of AfxOleInit().

Program disappears when accessing 0 element in a empty vector

For some reason, some codes like below exist in our product: 1: try 2: { 3: std::vector< int > v; 4: int i = v[0]; 5: int * pTemp = NULL; 6: *pTemp = 0; 7: } 8: catch (...) 9: { 10: AfxMessageBox(L "haha" ); 11: } 12:   Under VS2005, the above code can show message, but under 2008, it just disappears silently. Checking system event log can find some exception with code 0xc0000417. But the exception could not be caught, since it is the crt's invalid_parameter_info handler, internally, _invoke_watson is called and it unregister all existing unhandled exception handlers, then it terminates the process. (can be found under crt's code: "invarg.c). So, we have no change to catch this exception. If wishing to catch such error, we can set: 1: void myInvalidParameterHandler( const wchar_t * expression, 2: const wchar_t * function, 3: const wchar_t * file, 4: unsigned int line, ...

Can reference guarantee non-empty input?

Previously, when discussing the difference between pointer and reference, one may say that the argument passed as reference can guarantee non-empty input. We may just simply take it for granted, but it does not hold for all cases. For instance, 1: class TempClass 2: { 3: public : 4: int member; 5: }; 6:   7: void TestFunction(TempClass& input) 8: { 9: TempClass* pInput = &input; 10: if (pInput == NULL) 11: throw ; 12: int value = input.member; 13: } 14:   15: TempClass* p = NULL; 16: TestFunction(*p); 17:   What happens for the above code? The "input" is a null-reference. After reading c++ standard, it can be found that dereferencing a null pointer has undefined behavior, so, the above code has broken c++ standard already and is not suggested to use. "[Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference w...

BoundsCheck not working with mixed codes

Previously, we have tried to use BoundsChecker to test our mixed programs. But it does not support managed code and also cause huge memory usage during running, Recently, I tried "Application Verifier", a great tool distributed by Microsoft, can be used alone or together with Visual studio team version, and it seems to be acceptable. The below code can be found immediately: 1: int * p = new int [10]; 2: p[11]=1; // this cannot be detected, since the heap block has additional 8-bytes suffix, it seems that AppVerif does not check with this 3: p[100] = 1; // this can be detected immediately, since AppVerif generates memory fence after the heap block. After running with Application Verifier, the memory usage is also acceptable. Another thing related to this is that AppVerif can only work with native codes. As for the mixed code, msdn does not say clearly. Two potential results can be: 1: AppVerif can only check native memory, ignore managed objects. 2: AppV...

unexpected WM_PAINT message reentry when waiting for COM request under Vista/7

Recently, we had a weird problem: when CLR is waiting for the COM request result, especially a remoting one, the WM_PAINT message can be processed before it returns. We are waiting the COM request in rendering thread, and assumes that the code should be blocked and does not consider reenter problem. This really cause lots of trouble. When the problem happened, the callstack trace looks like below:   1: UIFramework.dll!UIFramework.MainForm.viewport_Paint 2: System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.WndProc(ref System.Windows.Forms.Message m) + 0x31 bytes 3: System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DebuggableCallback(System.IntPtr hWnd, int msg = 15, System.IntPtr wparam, System.IntPtr lparam) + 0x57 bytes 4: ... 5: user32.dll!_DispatchMessageW@4() + 0xf bytes 6: ole32.dll!CCliModalLoop::HandleWakeForMsg() + 0x48c30 bytes 7: ole32.dll!CCliModalLoop::BlockFn() - 0x5df7 bytes 8: ole32...