How to put breakpoint in every function of .cpp file? - debugging

Is there a macro that does it? Which DTE objects to use?

(This is not quite what you're asking for, but almost:)
You can put a breakpoint on every member function of a class in Visual Studio by bringing up the New Breakpoint dialog and entering:
CMyClass::*
See http://blogs.msdn.com/b/habibh/archive/2009/09/10/class-breakpoint-how-to-set-a-breakpoint-on-a-c-class-in-the-visual-studio-debugger.aspx for more details.

Here's a quick implementation of 1800 INFORMATION's idea:
Sub TemporaryMacro()
DTE.ActiveDocument.Selection.StartOfDocument()
Dim returnValue As vsIncrementalSearchResult
While True
DTE.ActiveDocument.ActiveWindow.Object.ActivePane.IncrementalSearch.StartForward()
returnValue = DTE.ActiveDocument.ActiveWindow.Object.ActivePane.IncrementalSearch.AppendCharAndSearch(AscW("{"))
DTE.ActiveDocument.ActiveWindow.Object.ActivePane.IncrementalSearch.Exit()
If Not (returnValue = vsIncrementalSearchResult.vsIncrementalSearchResultFound) Then
Return
End If
DTE.ExecuteCommand("Debug.ToggleBreakpoint")
DTE.ExecuteCommand("Edit.GotoBrace")
DTE.ActiveDocument.Selection.CharRight()
End While
End Sub

I don't know what DTE functions to use, but you could very simply record a macro that could pretty much do it:
Go to the top of the file
ctrl - shift - R (start recording)
ctrl - I (incremental search)
{ (search for the first { character).
F9 (set breakpoint)
ctrl - ] (go to matching } character)
ctrl - shift - R (stop recording)
Now just run this over and over (ctrl - shift P repeatedly) until you reach the end of the file.
If you have namespaces, then change 4. to:
( (search for "(" at the start of the function definition)
esc (stop incremental search)
ctrl - I (incremental search again)
{ (start of function body)
This kind of thing can be infinitely modified to suit your codebase

Like Constantin's method... This seems like windbg territory.
Since you have the cpp, (even if you didn't you could script something to get by), it should be no problem to use logger part of the debugging tools for windows... it's a very handy tool, shame so few people use it.
logger debug's C/COM/C++ easily, with rich symbolic info, hooks/profiling/flexible instrumentation;
One way to activate Logger is to start CDB or WinDbg and attach to a user-mode target application as usual. Then, use the !logexts.logi or !logexts.loge extension command.
This will insert code at the current breakpoint that will jump off to a routine that loads and initializes Logexts.dll in the target application process. This is referred to as "injecting Logger into the target application."

Here's how something similar could be achieved in WinDbg:
bm mymodule!CSpam::*
This puts breakpoint in every method of class (or namespace) CSpam in module mymodule.
I'm still looking for anything close to this functionality in Visual Studio.

There is a macro, but I tested it only with c#.
Sub BreakAtEveryFunction()
For Each project In DTE.Solution.Projects
SetBreakpointOnEveryFunction(project)
Next project
End Sub
Sub SetBreakpointOnEveryFunction(ByVal project As Project)
Dim cm = project.CodeModel
' Look for all the namespaces and classes in the
' project.
Dim list As List(Of CodeFunction)
list = New List(Of CodeFunction)
Dim ce As CodeElement
For Each ce In cm.CodeElements
If (TypeOf ce Is CodeNamespace) Or (TypeOf ce Is CodeClass) Then
' Determine whether that namespace or class
' contains other classes.
GetClass(ce, list)
End If
Next
For Each cf As CodeFunction In list
DTE.Debugger.Breakpoints.Add(cf.FullName)
Next
End Sub
Sub GetClass(ByVal ct As CodeElement, ByRef list As List(Of CodeFunction))
' Determine whether there are nested namespaces or classes that
' might contain other classes.
Dim aspace As CodeNamespace
Dim ce As CodeElement
Dim cn As CodeNamespace
Dim cc As CodeClass
Dim elements As CodeElements
If (TypeOf ct Is CodeNamespace) Then
cn = CType(ct, CodeNamespace)
elements = cn.Members
Else
cc = CType(ct, CodeClass)
elements = cc.Members
End If
Try
For Each ce In elements
If (TypeOf ce Is CodeNamespace) Or (TypeOf ce Is CodeClass) Then
GetClass(ce, list)
End If
If (TypeOf ce Is CodeFunction) Then
list.Add(ce)
End If
Next
Catch
End Try
End Sub

Here's one way to do it (I warn you it is hacky):
EnvDTE.TextSelection textSelection = (EnvDTE.TextSelection)dte.ActiveWindow.Selection;
// I'm sure there's a better way to get the line count than this...
var lines = File.ReadAllLines(dte.ActiveDocument.FullName).Length;
var methods = new List<CodeElement>();
var oldLine = textSelection.AnchorPoint.Line;
var oldLineOffset = textSelection.AnchorPoint.LineCharOffset;
EnvDTE.CodeElement codeElement = null;
for (var i = 0; i < lines; i++)
{
try
{
textSelection.MoveToLineAndOffset(i, 1);
// I'm sure there's a better way to get a code element by point than this...
codeElement = textSelection.ActivePoint.CodeElement[vsCMElement.vsCMElementFunction];
if (codeElement != null)
{
if (!methods.Contains(codeElement))
{
methods.Add(codeElement);
}
}
}
catch
{
//MessageBox.Show("Add error handling here.");
}
}
// Restore cursor position
textSelection.MoveToLineAndOffset(oldLine, oldLineOffset);
// This could be in the for-loop above, but it's here instead just for
// clarity of the two separate jobs; find all methods, then add the
// breakpoints
foreach (var method in methods)
{
dte.Debugger.Breakpoints.Add(
Line: method.StartPoint.Line,
File: dte.ActiveDocument.FullName);
}

Put this at the top of the file:
#define WANT_BREAK_IN_EVERY_FUNCTION
#ifdef WANT_BREAK_IN_EVERY_FUNCTION
#define DEBUG_BREAK DebugBreak();
#else
#define DEBUG_BREAK
#endif
then insert DEBUG_BREAK in the beginning of every function, like this:
void function1()
{
DEBUG_BREAK
// the rest of the function
}
void function2()
{
DEBUG_BREAK
// the rest of the function
}
When you no longer want the debug breaks, comment the line
// #define WANT_BREAK_IN_EVERY_FUNCTION
at the top of the file.

Related

VB6 Subscript Out fo Range - but this is an odd one because a mirror function is working fine

Thanks for reading.
I have built a VB6 DLL (VB_InterFace just for a name) that talks to a C# DLL (C#_Driver just for a name) that talks to a Bluetooth Device.
The Demo VB6 test app (VB_Demo just for a name) I created as stage one works fine, does what it is supposed to. It calls the VB_Interface and Opens and Closes the BTDevice. Additional functions also work fine.
However on placing the operational code from VB_Interface into another DLL that is the live operations DLL, Open works fine, but Close is throwing an error. "Variable not defined" when returning from the C#_Driver.
I just can't see why, the code is the same, the process is only marginally different. By this I mean ;
In the VB_Demo I have two buttons "Open" "Close" and when I click on these I get the feedback that I expect from the BTDevice.
Private Sub btnOpenPort_Click()
'MsgBox steps(0)
ReDim steps(5)
Dim rc As HF4000_ResultCodes
'rc = driver.OpenSerial(cmbPorts.Text)
If driver.OpenSerial(cmbPorts.Text) = True Then
Private Sub btnClosePort_Click()
Dim rc As HF4000_ResultCodes
If driver.CloseSerial("COM4") = True Then
However in the live DLL it just executes the same functions internally without being initiated by a button click.
' See IScanDevice documentation.
' #see IScanDevice#OpenDevice
Private Function IScanDevice_OpenDevice() As Scanning.Scan_ResultCodes
(truncated slightly)
50 If driver.OpenSerial("COM4") = True Then
rc = READY
MsgBox "Connected to the device successfully."
' See IScanDevice documentation.
' #see IScanDevice#CloseDevice
Private Function IScanDevice_CloseDevice() As Scanning.Scan_ResultCodes
(truncated slightly)
50 If driver.CloseSerial("COM4") = True Then
60 rc = READY
70 IScanDevice_CloseDevice = Scan_Success
clsDriver.cls
Public Event OnStateChanged(newState As String)
Public Event OnDataUpdated()
Dim WithEvents CSharpInteropServiceEvents As CSharpInteropService.LibraryInvoke
Dim load As New LibraryInvoke
Private Sub Class_Initialize()
Set CSharpInteropServiceEvents = load
End Sub
Private Sub CSharpInteropServiceEvents_MessageEvent(ByVal newState As String)
If newState = "OpenForm1" Then
' FormDummy2.Show ' Not required
End If
If State <> newState Then
State = newState
RaiseEvent OnStateChanged(State)
GetDriverData
End If
End Sub
Private Function BluetoothTestInvoke(load, functionName, param)
BluetoothTestInvoke = load.GenericInvoke("BluetoothTest.dll", "BluetoothTest.Class1", functionName, param)
End Function
Function OpenSerial(portNumber) ' "COM4"
Dim param(0) As Variant
Dim retorno As Variant
param(0) = portNumber
retorno = BluetoothTestInvoke(load, "OpenSerial", param)
OpenSerial = retorno(0) <<<<<<< Works fine returns TRUE
End Function
Function CloseSerial(portNumber) ' "COM4"
Dim param(0) As Variant
Dim retorno As Variant
param(0) = portNumber
retorno = BluetoothTestInvoke(load, "CloseSerial", param)
CloseSerial = retorno(0) <<<<<<<<< "Error Subscript Out of Range"
End Function
What I have discovered is this - and I guess this is the reason why the Close is not working. The question is why is this situation occurring ...
When driver.OpenSerial executes, it hits > Function OpenSerial
Within Function OpenSerial it executes BluetoothTestInvoke where "load" is "CSharpInteropService.LibraryInvoke"
From there it moves to - Sub CSharpInteropServiceEvents_MessageEvent
.. and everything is fine.
However when I then execute driver.CloseSerial after that, it hits > Function CloseSerial
Within Function OpenSerial it executes BluetoothTestInvoke where "load" is "CSharpInteropService.LibraryInvoke"
Now here it "should" move to - Sub CSharpInteropServiceEvents_MessageEvent
However No, it just drops to the next line which is CloseSerial = retorno(0)
and this is where I get the "Subscript out of range" error for retorno(0)
For some reason in the CloseSerial it is not invoking "load"
BluetoothTestInvoke(load, "CloseSerial", param)
Thoughts and suggestions much appreciated.
UPDATE
Quite right, one should never assume anything.
On the tips I started digging deeper into the C# Library. It turns out the "param" value that is the Bluetooth port is passed into the CloseSerial call, and from there is is passed around within the external C# library dll. At one stage it is reset so the port number that should be handled is lost, thus it doesn't close but specifically the "expected" data was not returned to the calling app.
param(0) = portNumber
retorno = BluetoothTestInvoke(load, "CloseSerial", param) << param was being reset in the external library.

How to get if the drawing sketch is being edited? (Autodesk Inventor C++ API)

I need to add a drawing sketch in Inventor and edit it. However, if another sketch is already being edited, my program terminates and even try/catch does not help. I can't find a property of the sketch showing if it is being edited or not. My main part of code is here:
// All of these three functions pass try/catch perfectly. Program never terminates
Inventor::Application^ App = (Inventor::Application^)Marshal::GetActiveObject("Inventor.Application");
DrawingDocument^ Doc = (DrawingDocument^)App->ActiveDocument;
Sheet^ Sh = Doc->ActiveSheet;
DrawingSketch^ Sk;
try
{
Sh->Sketches->Add();
Sk = Sh->Sketches[Sh->Sketches->Count];
Sk->Edit(); // Crushes the program completely if another sketch is being edited
}
catch (...)
{
return;
}
I tried to cycle through all the sketches and close them all. This behaves in a way I cannot understand.
try
{
// Note: in Inventor indexes definitely start from 1
for (int i = 1; i <= Sh->Sketches->Count; i++)
{
Sk = Sh->Sketches[i];
Sk->ExitEdit();
}
}
catch (...)
{
return;
}
For example, when the sketch 2 is open, the first cycle (i = 1) that tries to close the sketch 1, somehow closes the sketch 2. And the second iteration (i = 2) that now cannot close the sketch 2, as it is already closed, calls 'catch' and further 'return'.
I'm not familiar with C++, but here is VBA sample how to detect the drawing sketch is in edit mode
Dim oDrawing As DrawingDocument
Set oDrawing = ThisApplication.ActiveDocument
Dim oSheet As Sheet
Set oSheet = oDrawing.ActiveSheet
Dim editedObject As Variant
Set editedObject = ThisApplication.ActiveEditObject
If editedObject.Type = ObjectTypeEnum.kDrawingSketchObject Then
Dim activeEditSketch As DrawingSketch
Set activeEditSketch = editedObject
activeEditSketch.ExitEdit
End If
Dim oSketch As DrawingSketch
Set oSketch = oSheet.Sketches.Add()
I hope, you can convert this code to C++

How to declare winposget object within visual basic

I have attempted to use an autoit object WinGetPos to handle a popup within a thread in a vb project, I would like WinGetPos function to return the x and y coordiantes of the specified popup and have used the below code, having first imported the AutoItX3.PowerShell.dll reference to my project. I am unable to generate any array could anyone suggest where I might be going wrong?
Imports AutoIt
Imports AutoItX3Lib
Private Declare Auto Function WinGetPos Lib "AutoItX3.PowerShell.dll" (ByVal mywindowtitle As String) As Array
Public Sub Main()
Dim PopUpThread As Thread = New Thread(AddressOf PopUpHandler)
With PopUpThread 'thread is looking for PopUp and press OK
.IsBackground = True
.Start()
End With
End Sub
Private Sub PopUpHandler()
Dim Ret As Integer
Dim myarray As Array
Do
Ret = FindWindow(vbNullString, "Choose File to Upload")
If Ret <> 0 Then
myarray = WinGetPos("Choose File to Upload")
MsgBox(UBound(myarray))
End If
Loop
End Sub
AutoItX is a well known and documented Programm. So why don't just look into the help file. There you will find how to use and WinGetPosX, WinGetPosY, WinGetPosHeight and WinGetPosWidth, but no WinGetPos. That may be the reason for your problem.

VBScript determine which function is running

Is it possible in VBScript to determine the name of the function currently executing?
In .NET, you could do:
MethodBase method = MethodBase.GetCurrentMethod();
Console.WriteLine(method.Name);
In the past, I build a callstack viewer to see the performance of each function that is called. This needs one extra line of VBS code per function/sub and some overhead during runtime of course because of the extra code.
bottom - up:
Function DoSomething(a, b, c)
dim registerFunctionObj : Set registerFunctionObj = [new RegisterFunction]("DoSomething")
' other code
End Function
Whenever the function is called, it creates a new instance of the RegisterFunction object. When the function exits, the registerFunctionObj variable goes out of scope automatically, calling the Class_Terminate sub of the instance.
[new RegisterFunction] is just a function that return a registerFunction instance:
Function [new RegisterFunction](funcName)
Set [new RegisterFunction] = new cls_RegisterFunction
[new RegisterFunction].FunctionName = funcName
Set [new RegisterFunction].CallStackViewer = CallStackViewer
End function
Class cls_RegisterFunction
Private functionName_, startTime_, callStackViewer_, endTime_
Private Sub Class_Initialize
startTime_ = now
callStackViewer_.LogInitialize me
End Sub
Public Property Let FunctionName(fName)
functionName_ = fName
End Property
Public Property Set CallStackViewer(byRef csv)
Set callStackViewer_ = csv
End Property
Private Sub Class_Terminate
endTime_ = now
callStackViewer_.LogTerminate me
End Sub
End Class
The CallStackViewer instance is a singleton instance of the a CallStackViewer class, but you can make it a part of your project, so you retrieve it through you global project class:
Private PRIV_callStackViewer
Public Function CallStackViewer()
If not IsObject(PRIV_callStackViewer) Then
Set PRIV_callStackViewer = new cls_CallStackViewer
End If
Set CallStackViewer = PRIV_callStackViewer
End Function
Class cls_CallStackViewer
Public Sub Class_Initialize
' Here you can retrieve all function libraries (as text file) extract the
' function name, the file they are in and the linenumber
' Put them in a dictionary or a custom object
End Sub
Public Sub LogInitialize(byref registerFunction)
' Here you can push the function on a stack (use a standard dotnet list>stack for it),
' log the starttime to a log object or handle custom breakpoints
End Sub
Public Sub LogTerminate(byref registerFunction)
' Here you can pop the function from a stack, log the endtime to a log
' object or handle custom breakpoints
End Sub
End Class
Disclaimer: The code in here is pure demo code created on the fly. It lacks functionality and is only here to explain the concept. It could contain errors and is not complete.
The only thing you need is one line of code per function and your own imagination to expand it.
No, but you can easily implement it
dim module_name
sub sub1
module_name = "sub1"
wscript.echo "i'm " & module_name
'do something
end sub
function function1
module_name = "function1"
wscript.echo "i'm " & module_name
function1 = "something"
end function
In case of recursion you could also remember the level you'r in so that you can get out if getting too deep.

Hotkeys for Previous and Next call stack frames in Visual Studio

Visual Studio gives many navigation hotkeys:
F8 for next item in current panel (search results, errors ...),
Control+K, N for bookmarks,
Alt+- for going back and more.
There is one hotkey that I can't find, and I can't even find the menu-command for it, so I can't create the hotkey myself.
I don't know if such exist: Previous and Next call-stack frame.
I try not using the mouse when programming, but when I need to go back the stack, I must use it to double click the previous frame.
Anyone? How about a macro that does it?
I wrote 2 macros to gain it: PreviousStackFrame and NextStackFrame and assigned shortcuts to
Function StackFrameIndex(ByRef aFrames As EnvDTE.StackFrames, ByRef aFrame As EnvDTE.StackFrame) As Long
For StackFrameIndex = 1 To aFrames.Count
If aFrames.Item(StackFrameIndex) Is aFrame Then Exit Function
Next
StackFrameIndex = -1
End Function
Sub NavigateStack(ByVal aShift As Long)
If DTE.Debugger.CurrentProgram Is Nothing Then
DTE.StatusBar.Text = "No program is currently being debugged."
Exit Sub
End If
Dim ind As Long = StackFrameIndex(DTE.Debugger.CurrentThread.StackFrames, DTE.Debugger.CurrentStackFrame)
If ind = -1 Then
DTE.StatusBar.Text = "Stack navigation failed"
Exit Sub
End If
ind = ind + aShift
If ind <= 0 Or ind > DTE.Debugger.CurrentThread.StackFrames.Count Then
DTE.StatusBar.Text = "Stack frame index is out of range"
Exit Sub
End If
DTE.Debugger.CurrentStackFrame = DTE.Debugger.CurrentThread.StackFrames.Item(ind)
DTE.StatusBar.Text = "Stack frame index: " & ind & " of " & DTE.Debugger.CurrentThread.StackFrames.Count
End Sub
Sub PreviousStackFrame()
NavigateStack(1)
End Sub
Sub NextStackFrame()
NavigateStack(-1)
End Sub
I have solved this problem with AutoHotkey. I made this a few months ago.
Suppose you wanted to use Control+1 and Control+2 and that Control+Alt+C is bound to showing the Call Stack window:
^1::SendInput !^c{down}{enter}
^2::SendInput !^c{up}{enter}
It seems to work pretty well. If you aren't already using AutoHotkey to show Visual Studio who's boss, please give it a shot. Your question indicates that you would benefit greatly from it. It's a game changer. Good luck.
I don't think theres an explict next-frame / prev-frame key binding but heres what I do.
CTRL-ALT-C is already bound to "Debug.CallStack"
This will focus you in the Call Stack Tool Window
Once focused in the Callstack window... Up & Down arrows will move you through the call stack frames
I've then bound
CTRL-C, CTRL-S to "DebuggerContextMenus.CallStackWindow.SwitchToFrame"
and
CTRL-C, CTRL-C to "DebuggerContextMenus.CallStackWindow.SwitchToCode"
both of which will take you back into the code window at the particular frame.
Hope that helps.
Huge thanks to #Oleg Svechkarenko for his answer that gave me a starting point in crafting this solution. Since modern versions of Visual Studio no longer have official macro support, this should drop in for those who use the Visual Commander plugin, but probably can be easily adapted for any other macro extension.
Here is the code for the command, I created one for navigating up the call stack and one for navigating down with the same code except the parameter passed to MoveStackIndex(), then bound keyboard shortcuts to them:
using EnvDTE;
using EnvDTE80;
using System;
public class C : VisualCommanderExt.ICommand
{
enum MoveDirection
{
Up,
Down,
}
private bool IsValidFrame(StackFrame frame)
{
string language = frame.Language;
bool result = (language == "C#" ||
language == "C++" ||
language == "VB" ||
language == "Python");
return result;
}
private void MoveStackIndex(EnvDTE80.DTE2 DTE, MoveDirection direction)
{
StackFrame currentFrame = DTE.Debugger.CurrentStackFrame;
bool foundTarget = false;
bool pastCurrent = false;
StackFrame lastValid = null;
foreach (StackFrame frame in DTE.Debugger.CurrentThread.StackFrames)
{
bool isCurrent = frame == currentFrame;
if (direction == MoveDirection.Down)
{
if (isCurrent)
{
if (lastValid == null)
{
// No valid frames below this one
break;
}
else
{
DTE.Debugger.CurrentStackFrame = lastValid;
foundTarget = true;
break;
}
}
else
{
if (IsValidFrame(frame))
{
lastValid = frame;
}
}
}
if (direction == MoveDirection.Up && pastCurrent)
{
if (IsValidFrame(frame))
{
DTE.Debugger.CurrentStackFrame = frame;
foundTarget = true;
break;
}
}
if (isCurrent)
{
pastCurrent = true;
}
}
if (!foundTarget)
{
DTE.StatusBar.Text = "Failed to find valid stack frame in that direction.";
}
}
public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
{
if (DTE.Debugger.CurrentProgram == null)
{
DTE.StatusBar.Text = "Debug session not active.";
}
else
{
// NOTE: Change param 2 to MoveDirection.Up for the up command
MoveStackIndex(DTE, MoveDirection.Down);
}
}
}
Look in Tools->Options->Environment->Keyboard. Enter "stack" or "frame" and related menus will appear. It seems that there's no next and previous call-stack frame.

Resources