Debugging workflow aspects of Visual Studio development vs. "Linux" development? - c++

OK, so there are numerous questions around, asking for a "Visual Studio equivalent on Linux" or a variation of this question. (here, here, here, ...)
I would like to focus on one aspect and ask how the debugging workflow possibly differs on different systems, specifically the full-integrated-IDE approach used by Visual Studio (like) systems and a possibly more "separate" toolchain oriented approach.
To this end, let me present what I consider a short description of the "Visual Studio Debugging Workflow":
Given an existing project
I open up the project (one single step from a user perspective)
I navigate to the code I want to debug (possibly by searching of my project files, which is simply done by opening the Find in Files dialog box.)
I put a breakpoint at line (a), simply by putting the cursor on the line and hitting F9
I put a "tracepoint" at line (b), by adding a breakpoint there and then changing the breakpoint properties so that the debugger doesn't stop, but instead traces the value of a local variable.
I hit F5, which automatically compiles my executable, starts it under the debugger and then I wait until the prg stops at (a), meanwhile monitoring the trace window for output of (b)
When the debugger finally stops at (a), my screen automatically shows me the following information in (one-time preconfigured windows) side-by-side at the same time:
Current call stack
values of the most recently changed local variables
loaded modules (DLLs)
a list of all active breakpoints with their locations
a watch window with the last watch expressions I entered
A memory window to examine raw memory contents
a small window displaying current register values
Plus/minus some features, this is what I would expect under Eclipse/CDT under Linux also.
How would this workflow and presented information be retrieved when developing with VIM, Emacs, gdb/DDD and the likes?
This question isn't really about if some tool has one feature or not, it's about seeing that development/debugging work is using a combination of features and having a multitude of options available at your fingertips and how you access this information when not using a fully integrated IDE.

I think your answer isn't just about which software you use, but also what methodology you use. I use Emacs and depends on TDD for most of my debugging. When I see something fail, I usually write tests filling in the gap which I (obviously) have missed, and checks every expectation that way. So it goes far between each time I use the debugger.
When I do run into problems I have several options. In some cases I use valgrind first, it can tell me if there is some memory related problems right away, eliminating the need for the debugger. It will point straight to the line where i overwrite or delete memory that should be left alone. If I suspect a race condition valgrind is pretty good at that to.
When I use the debugger I often use it right in emacs, through GUD mode. It will give me a view with stack, local variables, the source code, breakpoints and a window where I can command the debugger. It usually involves setting a couple of breakpoints, watching some memory or some evaluation, and stepping through the code. It is pretty much like using the debugger in an IDE. The GDB debugger is a powerful beast, but my problems has never been large enough to need to invoke its power.

Related

How to write loggings to the Visual Studio output window?

I'd like to extend my application with a kind of logging, where one can choose to log to a file and/or to log to the "Visual Studio" "output" window.
For the latter, it seems that the function OutputDebugString() is doing the trick, but only for "Debug" builds, and I'd wish to have this also for "Release" builds, so I came up with the idea of using tracepoints (at least, I think that tracepoints are also writing to the "output" window for "release" builds), but here I have a rather frustrating problem:
Tracepoints are a special kind of breakpoints and seem to be written to *.suo files, being present in <project directory>\.vs\<project name>\v15 directory (see Where are Visual Studio breakpoints saved?., thank you, Max).
My idea was to write a postbuild event, adding a tracepoint to every line in the *.suo file where a log() operation was called.
This, however, is not possible, for the simple reason that the *.suo files are binary :-(
Does anybody know of another way to add tracepoints to an application at build-time or how to write (with a "Debug"/"Release" switch) to the "output" window of Visual Studio?
Thanks in advance
OutputDebugString() should work in Release builds - if there is anything to consume the output (such as WinDbg.) Debugging Tools for Windows (WinDbg, KD, CDB, NTSD)
As to why it's not - probably want to look into that, as it's possible your application isn't building quite the way you expect otherwise.
As I understand it, Tracepoints only work in a debugger (Debug or Release) - but the way I believe this works is, the debugger will, on application load/startup, (or during a run) actually replace instructions with a BRK and when the application triggers the break, the debugger catches it, substitutesthe original instruction back in, before performing whatever task it should (whether that be pause, increment a counter, etc.) - but I think Tracepoints will only work with an attached debugger, as otherwise there's nothing to perform the replace, catch and substitute operations, and the code runs uninterrupted.
However, if I read your intentions correctly, you might actually want to use something like Event Tracing* instead. This should output what you want to see to a standard windows log file, will work in debug or release, inside or outside of a debugger. However it won't output to the VS output window. For that, OutputDebugString() should the be correct operation.
*Disclaimer - not used them myself, as we use VS output and WinDbg for now - but it looks like a better way for deployed applications, going forwards.

Bizarre behavior with Visual Studio's debugger; "The network location cannot be reached" (ERROR_NETWORK_UNREACHABLE)

I've experienced this with every version of Visual Studio starting from 2012 (2012, 2013, 2015 Preview), on multiple computers and multiple projects, but I haven't figured out how to fix it:
Whenever I'm debugging a 64-bit(?) C++ console program, after a few minutes and seemingly completely randomly (when I'm not clicking or typing anything), the console window for the program spontaneously closes and I can no longer debug or step through the program with Visual Studio. When I press Stop and attempt to restart debugging, I usually get ERROR_NETWORK_UNREACHABLE:
// MessageId: ERROR_NETWORK_UNREACHABLE
// MessageText:
// The network location cannot be reached. For information about network troubleshooting, see Windows Help.
#define ERROR_NETWORK_UNREACHABLE 1231L
If I try to attach to the process manually I get the error:
Unable to attach to the process.
The only fix I've found for this is to restart Visual Studio. I can't find any other way to fix it, and I've tried running Process Monitor but haven't found anything.
What causes this problem and how can I fix it?
(?) Upon further checking it seems that this only happens in 64-bit mode, but I'm not 100% sure.
Ok, this is just so wrong
I also have issues with this bug, and in my case it occurred every other debug session. Which meant debug -> stop -> debug -> bug -> restart visual studio -> go to start (repeat every minute during the whole day).
Needless to say I was driven to find a solution. So yesterday I tried procmon, spend hours looking at API monitor differences, looked at plugins, netstat, etc, etc, etc. And found nothing. I gave up.
Today
Until today.
To track down a stupid bug in my program today, I launched appverifier. For my application, I ran the 'basics' tests and clicked save. After a few hours this led me to the bug in my program, which was something like this (extremely simplified version):
void* dst = _aligned_malloc(4096, 32);
memcpy(dst, src, 8192);
Obviously this is a bug and obviously it needed fixing. I noticed the error after putting a breakpoint on the memcpy line, which was not executed.
After a stop and 'debug' again I was surprised to find that I could actually debug the program for the second time. And now, several hours later, this annoying bug here hasn't re-emerged.
So what appears to be going on
So... apparently data from my program is bleeding through into the data or execution space of the debugger, which in turn appears to generate the bug.
I see you thinking: No, this shouldn't happen... you're right; but apparently it does.
So how to fix it? Basically fixing your program (more particular: heap corruption issues) seems to make the VS debugger bug go away. Using appverifier.exe (It's in Debugging tools for Windows) will give you a head start.
Why this works
Since VS2012, VC++ uses a different way to manage the heap. Hans Passant explains it here: Does msvcrt uses a different heap for allocations since (vs2012/2010/2013) .
What basically happens is that heap corruption will break your debugger. The AppVerifier basic settings will ensure that a breakpoint is triggered just before the application does something to corrupt the heap.
So, what happens now is that before the process will break the heap, a breakpoint will trigger instead, which usually means you will terminate the process. The net effect is that the heap will still be in-tact before you terminate your program, which means that your debugger will still function.
"Test"
Before using appverifier -- bug triggered every 2 minutes
While using appverifier -- VS debugger has been stable for 5 days (and counting)
This is an environmental problem of course. Always hard to troubleshoot, SysInternals' utilities like Process Monitor and Process Explorer are your primary weapons of choice. Some non-intuitive ways that a network error can be generated while debugging:
Starting with VS2012, the C runtime library had a pretty drastic modification that can cause very hard to diagnose mis-behavior if your program corrupts the heap. Much like #atlaste describes. Since time memorial, the CRT always created its own heap, underlying call was HeapCreate(). No more, it now uses GetProcessHeap(). This is very convenient, much easier now to deal with DLLs that were built with /MT. But with a pretty sharp edge, you can now easily corrupt the memory owned by Microsoft code. Not strongly indicated if you can't reattach a 64-bit program, you'd have to kill msvsmon.exe to clear up the corruption.
The Microsoft Symbol Server supplies PDBs for Microsoft executables. They normally have their source+line-number info stripped, but not all of them. Notably not for the CRT for example. Those PDBs were built on a build server owned by DevDiv in Redmond that had the source code on the F: drive. A few around that were built from the E: drive, Patterns+Practices uses that (unlikely in a C++ program). Your debugger will go look there to try to find source code. That usually ends well, it gives up quickly, but not if your machine uses those drive letters as well. Diagnose by clearing the symbol cache and disabling the symbol server with Tools + Options, Debugging, Symbols.
The winapi suffers from two nasty viral infections it inherited from another OS that add global state to any process. The PATH environmental variable and the default working directory. Use Control Panel + System + Advanced + Environment to have a look at PATH, copy/paste the content of the intentionally small textboxes into a text editor. Make sure it is squeaky clean, some paralysis at the usual mess is normal btw. Take no prisoners. Having trouble with the default directory is much harder to troubleshoot. Both should pop out when you use Process Monitor.
No slamdunk explanations, it is a tough problem, but dark corners you can look in.
I have the same problem. Thought it was related to 64 bit console apps, where it is very easily triggered with almost any debug session. But, it also happens on 64 bit windows apps too. Now I am seeing it on 32 bit windows apps. I am running Windows 8.1 pro on a single desktop with the latest version of vs 2013 and no remote debugging. My (added) extensions are Visual Assist, Advanced Installer, ClangFormat, Code Alignment, Code Compare, Duplicate Selection, Productivity Power Tools 2013, and Visual SVN.
I discovered that the "Visual Studio 2013\Settings\CurrentSettings.vssettings" file gets corrupted. You can delete this file and recreate it by restarting VS or you can try to edit the XML. I then keep a copy of a good settings file that I use to replace when it gets corrupted again.
In my case, the corrupted line begins with
</ToolsOptionsSubCategory><ToolsOptionsSubCategory name="XAML" RegisteredName="XAML"
... and it is extremely long (I think this is why it is prone to corruption).
I just disabled in the Menu
Tools > Options
Debugging > Edit and Continue
Native-only options > Enable native Edit and Continue
and now it does not give the that stupid error which was preventing the starting of the debuggee application.
I also had the same problem with VS2015. It was so frustrating that a simple Hello World program gave this error when I ran debugger for the second time. Tried uninstall and reinstall and didn't work.
Finally, the solution mentioned in https://social.msdn.microsoft.com/Forums/vstudio/en-US/8dce0952-234f-4c18-a71a-1d614b44f256/visual-studios-2012-cannot-findlaunch-project-exe?forum=vsdebug
worked. Reset all visual studio settings using Tools->Import and Export settings. Now the issue is not occurring.

Getting debug output from a crashed VS2010 application

Question: Can I set up VS2010 so it automatically writes debug output to a file?
Motivation: I have a DirectX 9 application that I'm trying to debug. I've noticed that when my application is fullscreen, it may crash under certain conditions. Normally I would just check my logs or DirectX debug output. However, the way my program crashes prevents that. It freezes and does not respond to any my attempts to end it (including "End Process" from task manager). Moreover, it also freezes my VS2010, and so VS doesn't respond to any commands either. The only way out of this whole thing that I've found is to End VS process. This, however, also destroys the output I'd very much like to read.
Now I see two ways out of this. First is to write all the debug info to a file but I have no idea how to do it. Second is to make my application crash in a more friendly way, but this seems like a difficult task.
Probably MiniDumpWriteMiniDump(..) helps on this. You can at any time dump the current state of the process to a file. After that, you can open the dumps with Visual Studio and analyze the state of the process - this includes callstacks of every thread, variable values...
Try to identify conditions in which your process crashes and write one or more dumps.
Another try is to install the Windows Debugging Tools and use WinDbg to debug your application. This is not as comfortable as Visual Studio, but allows a deeper insight.
Edit:
If there are debug statements made with OutputDebugString(..), you can use DebugView (from Microsoft, earlier Sysinternals) to display it.

Visual Studio application running extremely slow with debug

I have a native C++ program which runs more than 20 times slower when started with Debug (F5), but runs at normal speed when using start without debug (Ctrl + F5).
It does not matter whether I use a debug or release build. Also if I use WinDbg the program is a magnitude slower.
Is there some setting I did choose wrong or something?
Set the _NO_DEBUG_HEAP environment variable to 1 (as seen on http://preshing.com/20110717/the-windows-heap-is-slow-when-launched-from-the-debugger).
This can be done from inside Visual Studio, too.
Now this is just a workaround, and I'm curious to know how to refactor a program which suffers from this kind of problem. Do you have many std::map's, shared_ptr, or any other big indirections by any chance?
This is of course not caused by having the _DEBUG symbol defined or compiling the code in the debug configuration. The added debugging code runs whether or not the debugger is attached to the program.
The debugger doesn't normally affect code execution, it stays out of the way by calling WaitForDebugEvent. Which blocks it, until the operating system tells it that something noteworthy happened. That can trigger a bunch of code in the debugger that can slow down your program. You can see the events listed in the DEBUG_EVENT structure documentation.
Annotating them a bit beyond the documentation: the debugger steps in and can slow down your program when:
The program loads or unloads a DLL. Lots of stuff happens during load, the debugger goes hunting for a debug symbol file (.pdb). It may contact a symbol server to download it. Any breakpoints that were set in the DLL source code will get activated. This can be quite slow, but the effect is temporary and generally only slows down the startup. You can see the load/unload notification in the Output window.
The program raises an exception. This activates the debugger at the moment the exception is raised, a "first chance notification". Which can be very helpful, you can use the Debug + Exception, Thrown checkbox to make the debugger stop when the exception is raised. You can see the notification message in the Output window. This does slow down code that raises and catches exceptions tremendously and is quite likely the source of your slowdown. Never use exceptions for flow control.
A thread starts running or terminates. Again, a notification message is printed to the Output window. You'd have to create a lot of threads to make this slow down your program.
When your program uses OutputDebugString() for tracing purposes. Visible in the Output window. Another good candidate for a slow down, output falls in the bit bucket if no debugger is attached. You shouldn't have any trouble diagnosing this as the cause, the obvious side-effect is seeing a lot of messages in the Output window.
When the program hits a breakpoint. Not a lot of reasons to be stumped by that one. But you can set breakpoints that slow down the program a lot yet don't cause a debugger break. Particularly the Conditional breakpoint, Hit counter, Filter and the When Hit operation will be slow. Use Debug + Windows + Breakpoints to review the breakpoints that are defined.
When a process is created under the debugger, the operating system by default uses the debug heap. The debug heap does more verification of your memory, especially at de-alloc.
There are several possible options in order to disable the use of the Debug Heap:
Attach to the process soon after startup. This will allow you to speed up performance in debug mode knowingly so and being fully aware of the mode in which you are running.
Add the environment variable setting _NO_DEBUG_HEAP=1.
This can be set either globally for the machine or for a specific instance of Visual Studio.
a. Globally you would set an environment variable through the Control Panel → System → Advanced system settings → Environment Variables, and there add the variable _NO_DEBUG_HEAP=1.
Note: This will have an affect on EVERY application you debug.
b. For an instance of Visual Studio you can open a command prompt, setting the environment variable _NO_DEBUG_HEAP=1 and then open visual studio from inside that command prompt. This will influence only the processes created from
that instance of Visual Studio will inherit the environment
variable.
Append the behavior of the debugger, this is possible for VS2015. There are 2 ways to override this:
a. To modify for a specific project, go to the project properties Configuration Properties → Debugging and change the Environment property _NO_DEBUG_HEAP to 1
b. To modify for every project in Visual Studio, go to Tools → Options → Debugging and check the option: “Enable Windows debug heap allocator (Native only)”.
Note: f the _NO_DEBUG_HEAP environment variable mentioned in the 'a' is set in a project level it will override this global setting.
For me the difference in performance between debug mode and release mode is about a factor 40. After some digging, it appears several things contribute to the difference in performance, but there is one compiler option that quadruples my debug performance almost for free.
Namely, changing /ZI into /Zi. For a description, see the MSDN page.
I don't use the edit and continue feature anyway.
No one has mentioned closing unused source windows.
After closing 20+ unused windows, debug source stepping went from ~5s back down to ~.2s. This unusually slow project loads a DLL dynamically and that DLL was also the one being stepped through (and having source windows open) so it seems likely related. However this was C# (headline and tags are non-specific).
There are several things that are different if you run the debug build outside the IDE. One is that the IDE takes a while to load symbols, and if you depend on a lot of libraries then that startup time can be significant.
If you are using a symbol server (including the Microsoft public symbol server) then this may add to the startup time, so ensure you have a local symbol cache in your _NT_SYMBOL_PATH variable if that is the case.
Also the IDE runs with the debug heap enabled, but I don't think this happens if you run outside the IDE.
Debugging Visual C++ comes with lots and lots of overhead, especially in the STL. Try not defining _DEBUG, and define NDEBUG.

Saving debugging state and backwards debugging with Xcode or friends

I am using Xcode in order to debug C++ programs. The main problem for me is that it takes around 10 munutes till the program gets to the point of the program that I need to debug. Then I realize about something inspecting the variables and some other stuff, and modify the code. Then 15 minutes again and so ...
I wonder if there is possible in some way in Xcode or in another IDE or compiler/debugger for C++, to "save" in some way a desired debugging state of the program. So if my compouter crashes or I modify the code and make some mistakes, one can open this saved state instantly and get fast to the point where one left before.
I also wonder if at this moment Xcode can "backwards debugging". GDB can for sure, as for september 2009. Or what do you think is the best IDE to do this.
Thanks a lot
GDB has "backwards debugging" (or more correctly "Reverse Debugging") for a limited number of platforms (list of native supported ones):
i386-linux
amd64-linux
moxie-elf ( http://moxielogic.org/blog/ )
So it is impossible for now to use this functionality on Mac OS X, with Xcode or without it.
Saving of program state in offline is very hard task. It is almost impossible to restore state of file descriptors, network connections, memory state (randomization of layout), even pid.
Such task is related to "Live migration" problem in openvz.
"Edit and Continue" feature from MSVS allow you to continue running after breakpoint with new version of code. It is supported for C#, C++ and Basic.
http://msdn.microsoft.com/en-us/library/esaeyddf(VS.80).aspx