How can I detect breakpoints in GDB command files and stop the execution? - debugging

I am trying to implement a single stepping using GDB command file. I would like to stop executing the command file whenever I encounter any breakpoint.
Is there a way to detect that a breakpoint was hit? and also how can I stop executing the command file after that.
I checked the documantation and it seems like I only can have break commands for certain breakpoints. But not for a random breakpoint.
I have something like this:
printf "single stepping\n"
set $steps_count = 0
while ($steps_count < 5)
set $steps_count = $steps_count + 1
printf "program counter 0x%x\n", $pc
printf "next #%d\n", $steps_count
next
end
And this is what I want to achieve:
printf "single stepping\n"
set $steps_count = 0
while (# breakpoint is not hit)
set $steps_count = $steps_count + 1
printf "program counter 0x%x\n", $pc
printf "next #%d\n", $steps_count
next
end
# end the execution of the command file.
update:
I tried to use the follwing:
# set the end breakpoint
break *0x199e
commands
stop 1
quit
end
break *0x1980
# set a certain once we encounter the first breakpoint
commands
set $count = 0
while $count < 5
printf "#PC: 0x%x", $pc
set $count = $count + 1
stepi
end
end
This should start logging the program counter once the first breakpoint is hit. But I don't know why this break command doesn't work. Once the breakpoint is hit the program stops and the while loop is not entered!
Update:
according to the gdb documentation:
Any other commands in the command list, after a command that resumes execution, are ignored. This is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint--which could have its own command list, leading to ambiguities about which list to execute.
so I don't think it is a good idea to put a loop that has step or next in break commands.

Try something like:
commands 1-10 # for breakpoints number 1 through 10
set $breakpoint_hit = 1
end
Then check for that in your loop.

Related

Passing Command Line Argument to SwitchCase in AutoIt

I have a script that has a GUI and I have been running with a start button using the below code:
Case $StartButton
I would also like to try scheduling this using Windows TaskScheduler to run every morning at 8 AM EST. What would be the best way to add a condition to either start with the start button OR when TaskScheduler runs at 8 AM EST (or any specific time)? I am hesitant to just do 8 AM condition as it may increase processing a lot always looking at the time.
Essentially what I am looking to have happen is for my computer to auto-unlock (login?) using task scheduler and run this AutoIt script which has been compiled to exe.
FilePath is: C:\Users\robert\OneDrive\Desktop\TempFile.exe
Block of relevant code is below:
While 1
$nMsg = GUIGetMsg()
Switch $nMsg
Case $GUI_EVENT_CLOSE
Exit
Case $Save
SaveOptions()
Case $StartButton
;TAB1 of GUI
If WinExists("[CLASS: QT373947473845]") Then
$oBlah = WinGetHandle("[CLASS: QT373947473845]")
$BSLoc = WinGetPos ("[CLASS: QT373947473845]")
If $BSLoc[0] <> 0 or $BSLoc[1] <> 0 or $BSLoc[2] <> 800 or $BSLoc[3] <> 600 Then
WinSetState ( $oBlah, "", #SW_MINIMIZE )
sleep(500)
WinActivate($oBlah)
WinWaitActive($oBlah)
WinMove($oBlah, "", 0, 0, 800, 600)
sleep(2000)
Else
WinActivate($oBlah)
WinWaitActive($oBlah)
sleep(2000)
EndIf
Endif
EndSwitch
WEnd
I have thousands of lines of other code within the case but I tried to limit it as that portion is irrelevant
The Case $StartButton is the line where I am trying to do an OR if run by TaskManager. I have read you cannot do an OR function within a switch case but if you do 2 cases without a break it is the same thing?
I read some documentation and saw I can add a “/prim1=value” to the end of the command line and it will pass the prim1 argument to $CmdLine[0] but I can’t seem to get it working properly.
Review the documentation.
Particularly this part:
So if you were to use the compiled executable by passing commandline
parameters:
myProg.exe param1 "This is a string parameter" 99
$CmdLine[0] ; this equals 3 (because there are 3 command line parameters)
$CmdLine[1] ; This contains "param1".
$CmdLine[2] ; This contains "This is a string parameter".
$CmdLine[3] ; This contains 99.
So then just modify the code so that it behaves differently if $CmdLine[1] = something.
As for the switch case: that is inside of a message loop for the GUI and the code in the Case $StartButton part of the switch block is run when the start button is pressed and $nMsg is equal to the control ID of the start button ($StartButton).
If you want to run this code at some other time what I would do it just move all of that code into its own function:
Func onStartClick()
; start button code here
Endfunc
And then just call onStartClick() in the switch block:
$nMsg = GUIGetMsg()
Switch $nMsg
Case $StartButton
onStartClick()
Case $someOtherButton
; someOtherButton code...etc
EndSwitch
And then you can also call this function if there is a particular command line param (place this code before the Switch...EndSwitch block, not inside it):
If $CmdLine[0] >= 1 And $CmdLine[1] = "param1" then
; other code to run when started with "program.exe param1"
onStartClick()
EndIf
So the entire thing would look like this:
Func onStartClick()
; start button code here
Endfunc
If $CmdLine[0] >= 1 And $CmdLine[1] = "param1" then
; other code to run when started with "param1"
onStartClick()
EndIf
$nMsg = GUIGetMsg()
Switch $nMsg
Case $StartButton
onStartClick()
Case $someOtherButton
; someOtherButton code...etc
EndSwitch

How to handle optional windows in Autoit?

I am automating a software installation in Windows7 using AutoIt.
During the installation, in between if a error window appears. I want to click ENTER.
If the error window not appears then I should NOT do anything. Simply its should go to the next section.
I have tried "WinActive and WinWaitActive" But its waiting for the window to appear. If window not appears its not going to the next screen.
Any idea how to handle this situation?
Do a while loop:
$w = 0
While($w = 0)
If(WinActive("ERROR WINDOW"))Then
Send("{ENTER}")
$w = 1
ElseIf(ControlGetText("YOUR WINDOW", "", "[CLASS:Static; INSTANCE:2]") <> "SOME TEXT") Then
$w = 1
;and something else
EndIf
Sleep(1000)
WEnd
AdlibRegister() is the right choice. From the help file:
"... typically to check for unforeseen errors. For example, you could use adlib in a script which causes an error window to pop up unpredictably."
Each 100 ms (may be adjusted) the function is called to check the appearing of your error dialog:
Global $sErrorWindow = 'ErrorDialogName'
Global $iDelayHowOftenDoTheFunctionCall = 100
AdlibRegister('_isErrorWindowDisplayed', $iDelayHowOftenDoTheFunctionCall)
Func _isErrorWindowDisplayed()
If WinActive($sErrorWindow) <> 0 Then
WinActivate($sErrorWindow) ; just to be sure that the ENTER command is on the correct window/dialog
; either do
Send('{ENTER}')
; or
ControlClick('title', 'text', 'controlID')
EndIf
EndFunc
; do your software installation processing here
; ...
; ...
; don't forget to unregister the function at the end
AdlibUnRegister('_isErrorWindowDisplayed')

Can I tell LLDB to remove the active breakpoint?

When LLDB triggers breakpoint X, is there a command that will disable or remove X and then continue?
That's an interesting idea. There's no built in command to do this in lldb but it would be easy to implement as a user-defined command written in Python. SBThread::GetStopReason() will be eStopReasonBreakpoint if that thread stopped because of a breakpoint. SBThread::GetStopReasonDataCount() will return 2 -- indicating that the breakpoint id and location id are available. SBThread::GetStopReasonDataAtIndex(0) will give you the breakpoint ID, SBThread::GetStopReasonDataAtIndex(1) will give you the location ID. (a single user-specified breakpoint may resolve to multiple locations. e.g. an inlined function, or a function name that occurs in multiple libraries in a single program.)
Here's a quick & dirty example of a python command that does this. I put this in ~/lldb where I save my lldb user-defined commands and then in my ~/.lldbinit file I have a line like command script import ~/lldb/disthis.py.
In use, it looks like this:
% lldb a.out
(lldb) target create "a.out"
Current executable set to 'a.out' (x86_64).
(lldb) br s -n main
Breakpoint 1: where = a.out`main + 15 at a.c:4, address = 0x0000000100000f4f
(lldb) r
Process 67487 launched: '/private/tmp/a.out' (x86_64)
Process 67487 stopped
* thread #1: tid = 0x290c51, 0x0000000100000f4f a.out`main + 15 at a.c:4, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
#0: 0x0000000100000f4f a.out`main + 15 at a.c:4
1 #include <stdio.h>
2 int main()
3 {
-> 4 puts ("HI");
5 puts ("HI");
6 }
(lldb) com scr imp ~/lldb/disthis.py
(lldb) disthis
Breakpoint 1.1 disabled.
(lldb) br li
Current breakpoints:
1: name = 'main', locations = 1
1.1: where = a.out`main + 15 at a.c:4, address = 0x0000000100000f4f, unresolved, hit count = 1 Options: disabled
(lldb)
Pretty straightforward.
# import this into lldb with a command like
# command script import disthis.py
import lldb
def disthis(debugger, command, *args):
"""Usage: disthis
Disables the breakpoint the currently selected thread is stopped at."""
target = None
thread = None
if len(args) == 2:
# Old lldb invocation style
result = args[0]
if debugger and debugger.GetSelectedTarget() and debugger.GetSelectedTarget().GetProcess():
target = debugger.GetSelectedTarget()
process = target.GetProcess()
thread = process.GetSelectedThread()
elif len(args) == 3:
# New (2015 & later) lldb invocation style where we're given the execution context
exe_ctx = args[0]
result = args[1]
target = exe_ctx.GetTarget()
thread = exe_ctx.GetThread()
else:
print "Unknown python function invocation from lldb."
return
if thread == None:
print >>result, "error: process is not paused, or has not been started yet."
result.SetStatus (lldb.eReturnStatusFailed)
return
if thread.GetStopReason() != lldb.eStopReasonBreakpoint:
print >>result, "error: not stopped at a breakpoint."
result.SetStatus (lldb.eReturnStatusFailed)
return
if thread.GetStopReasonDataCount() != 2:
print >>result, "error: Unexpected number of StopReasonData returned, expected 2, got %d" % thread.GetStopReasonDataCount()
result.SetStatus (lldb.eReturnStatusFailed)
return
break_num = thread.GetStopReasonDataAtIndex(0)
location_num = thread.GetStopReasonDataAtIndex(1)
if break_num == 0 or location_num == 0:
print >>result, "error: Got invalid breakpoint number or location number"
result.SetStatus (lldb.eReturnStatusFailed)
return
bkpt = target.FindBreakpointByID (break_num)
if location_num > bkpt.GetNumLocations():
print >>result, "error: Invalid location number"
result.SetStatus (lldb.eReturnStatusFailed)
return
bkpt_loc = bkpt.GetLocationAtIndex(location_num - 1)
if bkpt_loc.IsValid() != True:
print >>result, "error: Got invalid BreakpointLocation"
result.SetStatus (lldb.eReturnStatusFailed)
return
bkpt_loc.SetEnabled(False)
print >>result, "Breakpoint %d.%d disabled." % (break_num, location_num)
return
def __lldb_init_module (debugger, dict):
debugger.HandleCommand('command script add -f %s.disthis disthis' % __name__)

Print the value of a local variable through GDB

while debugging I need to print the value of a variable that is declared in the else block. something like this :
if(condition){
}
else {
string str = "abcd";
strcpy(globalvariable,str,sizeOf(str));
}
I want to see the value of str.
Run the program inside the debugger.
Set break point to stop the execution of program sequence using break command. In your case, (gdb) break strcpy to break every time it is being called strcpy in else.
To print you can use any of the following, x str, x/s str, print str, print "%s", str.
You can't see the value of str if condition is true during program flow because it does not exist in memory in this case.
You have to enter else block somehow, either during normal program flow or using gdb jump command.

Using gdb, display multiple vars in one line?

How can I ask to display multiple vars in one line? So I want to get output like:
30 if(s[i] != '\0')
5: s[i] = 101 'e'
4: exp = 14
3: val = 123.45
2: sign = 1
1: i = 6
I've been typing in disp s[i] ENTER disp exp ENTER (etc, etc) and I just know there's got to be a better way to do this in one line of typing.
To establish multiple active "variable displays" without re-typing each of display i, display s[i], etc. every time you restart GDB, use a GDB "canned command sequence".
For example, add this to your ~/.gdbinit:
define disp_vars
disp i
disp sign
disp val
disp exp
disp s[i]
end
Now you can add all the displays at once by typing disp_vars at the GDB prompt.
Employed Russian gave the correct solution but for those that want see it used in an example see below. If you're not sure if you want to commit to putting the .gdbinit in your home directory, you can also put it in the directory you're executing the program from to experiment.
$ gcc -g atof_ex4.2.c
$ gdb ./a.out
(gdb) b 30
Breakpoint 1 at 0x1907: file atof_ex4.2.c, line 30.
(gdb) h user-defined
List of commands:
disp_vars -- User-defined
(gdb) disp_vars #this will enable the user defined canned sequence (but I haven't done run yet! So I'll this actually doesn't work yet.)
No symbol "i" in current context.
(gdb) r
Starting program: a.out
Breakpoint 1, atof (s=0xbffff028 "123.45e-6") at atof_ex4.2.c:30
30 if(s[i] != '\0')
(gdb) s # No disp_vars output yet because I have to do it AFTER 'run' command
32 if(s[i] == 'e' || s[i] == 'E')
(gdb) disp_vars # Now it will work ;)
(gdb) s
35 sign = (s[i] == '-') ? -1 : 1;
5: s[i] = 45 '-'
4: exp = 14
3: val = 123.45
2: sign = 1
1: i = 7
Of course 'r' is for run, 's' is for step, 'b' is for break, etc. I've also omitted some output. Notice that I had to enter the 'disp_vars' command again after 'run'. Thanks Employed Russian.

Resources