Can gdb set break at every function inside a directory? - debugging

I have a large source tree with a directory that has several files in it. I'd like gdb to break every time any of those functions are called, but don't want to have to specify every file. I've tried setting break /path/to/dir/:*, break /path/to/dir/*:*, rbreak /path/to/dir/.*:* but none of them catch any of the functions in that directory. How can I get gdb to do what I want?

There seems to be no direct way to do it:
rbreak file:. does not seem to accept directories, only files. Also note that you would want a dot ., not asterisk *
there seems to be no way to loop over symbols in the Python API, see https://stackoverflow.com/a/30032690/895245
The best workaround I've found is to loop over the files with the Python API, and then call rbreak with those files:
import os
class RbreakDir(gdb.Command):
def __init__(self):
super().__init__(
'rbreak-dir',
gdb.COMMAND_BREAKPOINTS,
gdb.COMPLETE_NONE,
False
)
def invoke(self, arg, from_tty):
for root, dirs, files in os.walk(arg):
for basename in files:
path = os.path.abspath(os.path.join(root, basename))
gdb.execute('rbreak {}:.'.format(path), to_string=True)
RbreakDir()
Sample usage:
source a.py
rbreak-dir directory
This is ugly because of the gdb.execute call, but seems to work.
It is however too slow if you have a lot of files under the directory.
My test code is in my GitHub repo.

You could probably do this using the Python scripting that comes with modern gdb's. Two options: one is to list all the symbols and then if they contain the required directory create an instance of the Breakpoint class at the appropriate place to set the breakpoint. (Sorry, I can't recall off hand how to get a list of all the symbols, but I think you can do this.)
You haven't said why exactly you need to do this, but depending on your use-case an alternative may be to use reversible debugging - i.e. let it crash, and then step backwards. You can use gdb's inbuilt reversible debugging, or for radically improved performance, see UndoDB (http://undo-software.com/)

Related

Implement a SCons source code formater. Modify a source file before compiling it

I want to format my C/C++ source code before every compilation.
I found no information how to do it in SCons.
Ideas I tried:
What I would need: a Builder that has the same files for source and target. Impossible in SCons because cyclic dependency. env.FormatCode(target='bla.c', source='bla.c')
Use env.AddPreAction(source, format_action) on the objects resulted in compilation. Partially works, but not incremental with variant dirs.
def StyleFormatCCode(env, source):
sys.path.append('somePath/clangStyleChecker'))
import styleChecker
def format_action(target, source, env):
for file in source:
styleChecker.main(['-f', '-i', str(file)])
return env.AddPreAction(source, format_action)
sources1 = env.Glob('*.cpp')
sources = env.Object(sources1)
env.StyleFormatCCode(sources)
The style formatter problem is the same as Modify a source file before compilation.
Any idea how to do it or locations where I can find something like this in SCons?
Firstly, don't do this in process.
If you do it in process you will NOT be able to parallel build any where near as efficiently.
Python has the GIL and so there's very limited multithreading if all the logic is in python.
Secondly, modifying the source file before each compile will cause a recompile the next time around. Since you'll be modifying the sources.
If you're okay with either or both of the above, then something similar to your method would work for you.. ;)
You can reach into the Object and SharedObject builders and add prepend an action to their list of actions. You will be reaching in the innards of SCons to proceed carefully.
Another option would be just to do this logic in plain python (no Builder()s involved) in your SConscript/SConstruct. That would prevent the rebuilds as the sources are scanned and checked for changes after all the SConscripts have been processed.

Linking against an external object file (.o) with autoconf

For work purposes I need to link against an object file generated by another program and found in its folder, the case is that I did not find information about this kind of linkage. I think that if I hardcode the paths and put the name-of-obj.o in front of the package_LDADD variable should work, but the case is that I don't want to do it that way.
If the object is not found I want the configure to fail and tell the user that the name-of-obj.o is missing.
I tried by using AC_LIBOBJ([name-of-obj.o]) but this will try to find in the root directory a name-of-obj.c and compile it.
Any tip or solution around this issue?
Thank you!
I need to link against an object file generated by another program and
found in its folder
What you describe is a very unusual requirement, not among those that the Autotools are designed to handle cleanly or easily. In particular, Autoconf has no mechanisms specifically applicable to searching for bare object files, as opposed to libraries, and Automake has no particular automation around including such objects when it links. Nevertheless, these tools do have enough general purpose functionality to do what you want; it just won't be as tidy as you might like.
I think that if I hardcode the paths and put the
name-of-obj.o in front of the package_LDADD variable should work, but
the case is that I don't want to do it that way.
I take it that it is the "hardcode the paths" part that you want to avoid. Adding an item to an appropriate LDADD variable is not negotiable; it is the right way to get your object included in the link.
If the object is not found I want the configure to fail and tell the
user that the name-of-obj.o is missing.
Well, then, the key thing appears to be to get configure to perform a search for your object file. Autoconf does not have a built-in mechanism to perform such a search, but it's just a macro-based shell-script generator, so you can write such a search in shell script + Autoconf, maybe something like this:
AC_MSG_CHECKING([for name-of-obj.o])
OTHER_LOCATION=
for my_dir in
/some/location/other_program/src
/another/location/other_program.12345/src
$srcdir/../relative/location/other_program/src; do
AS_IF([test -r "${my_dir}/name-of-obj.o"], [
# optionally, perform any desired test to check that the object is usable
# ... perhaps one using AC_LINK_IFELSE ...
# if it passes, then
OTHER_LOCATION=${my_dir}
break
])
done
# Check whether the object was in fact discovered, and act appropriately
AS_IF([test "x${OTHER_LOCATION}" = x], [
# Not found
AC_MSG_RESULT([not found])
AC_MSG_ERROR([Cannot configure without name-of-obj.o])
], [
AC_MSG_RESULT([${OTHER_LOCATION}/name-of-obj.o])
AC_SUBST([OTHER_LOCATION])
])
That's functional, but of course you could embellish, such as by providing for the package builder to specify a location to use via a command-line argument (AC_ARG_WITH(...)). And if you want to do this for multiple objects, then you would probably want to wrap up at least some of that into a custom macro.
The Automake side is much less involved. To get the object linked, you just need to add it to the appropriate LDADD variable, using the output variable created by the above, such as:
foo_LDADD = $(OTHER_LOCATION)/name-of-obj.o
Note that if you're building just one program target then you can use the general LDADD instead of foo_LDADD, but note that by default these are alternatives not complements.
With that said, this is a bad idea overall. If you want to link something that is not part of your project, then you should get it from an installed library. That can be a local, custom-built library, of course, so long as it is a library, not a bare object file, and it is installed. It can be a static library if you don't want to rely on or distribute a separate shared library.
On the other hand, if your project is part of a larger build, then the best approach is probably to integrate it into that build, maybe as a subproject. It would still be best to link a library instead of a bare object file, but in a subproject context it might make sense to use a lib that was not installed to the build system. In conjunction with a command-line argument that tells it where to find the wanted lib, this could make the needed Autoconf code much cleaner and clearer.

ruby: copy directories recursively with link dereferencing

It's very strange, I cannot find any standard way with Ruby to copy a directory recursively while dereferencing symbolic links. The best I could find is FindUtils.cp_r but it only supports dereferencing the root src directory.
copy_entry is the same although documentation falsely shows that it has an option dereference. In source it is dereference_root and it does only that.
Also I can't find a standard way to recurse into directories. If nothing good exists, I can write something myself but wanted something simple and tested to be portable across Windows and Unix.
The standard way to recurse into directories is to use the Find class but I think you're going to have to write something. The built-in FileUtils methods are building blocks for normal operations but your need is not normal.
I'd recommend looking at the Pathname class which comes with Ruby. It makes it easy to walk directories using find, look at the type of the file and dereference it if necessary. In particular symlink? will tell you if a file is a soft-link and realpath will resolve the link and return the path to the real file.
For instance I have a soft-link in my home directory from .vim to vim:
vim = Pathname.new ENV['HOME'] + '/.vim'
=> #<Pathname:/Users/ttm/.vim>
vim.realpath
=> #<Pathname:/Users/ttm/vim>
Pathname is quite powerful, and I found it very nice when having to do some major directory traversals and working with soft-links. The docs say:
The goal of this class is to manipulate file path information in a neater way than standard Ruby provides. [...]
All functionality from File, FileTest, and some from Dir and FileUtils is included, in an unsurprising way. It is essentially a facade for all of these, and more.
If you use find, you'll probably want to implement the prune method which is used to skip entries you don't want to recurse into. I couldn't find it in Pathname when I was writing code so I added it using something like:
class Pathname
def prune
Find.prune
end
end
Here's my implementation of find -follow in ruby:
https://gist.github.com/akostadinov/05c2a976dc16ffee9cac
I could have isolated it into a class or monkey patch Find but I decided to do it as a self-contained method. There might be room for improvement because it doesn't work with jruby. If anybody has an idea, it will be welcome.
Update: found out why not working with jruby - https://github.com/jruby/jruby/issues/1895
I'll try to workaround. I implemented a workaround.
Update 2: now cp_r_dereference method ready - https://gist.github.com/akostadinov/fc688feba7669a4eb784

Prolog SWI : Logtalk, How do I load my own project files?

so this week consisted of me installing Logtalk, one of the extensions for Prolog. In this case I'm using Prolog SWI, and I've run into a little snag. I'm not sure how to actually consult my own projects using Logtalk. I have taken a look at the examples that Logtalk comes with in order to understand the code itself, and in doing so I've been able to load them and execute them perfectly. What I don't understand though is what is actually going on when logtalk is loading a file, and how I can load my own projects.
I'll take the "hello_world" example as the point of discussion. The file called hello_world, is located in the examples folder of the Logtalk files. and yet it is consulted like so:
| ?- logtalk_load(hello_world(loader)).
First thing I thought was "that is a functor", looking at what it was doing using trace, I found that it was being called from the library and was being told how to get to the examples folder, where it then opened the "hello_world" folder and then the "loader" file. After which normal compiling happened.
I took a look at the library and couldn't figure out what was going on. I also thought that this can't possibly be the practical route to load user created projects in Logtalk. There was another post that was asking how to do this with SWI as well, but it didn't have any replies and didn't look like any effort had been made to figure the problem out.
Now let me be clear on something, I can use the "consult('...')." command just fine, I can even use "consult" to open my projects, however if I do this the logtalk console doesn't seem to be using any of the logtalk extensions and so is just vanilla prolog. I've used an installer for windows to install logtalk and I know that it is working as I've been looking at the examples that it comes with.
I've tried to find a tutorial but it is very difficult to find much of anything for Logtalk, the most I have found is this documentation on loading from within your project:
logtalk_load/1.
logtalk_load/2.
which I understand like so:
logtalk_load(file). % Top level loading
logtalk_load(folder(file). % Bottom level loading
So to save a huge manual load each time I would have a loader file that will load the other components of my project (which is what the examples for Logtalk do). This bit makes sense to me, I think, how I get to my loader file, doesn't.
Whether or not I have been understanding it correctly or not remains to be seen, but even if I have been understanding it correctly, I'm still lost as to how I load my own projects. Thanks for any help you can give, if you could give an example that'll be best as I do learn from examples quite quickly.
LITTLE UPDATE
You asked if I was using a logtalk console for my program running, and I am, I'm using the one that is provided and referred to during the "QUICK_START" file [Start > Programs > Logtalk > "Logtalk - Prolog-SWI (console)"] I thought to double check if the logtalk add ons were working and tested the "birds" example since it uses objects and is a nice familiar example. Yet again, everything works fine when using the logtalk_load/2 functor.
I took a look at what the library path was referring to a bit more given the feedback given so far. Looking into how logtalk loads files. Set up as it is so far, without changing things logtalk consults a folder which contains a prolog file called libpaths. It is basically how the examples are found, all it is is a part way description for where to get a file from. So when I say "logtalk_load/2" from what I can tell at least I'm going to this file and finding where the folder is that I'm asking for.
Now since I have already placed my own project folder in the examples folder, I promptly added my own folder to the list to test if this would at least be a part way solution to help me understand things a bit more. I added the following to the libpaths.pl file.
logtalk_library_path(my_project, examples('my_project/')).
% The path must end in a / so I have done so
So, I've got my folder path declared, got my folder, and the loader file is what I'll be calling when I use the loader. Without thinking about setting my own lib path folder, I should have enough to get things working and do some practical learning. But alas no, seems my investigation failed and I was returned the following:
ERROR: Unhandled exception: existence_error(library,project_aim)
Not what I wanted to see, I'm back to this library error business. I'm missing a reference to my project folder somewhere but I don't know where else it could need referencing. Running trace on the matter didn't help I simply had the following occur:
Call: (17) logtalk_library_path(my_project, _G943) ? creep
Fail: (17) logtalk_library_path(my_project, _G943) ? creep
ERROR: Unhandled exception: existence_error(library,my_project)
The call is failing, I'm simply not finding a reference where ever it is logtalk is looking. And I'm a novice at best when it comes to these sorts of issues, I've been using computers now for only 3 years and programming for the past 2 in visual studios using c# and c++. At least I've shone some more light on the matter, any more helpful advice given this information?
Please use the official Logtalk support channels for help in the future. You will get timely replies there. Daniel, thanks for providing help to this user.
I assume that you're using Logtalk 2.x. Note that Logtalk 3.x supports relative and full source file paths. In Logtalk 2.x, the logtalk_compile/1-2 (compile to disk) and logtalk_load/1-2 (compile and load into memory) predicates take either the name of a source file (without the .lgt extension) OR the location of the source file to be loaded using "library notation". To use the former you need first to change the current working directory to the directory containing the file. This makes the second option more flexible. As you mention, the hello_world example you cite, can be loaded by typing:
?- logtalk_load(hello_world(loader)).
or:
?- {hello_world(loader)}.
Logtalk 2.x and 3.x also provide integration with some SWI-Prolog features such as consult/1, make/0, edit/0-1, the graphical tracer and the graphical profiler. For example:
?- [hello_world(loader)].
********** Hello World! **********
% [ /Users/pmoura/logtalk/examples/hello_world/hello_world.lgt loaded ]
% [ /Users/pmoura/logtalk/examples/hello_world/loader.lgt loaded ]
% (0 warnings)
true.
To load your own examples and projects, the easiest way is to add a library path to the directory holding your files to the $LOGTALKUSER/settings.lgt file (%LOGTALKUSER%\settings.lgt on Windows) as Daniel explained. The location of the Logtalk user directory is defined by you when using the provided installer. The default is My Documents\Logtalk in Windows. Editing the libpaths.pl file is not a good idea. Use the settings.lgt file preferentially to define your own library paths. Assuming, as it seems to be your case, that you have created a %LOGTALKUSER%\examples\project_aim directory, add the following lines to your %LOGTALKUSER%\settings.lgt file:
:- multifile(logtalk_library_path/2).
:- dynamic(logtalk_library_path/2).
logtalk_library_path(project_aim, examples('project_aim/').
If you have a %LOGTALKUSER%\examples\project_aim\loader.lgt file, you can then load it by typing:
?- {project_aim(loader)}.
Hope this helps.
What makes me uncertain of my answer is just that you claim the usual consult works but not logtalk_load. You do have to run a different program to get to Logtalk than Prolog. In Unix it would be something like swilgt for SWI-Prolog or gplgt for GNU Prolog. I don't have Windows so I can't really tell you what you need to do there, other than maybe make sure you're running a binary named Logtalk and not simply Prolog.
Otherwise I think your basic problem is that in Windows it's hard to control your working directory. In a Unix environment, you'd navigate your terminal over to the directory with your files in it and launch Logtalk or Prolog from there. Then when you name your files they would be in the current directory, so Prolog would have no trouble finding them. If you're running a command-line Prolog, you can probably configure the menu item so that it will do this for you, but you have to know where you want to send it.
You can use the functor notation either to get at subdirectories (so, e.g., foo(bar(baz(bat(afile)))) finds foo\bar\baz\bat\afile.lgt). This you seemed to have figured out, and I can at least corroborate it. This will search in its predefined list of functors, and also in the current directory. But you could launch Logtalk from anywhere and then run, say, assertz(logtalk_library_path(foo, 'C:\foo\bar\baz\bat')). after which logtalk_load(foo(afile)) is going to be expanded to C:\foo\bar\baz\bat\afile.lgt.
Building on that technique, you could put your files in the Logtalk user directory and use $LOGTALKUSER as demonstrated in the documentation. I can't find a definitive reference on where the Logtalk user directory will be on Windows, but I would expect it to be in the Documents and Settings folder for your user. So you could put stuff in there and reference it by defining a new logtalk_library_path like this.
It's nice, but it still leaves you high and dry if you have to keep on re-entering these assertions every time you launch. Fortunately, there is a Logtalk settings file named settings.lgt in your Logtalk user directory which has a chunk of commented-out code near the top:
% To define a "library" path for your projects, edit and uncomment the
% following lines (the library path must end with a slash character):
/*
:- multifile(logtalk_library_path/2).
:- dynamic(logtalk_library_path/2).
logtalk_library_path(my_project, '$HOME/my_project/').
logtalk_library_path(my_project_examples, my_project('examples/')).
*/
You can simply uncomment those lines and insert your own stuff to get a persistent shortcut.
You can also write a plrc file for SWI Prolog to define other things to happen at startup. The other option seems cleaner since it's Logtalk-specific, but a plrc is more general.
Once you have that machinery in place, having a loader file will be a lot more helpful.
NOTE: I don't have Windows to test any of this stuff on, so you may need to make either or both of the following changes to the preceeding:
You may need to use / instead of \ in your paths (or maybe either will work, who knows?). I'd probably try / first because that's how all other systems work.
You may need to use %LOGTALKUSER% instead of $LOGTALKUSER, depending on how Logtalk expands variables.
Hope this helps and I hope you stick with Logtalk, it could use some passionate users like yourself!

Shell scan for variables in "C" source program

Can anyone help me with some advice on how to solve the following problems?
The idea of the problem is to scan a Foo.c file to find all variables, how many times they occur, and the lines were they do occur.
The implementation can be in at least one of the methods:
Build a bat script and eventually additional C program(s)
to solve the problem. Run the implementation in a cmd window.
Build a ps1 script and eventually additional C program(s)
to solve the problem. Run the implementation in a PowerShell window.
I think that, in order to get all variable declarations and uses, and only variable declarations and uses, you're going to need to at least partially parse the source files and analyze the resulting abstract syntax trees.
Your first step, then, is to either write a parser or figure out how to utilize an existing one.
If you are programming C# you can use ANTLR V3 to parse your sources the "C" grammar exists.
You could certainly try to write this as a bat script, but believe me, I've written close to 200 bat scripts and it's horrendous. cmd.exe's findstr would be your friend, but between bat and regex, you're gonna go crazy. Powershell would definitely be better, however a real scripting language would be your best bet, like perl, ruby, or python.
Luckily, in your case anyways, all var in C are explicitly declared, so you could scan once for all the var declarations and create an array of them. Then, scan a second time looking for instances of those variable names. Total number of instances would be total_times_seen -1 since the first would be the var declaration. This assumes of course they are only declared once...

Resources