Running a perl program under a debugger until some condition is met - c

I am using perl debugger in Eclipse (via EPIC plugin). Is there any feature to automate the steps until an event occurs. For example can I make it run until $args->{some_arg} is set? If not, what is the best known workaround? This feature or workaround may be similar to debugging some other C-like languages.

In the normal perl debugger, setting $DB::single = 1; will drop you to the debugger. So you could have the following:
$DB::single = 1 if $args->{some_arg};
I have no idea if this works in Eclipse.

What I was looking for actually something that follows all the flow and stops whenever that condition is met. But closest thing to this is called conditional breakpoints which works as Leolo mentioned. EPIC actually supports this but some versions is kind'a faulty in some versions. The way to do that is after setting breakpoint somewhere, right-click on it and set condition in Properties dialog. In faulty versions, properties is the third choice in the menu, with no text.

The stock perl debugger has a watch w command.
The perl debugger Devel::Trepan can also has a watch command.
Here is an example. In file test.pl:
my $x = 1;
my $y = 2;
my $x = 3;
Now here is a sample session:
trepan.pl test.pl
-- main::(test.pl:1 #0x19b5da8)
my $x = 1;
(trepanpl): watch $y
Watch expression 1: $y set
$DB::D[0] = <undef>
(trepanpl): c
Watchpoint 1: $y changed
------------------------
old value <undef>
new value 2
wa main::(test.pl:3 #0x1b2a5a8)
my $x = 3;
(trepanpl):
I should note one thing about watchpoints. In contrast to gdb which often has hardware support for this feature, that is not the case here. So when you use this, your program may slow down because the debugger gets called every each possible stopping point to check of the value of the expression has changed.
Devel::Trepan also has gdb-style breakpoints where you can attach a condition to the breakpoint. If using watchpoints slows your program down too much, use this which should be faster.
Perhaps someone will write an Eclipse plugin for Devel::Trepan.

Related

Launch interactive session via script bridge

I am trying to launch an interactive debugging session from a python script via the SWIG-generated lldb module. The program to debug is nothing but an empty main function. Here is my current attempt:
import lldb
import sys
import os
debugger = lldb.SBDebugger.Create()
debugger.SetAsync(False)
target = debugger.CreateTargetWithFileAndArch("a.out", "")
# The breakpoint itself works fine:
fileSpec = lldb.SBFileSpecList()
mainBp = target.BreakpointCreateByName("main", 4, fileSpec, fileSpec)
mainBp.SetAutoContinue(False)
# Use the current terminal for IO
stdout = os.ttyname(sys.stdout.fileno())
stdin = os.ttyname(sys.stdin.fileno())
stderr = os.ttyname(sys.stderr.fileno())
flag = lldb.eLaunchFlagNone
target.Launch(target.GetDebugger().GetListener(), [], [], stdin, stdout,
stderr, os.getcwd(), flag, False, lldb.SBError())
It seems to me that whatever flag I pass to target.Launch (I tried amongst those flags), there is no way of switching to an interactive editline session. I do understand that the primary purpose of the python bindings is non-interactive scripting, but I am nevertheless curious whether this scenario could be made possible.
There is a method on SBDebugger to do this (RunCommandInterpreter). That's how Xcode & similar make lldb console windows. But so far it's only been used from C and there's something wrong with the C++ -> Python bindings for this function such that when you try to call it from Python you get a weird error about the 5th argument being of the wrong type. The argument is an int& and that gives SWIG (the interface generator) errors at runtime.
Of course, you could just start reading from STDIN after launch and every time you get a complete line pass it to "SBCommandInterpreter::HandleCommand". But getting RunCommandInterpreter working is the preferable solution.

Parallel processing - `forking` fails under Mac OS 10.6.8

It appears that fork fails under Mac OS 10.6.8. The algorithm is coded in R and I have mainly be using the foreach package for parallel processing. The code works perfectly well when run sequentially (foreach and %do%) but not when run in parallel (foreach and %dopar%) even though the processes run in parallel do NOT communicate.
I used foreach on this same machine a month ago and it worked fine. An update of the OS has been performed in the meantime.
Error Messages
I received several kinds of error messages that seems to come almost stochastically. Also the errors differ depending on whether the code is run from the terminal (either by copy-pasting in the R environment or with R CMD BATCH) or from the R console.
When run on the Terminal, I get
Error in { : task 1 failed - "object 'dp' not found"
When run on the R console I get either
The process has forked and you cannot use this CoreFoundation functionality safely. You MUST exec().
Break on __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__() to debug.
....
<repeated many times when run on the R console>
or
Error in { : task 1 failed - "object 'dp' not found"
with the exact same code! Note that although this second error message is the same than the one received on the Terminal, the number of things that are printed (through the print() function) on the screen vastly differ!
What I've tried
I updated the package foreach and I also restarting my computer but it did not quite help.
I tried to print pretty much anything I could but it ended up being quite hard to keep track of what this algorithm is doing. For example, it often through the error about the missing object dp without executing the print statement at the line that precedes the call of the object dp.
I tried to use %dopar% but registering only 1 CPU. The output did not change on the Terminal, but it changed on the Console. Now the console gives the exact same error, at the same time than the terminal.
I made sure that several CPUs were in used when I ask for several CPUs.
I tried to use mclapply instead of foreach and registerDoMC() instead of registerDoParallel() to register the number of cores.
Extra-Info
My version of R is 3.0.2 GUI 1.62 Snow Leopard build. My machine has 16 cores.

tcl multithreading like in c, having hard time to execute thread with procedure

I used to work in C, where threads are easy to create with a specific function I choose.
Now in tcl I can't use thread to start with a specific function I want, I tried this:
package require Thread
proc printme {aa} {
puts "$aa"
}
set abc "dasdasdas"
set pool [tpool::create -maxworkers 4 ]
# The list of *scripts* to evaluate
set tasks {
{puts "ThisisOK"}
{puts $abc}
{printme "1234"}
}
# Post the work items (scripts to run)
foreach task $tasks {
lappend jobs [tpool::post $pool $task]
}
# Wait for all the jobs to finish
for {set running $jobs} {[llength $running]} {} {
tpool::wait $pool $running running
}
# Get the results; you might want a different way to print the results...
foreach task $tasks job $jobs {
set jobResult [tpool::get $pool $job]
puts "TASK: $task"
puts "RESULT: $jobResult"
}
I always get:
Execution error 206: invalid command name "printme"invalid command name "printme"
while executing
"printme "1234""
invoked from within
"tpool::get $pool $job"
Why?
You problem is, that the Tcl threading model is very different from the one used in C. Tcl's model is a basically 'shared nothing by default' model mostly based on message passing.
So every thread in the pool is an isolated interpreter and does not know anything about a proc printme. You need to initialize those interpreters with the procs you need.
See the docs for the ::tpool::create command, it has an option to provide a -initcmd where you can define or package require the stuff you need.
So try this to initialize your threads:
set pool [tpool::create -maxworkers -initcmd {
proc printme {aa} {
puts "$aa"
}}]
https://www.tcl.tk/man/tcl/ThreadCmd/tpool.htm#M10
To answer your comment a bit more detailed:
No, there is no way to make Tcl threads work like C threads and share objects and procs freely. It is a fundamental design decision and allows Tcl to have an interpreter without a massive global lock (in contrast to e.g. CPython), as most things are thread local and use thread local storage.
But there are some ways to make initialization and use of multiple thread interpreters easier. One is the -initcmd parameter from ::tpool::create which allows you to run initialization code for every single interpreter in your pool without doing it manually. If all your code lives in a package, you simply add a package require and your interpreter is properly initialized.
If you really want to share state between multiple threads, you can use the ::tsv subcommands. It allows you to share arrays and other things between threads in an explict way. But under the hood it involves the typical locks and mutexes you might know from C to mediate access.
There is another set of commands in the thread package that allow you to make initialization easier. This is the ttrace command, which allows you to simply trace what gets executed in one interpreter and automatically repeat it in another interpreter. It is quite smart and only shares/copies the procs you really use to the target instead of loading all things upfront.

On key board handler in linux using c programing

I am trying a program in c that controls keyboard handler to blink NUMLOCK & CAPSLOCK LED's as a reaction of ctrl+alt+del push... please help me..
I kinda agree with KP. This is funny...
But if yer serious...
First:
There's a setleds program that might help you get started. It's been around for ages... Try man setleds.
Also, xset can be used (under X-windows) to change leds... (You may have to see which leds are enabled for changing in the X-config file.)
Second:
Detecting ctrl+alt+del is more of an issue as it's flagged specially by init. Look in /etc/inittab or /etc/init/control-alt-delete.conf or someplace like that, and you'll see lines like:
# Trap CTRL-ALT-DELETE
ca::ctrlaltdel:/sbin/shutdown -t3 -h now
Or:
# control-alt-delete - emergency keypress handling
#
# This task is run whenever the Control-Alt-Delete key combination is
# pressed. Usually used to shut down the machine.
start on control-alt-delete
exec /sbin/shutdown -r now "Control-Alt-Delete pressed"
So you'd have to disable that... Or simply have it run your keyboard-blink program rather than /sbin/shutdown.
Also, watch out for "Control-Alt-Backspace" -- Many X11 config setups enable this combination to shutdown the X server. (Option "DontZap".)
Third:
Now you need to find a way to pickup the control-alt-delete keypress. It's not impossible, but it may not be as simple as getc(). (The again, I could be wrong...)
Of course, if you don't want your program to have the keyboard focus. If you want this to happen while other programs are running in the foreground with keyboard focus... Well then yer looking at tweaking the kernel or some kernel driver. (Or having inittab run yer program instead of /sbin/shutdown.)
Any way you slice it, this is not a good Hello World type exercise.
Option:
Find the right place to trap Alt+Ctrl+Del and register a handler.
Use the KDGETLED/KDSETLED ioctl on /dev/console to changes the keyboard LEDs.
Good Luck!

Most tricky/useful commands for gdb debugger [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Can you post your most tricky and useful commands while you run a debugger like gdb or dbx.
backtrace full: Complete backtrace with local variables
up, down, frame: Move through frames
watch: Suspend the process when a certain condition is met
set print pretty on: Prints out prettily formatted C source code
set logging on: Log debugging session to show to others for support
set print array on: Pretty array printing
finish: Continue till end of function
enable and disable: Enable/disable breakpoints
tbreak: Break once, and then remove the breakpoint
where: Line number currently being executed
info locals: View all local variables
info args: View all function arguments
list: view source
rbreak: break on function matching regular expression
Start gdb with a textual user interface
gdb -tui
Starting in gdb 7.0, there is reversible debugging, so your new favourite commands are:
* reverse-continue ('rc') -- Continue program being debugged but run it in reverse
* reverse-finish -- Execute backward until just before the selected stack frame is called
* reverse-next ('rn') -- Step program backward, proceeding through subroutine calls.
* reverse-nexti ('rni') -- Step backward one instruction, but proceed through called subroutines.
* reverse-step ('rs') -- Step program backward until it reaches the beginning of a previous source line
* reverse-stepi -- Step backward exactly one instruction
* set exec-direction (forward/reverse) -- Set direction of execution.
Instead of launching GDB with "-tui" param you can also switch to text mode after a while using by typing "wh".
thread apply all bt or thread apply all print $pc: For finding out quickly what all threads are doing.
For example the macros defined in stl-views.gdb
scripting gdb is a good trick, other than that I like
set scheduler locking on / off to prevent the running of other threads when you are stepping in one.
Using the -command=<file with gdb commands> option while firing up gdb. Same as -x <command file>. This command file can contain gdb commands like breakpoints, options, etc. Useful in case a particular executable needs to be put through successive debug runs using gdb.
Using .gdbinit (start up file where you can write macros and call from gdb). Place .gdbinit in your home directory so that it is picked up every time gdb is loaded
info threads to list all the active threads, and f(#) -> # thread number you want to switch to
sometime i use gdb to convert from hex to decimal or binary, its very handy instead of opening up a calculator
p/d 0x10 -> gives decimal equivalent of 0x10
p/t 0x10 -> binary equivalent of 0x10
p/x 256 -> hex equivalent of 256
Instead of starting gdb with the option -tui to see a child process that contains a screen that highlights where the executing line of code is in your program, jump in and out of this feature with C-x o and C-x a. This is useful if you're using the feature and what to temporarily not use it so you can use the up-arrow to get a previous command.
This can be useful, I am sure it could be improved though, help welcome:
define mallocinfo
set $__f = fopen("/dev/tty", "w")
call malloc_info(0, $__f)
call fclose($__f)
To debug STL, add content to .gdbinit, follow these instructions:
http://www.yolinux.com/TUTORIALS/GDB-Commands.html#STLDEREF

Resources