How to execute GetLastError() while debugging in Visual Studio - visual-studio

You're stepping through C/C++ code and have just called a Win32 API that has failed (typically by returning some unhelpful generic error code, like 0). Your code doesn't make a subsequent GetLastError() call whose return value you could inspect for further error information.
How can you get the error value without recompiling and reproducing the failure? Entering "GetLastError()" in the Watch window doesn't work ("syntax error").

As mentioned a couple times, the #err pseudo-register will show the last error value, and #err,hr will show the error as a string (if it can).
According to Andy Pennell, a member of the Visual Studio team, starting with VS 7 (Visual Studio .NET 2002), using the '#' character to indicate pseudo-registers is deprecated - they prefer to use '$' (as in $err,hr). Both $ and # are supported for the time being.
You can also use the $err pseudo-register in a conditional breakpoint; so you can break on a line of code only if the last error is non-zero. This can be a very handy trick.
Some other pseudo registers that you may find handy (from John Robbins' outstanding book, "Debugging Applications for Microsoft .NET and Microsoft Windows"):
$tib - shows the thread information block
$clk - shows a clock count (useful for timing functions). To more easily use this, place a $clk watch then an additional $clk=0 watch. The second watch will clear the pseudo register after the display of the current value, so the next step or step over you do gives you the time for that action only. Note that this is a rough timing that includes a fair bit of debugger overhead, but it can still be very useful.

ERR,hr in a watch window usually does the trick

"edit and continue" add the code so you can see the error (just don't create a new global variable to store it). It works really well if you can quickly put a call to a pre-existing function that executes this kind of error handling code.
As a bonus, you can leave the new code there for the future too.
If you can't do this, then QBziZ is right "ERR,hr" does it.

Related

Where to get a full list of debugger variables?

I'm trying to set a tracepoint to print hit count in VS but I cannet find any sort of $NAME to use in print message dialog. I tried http://msdn.microsoft.com/en-us/library/vstudio/232dxah7(v=vs.100).aspx but I'm unable to find any link that describes every possible value I can output. Previously I used VB macro that I have written for this purpose, but unfortunately it runs too slow and can lead to very high delays that are unacceptable on my environment. Maybe somebody can point me to some article where I can pick enough of information?
MSDN states: You can include programmatic information in the message by using DebuggerDisplayAttribute syntax (see DebuggerDisplayAttribute). Here are a couple of examples
http://msdn.microsoft.com/en-us/library/5557y8b4.aspx
http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerdisplayattribute.aspx
Have a look at this Q&A:
What expressions are allowed in tracepoints?
Not exactly what you want but you can achieve this by declaring a variable in the Immediate window with execution stopped ie:
int hitCount;
Then in Breakpoint -> When Hit -> Print a Message enter:
Hit Count : {hitCount}

Visual Studio 2010 - Code flow visualiser

I would like to know if there is a tool which can help me in seeing which lines of code were executed within two break points.
Example: I have break points set at the beginning and end of a method. Now I want to see which are the lines of code that got called from within this method. Basically, the tool must do a recursive deep debugging and record the file name and line number.
Runtime Flow can show all function calls in a running .NET application, though it doesn't work with debugging - you need a separate application execution.

Edit assembly language code in Visual Studio while stepping through each statement

In Visual Studio, is it possible to edit assembly language code while stepping through each statement (so that statements in the program can be modified while the program is running?) It would be useful to modify statements in a program while the program is running (for debugging purposes), but I'm not sure if this is possible yet.
You can modify the source code, but it doesn't get reassembled to produce a new binary during your debugging session. The debugger will tell you the "source no longer matches the code" but you can still step. Your display may be confusing because, well, the source code no longer matches the object code :-} I often add comments to instructions or in blank lines, which gets me the complaint, but you can still single-step and see the right source lines in this special case.
I think you can manually modify the memory containing the instruction you want to patch. I've not ever bothered to do this; its easier to set a breakpoint where I'm at, re-assemble, and then run till the breakpoint.
You can modify all the registers and data memory pretty easily (actually you have to use this to modify the code memory, I think!).
A really useful thing to do is "Set Next Statement" to set the PC back to a somewhat earlier place in the code; you can often then step forward to point of failure, if the registers and memory aren't changed. (put cursor in your source or disassembly window, click on a line, then right-click "Set Next Statement")

Windows 7 task scheduler keeps returning operational code 2

I set up a scheduled task to run under my account. Everything it runs, even if it is successful, returns an operational code of (2). I looked this up this error code at the below link, and it claims it cannot find the specific file.
http://www.hiteksoftware.com/knowledge/articles/049.htm
Even if I do something very simple, I get back operational code of (2). For example:
run program: cmd.exe
start in path: c:\windows\system32
I start the task and I see the process running in my task manager, so I kill the task. I then check in the history of scheduled task and it shows up as (2).
Something more realistic of what I am doing:
<?
/* file in c:\php\test.php */
echo "hello";
?>
run program: php.exe
start in path: c:\php
arguments: -f test.php
Everything works in the command line, but Windows schedule task keeps returning operational code (2). I should be seeing an operational code of (0), which means successful, correct?
You may not have put a path in the "Start In (Optional) box of the Edit Action dialog box.
Even though you had a path on the program that was being executed, Windows 7 still wants you to tell it where to run the program.
TL/DR: Don't worry about it. This just means the task finished, but tells you nothing about whether it was successful or how it failed. Look at the "Last Run Result" for that information.
The question and the top answer are confusing the notion of a "return code", which shows up in Task Scheduler as the "Last Run Result" with the "OpCode"/"Operational Code" that shows up in the history of a task.
If I create a simple Python program that does nothing more than sys.exit(7), and run it via task scheduler, I get a Last Run Result of 0x7, and an opcode of 2. If I have it do nothing, or sys.exit(0), I get a Last Run Result of "The operation completed successfully (0x0)" and still an opcode of 2. In other words, the return code from the executed program determines the Last Run Result. The OpCode appears to be a constant 2. This also establishes that the opcode 2 is not related to the return code 2 that likely means the file's not found. We know the file was found as it executed, and returned different Last Run Results depending on the code contained.
Further, a Windows forum post points out that this history view is really coming out of the event log. Sure enough, I can find the same events in the event log (always with a value of 2). This means the definition of the OpCode is going to be the same as the definition used for events, and is less of a task scheduler concept than a Windows event concept.
What is an opcode for an event? I've struggled to get a clear answer, but as best I can tell, it appears it's ultimately controlled by the program writing to the event log. There's documentation around for defining opcodes in your program. In this case, the thing writing to the event log would be Task Scheduler itself or something else in Windows.
A final observation: If I go to the event viewer and look for Log: Microsoft-Windows-TaskScheduler/Operational, Source: Microsoft-Windows-TaskScheduler and Event ID: 102,201, add the column for Operational Code, and sort, I see it is always a 2. And events 100 and 200 are always a 1. This applies not just to my manual experiments, but also includes every other random program that's using scheduled tasks, e.g. Dropbox and Google updaters that are working as far as I know.
Put all this together and I would strongly bet that the events generated while starting up a scheduled task are hardcoded by Windows to use an opcode of 1 when writing to the event log, and the events generated while finishing a task (successful or not - which goes in the Last Run Result) are hardcoded by Windows to use an opcode of 2 when writing to the event log. This opcode appears to be a red herring that doesn't affect anything we need to worry about beyond curiosity.
I was striking out until I just deleted & re-created the scheduled task...now it works. Don't know why but there it is.
Okay I know I am late to the party here, but I think a lot of the problem stems from confusing the Operational Code with a Return Code. I'm not an expert in Windows programming or internals (I make a living using a Windows system to program, but my programming isn't for Windows systems).
If I understand correctly:
The Operational Code is set by what ever routine being run at whatever value the programmer decided to set it at.
The Return Code is indicative of success or failure.
Consider the following (edited) example from the history of one of my scheduled tasks:
Event 201, Task Category "Action completed" shows an Operational Code of (2).
Down below under the General tab, is the message:
Task Scheduler successfully completed task "\My_task" , instance "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" , action "C:.....\blahblah.exe" with return code 0.
There's the indication of success. A different return code would indicate a failure. The Operational Code of (2) merely indicates that the routine was finished (in this case) when reported. I don't believe there's any set values to be interpreted for the Operation Code.
I've been having a similar issue and found that in addition to what was suggested in both the accepted answer and its comments I had to do one other thing. I had to re-create the task and set its "configure for" to Windows Server 2003, Windows XP, or Windows 2000 I dont understand why, since its not for any of those OS' but after I did so my task actually worked.
If this runs, and works, yet you still get an error code try entering exit 0 at the end of your script.
It took me a lot of googling to find that so hopefully this is helpful to someone.
#ojchase is right.
Opcodes are attached to events by the event provider. An opcode defines a numeric value that identifies the activity or a point within an activity that the application was performing when it raised the event.
Opcode 1 means that, when producing the event, the application was in the start of an activity.
Opcode 2 means that, when producing the event, the app. was at the end of an activity.
So opcodes have little to do with success or failure.
Sources:
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.eventing.reader.standardeventopcode?view=net-5.0
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.eventing.reader.eventopcode?view=net-5.0

How can I force VB6 to enter the debugger from the execution of a program without a break point?

I'm trying to watch the execution of a VB6 app and I'm running into an issue because once I enter the debugger and then hit Continue, it no longer lets me step through the code until I hit another break point. I want to be able to execute a program without stepping through something until I hit a point where I want to watch it execute. Ideally this would be something to the effect of holding a key down while I pressed a button to 'step into' that function.
Thanks in advance!
[EDIT]: I'm aware that I can use break points to stop the execution. To be more clear, the problem is that I don't know where the execution is going to, so I can't set the break point there (because I don't know where there is). That's why I essentially want to be able to say, 'after this next thing that I do, break, no matter what'. It sounds like this functionality does not exist, but I'm still keeping my fingers crossed.
While the code is running, press ctrl+break (or the 'VCR pause' button in the IDE) then press F8 (or choose 'Step Into'from the Debug menu in the IDE) to continue running the app. The next action will cause execution to break.
Note that the which causes the break will not always be the one you hoped it would be. Particularly annoying is the _MouseOver event which prevents you from doing a mouse down or a timer firing quckier than you can perform your action. Some breaks may even be fatal as regards running your app e.g. where Windows messages have been hooked (subclassing). Also consider there may not be an event handler in code (yet) for your action where it can break. But usually this technique identifies where you should be setting your breakpoint.
There is a Stop statement available for use in VB6 that will drop to the debugger when the statement is executed from code running through the IDE. (Just be sure to remove the all of the Stop statements from the code when compiling a release build.)
There are several techniques you can use.
These two have been mentioned
Using F8 and Shift-F8 to step through the program
Adding Stops (and later removing)
Others
Use a global variable to create a collection. Use it as a stack and have the subroutines you are interested in push and and pop strings. Conversely don't pop anything and you will get a trace.
Use Watches to monitor and break at selection conditions. You can setup just about any condition to break.
Make a Global String and have your procedures set when you enter them. Monitor it through a Watch.
Use Debug.Print in your code. Also Unlike Stop you can leave these in without effecting the production code.
Use the File System Object to create a text file to act as a log.
Sometimes problem only occurs in the Complied version then you need to use MsgBox or log to a text file. MsgBox can alter the behavior of complex user interactions with forms.
These are all techniques I used in debugging an application. If I had to monitor an application I would use Debug.Print. If that doesn't do the trick compile then log to a text file.
If you have something really complex going on then I recommend moving all your code out of the events into classes implementing a Command Pattern. Your commands classes should interact with the form through and interface.
In the Execute method of the command classes you will something like
<save the current state>
<Do your original code>
<save the modified state>
<push the command onto a stack>
What will happen is that you wind up with a list of all the commands you have executed (even things like mouseover) with the state they encountered and the modified state. You can then examine each object in turn to see what is happening. This is nearly the equivalent of creating Undo/Redo
Note however things like MouseOver can push a lot of classes on the command stack so you will have to structure your tests carefully or be overloaded with information. Remember you can always skip pushing the command onto the stack.
The downside of using commands is that you gone beyond debugging into redesigning. You will to decide whether the problem is worth doing this.
You can press the F8 key to step through the code line by line. Alternatively, you can press SHIFT-F8 to step through line by line.
F8 will step you in to a function, where SHIFT-F8 will step you over the function. If you click on the DEBUG menu in the VB IDE, you will see other options too.
EDIT:
You can also put a permanent break point in your code by using:
Debug.Assert False
By doing it this way, the 'breakpoint' is saved in your code. When you compile the app, debug code is ignored.

Resources