How to create empty working boost::python::dict? - c++

I parse a C++ project which compiling as library.so for python. So I can`t debug it inside Qt creator IDE. For this purpose I created separate project with executable main():
int main()
{
boost::python::dict whiteList;
whiteList.has_key("blablabla");
...
return 0;
}
On release mode program compiling and work incorrectly. But on debugging mode program fails in has_key() method with error window:
The inferior stopped because it received a signal from the Operating System.
Signal name : SIGSEGV
Signal meaning : Segmentation fault
Probably the question is: How to correctly create and use boost::python::dict purely inside C++ program without involving python script?

Whenever you use the Python C API or Boost Python, you must initialize Python:
Py_Initialize();
Add that to the top of your main() et voila.

Related

Compiling and injecting code in GDB: C++ rather than C

I am running gdb 10.1.90.20210103-git and gcc/g++ 10.2.1 20210110 on x86-64 Debian 11. My IDE is Codelite, which uses the manual rather than the machine interface to gdb, and enables me to type commands directly to gdb, and see the response (potentially copying the response to the clipboard). This when the inferior is paused after hitting a breakpoiunt, via the gdb console, which is in Codelite's Debugger > Output pane.
I was able to use the instructions at: https://sourceware.org/gdb/current/onlinedocs/gdb#Compiling-and-Injecting-Code "Compiling and injecting code in GDB" to compile simple C code and make it run in the environment of the halted inferior. For instance: compile code blah++; increments a local variable int in the inferior, which I can see via the Locals or Watch panes.
The compile file command worked fine as long as I specified the absolute path of the source file.
I was unable to see console output (to the inferior's or gdb's console) for a simple printf() statement: `printf("xxx");' because the code would not compile if there was such a line
Despite using set debug compile and set debug compile-cplus-types and checking these are set with the show versions of these, I get no error messages or acknowledgements regarding whatever I try to compile.
The blah variable is an integer, which is accessible through C code and so gcc. The ability to increment this was the only indication that my code had compiled and run.
I could not get any responses to set/show compile gcc so I am presumably compiling with gcc. I did give the command set compile gcc /usr/bin/x86_64-linux-gnu-cpp-10, but there was still no response from show compile gcc or any change in the C-only behaviour.
I could not compile the file if it contained a C++ line which incremented a data member of a class object in an vector of such objects. Nor could I compile my code if it contained C++ code such as: #include <fstream> and/or std::fstream oFile;.
The gdb documentation mentioned above is general, but does have C examples.
Is it possible to compile C++ code under gdb, injecting it into the environment of the paused inferior, with any version of gdb and gcc?
I am keen to use this C++ code injection facility, if it exists, for dumping the contents of large, complex, data structures to files and and to modify some elements of same to aid debugging.
Summary: GDB's C++ compilation and injection system does not work for me, and it is reported to be buggy or non-functional. I only tested this compile command with single lines of C code, but it worked fine for these. I was able to run my function, which writes a text dump file containing the values of a vector of class objects' data members, while the inferior was paused after a breakpoint, by including it in a source file and calling it with GDB's print or call commands, giving it the required input argument of the name of the vector to dump.
I haven't tried using GDB on its own, but at present I have no reason to believe that Codelite is interfering with my ability to communicate with GDB via Codelite's "Debugger > Output" console.
I wrote to the GDB Developer list and received what I assume is a well informed reply. I was told that in my respondent's experience "the C++ plugin isn't very functional. It seems to have some bugs and crash pretty frequently as well. Also, it seems like nobody is actively working on it." This is consistent with my experience to date.
Perhaps later versions of GDB would work better. However, there has been minimal change to the library https://github.com/gcc-mirror/gcc/commits/master/libcc1/libcp1.cc since 2017, and I could find no indication of new work on C++ compilation and injection in https://www.sourceware.org/gdb/news/ since the announcement of its introduction:
GDB 8.3.1 was released on 2019-09-20, with: "Experimental support for compilation and injection of C++ source code into the inferior (requires GCC 7.1 or higher, built with libcp1.so)."
It is possible that my problem is related to not having this library. I do have the C equivalent: /usr/lib/x86_64-linux-gnu/libcc1.so.o. I could find no such library in a Debian package. It is possible I could get this going by compiling the latest GCC/G++ and GDB, but that is pretty daunting, involving installing later standard libraries than my current Debian installation has, while making those and the newer G++ and GDB available for Codelite sessions, but not interfering with other software on machine which needs the older compilation system.
The respondent suggested that instead of compiling and injecting fresh code in the middle of a debugging session, I could write it as a library, and run it by using the compile command, on a purely C piece of code which would call it. However, for my purposes, the function needs to be passed one or more C++ constructs, and any code which called a C++ function would be C++ code and so, presumably, not be compiled by GDB.
For my immediate purpose of doing text dumps of large vectors of class objects' data members, I was able to succeed by writing such a function in an existing source file, which also contains the functions I am debugging. Then I could call it with GDB's print or call commands. I imagine this would work if the debugging function was in any other linked source file, or in a linked library. (Perhaps there is a way of writing such a library, compiling and linking it while the inferior is halted.)
I was able to run this, from a debugging session in which the inferior was halted somewhere, with either the print or call command followed by the name of the function, with the name of the vector in brackets. There must be no semicolon. I found the print command better, since GDB would report the return value, which was "void". My function used C++ constructs such as "<<" to write to the text file.
A call within my dump function of the C function system("pwd") resulted in the current directory being output on the inferior's terminal window. Likewise: print system("pwd"). print system("mc") dutifully ran Midnight Commander in the inferior's terminal window.
I altered the function to return a string, which GDB reported in the GDB "Debugger > Output" console. I added a line: std::cout << "xyz"; - but nothing appeared on either the inferior's terminal window or in the GDB console.
My attempts to use the compile command to call my dump function in exactly the same way produced no results, with or without a trailing semicolon.
I found thatprint and call work with C and C++ code while `compile" only works with C code.
I tried print vvv[6].mmm for data members which were integers, floats, and strings and GDB returned their values correctly. Adding a ++ at the end caused it to return the original integer value, but the value itself was incremented.
When I tried print with a compound line of code, with a semicolon between the two logical lines, with and without one at the end, there was no response.
The GDB Developers list is not the place for support requests, but I did not know a better way to find out about the status of this facility.

QT Creator Can't read from stdin in debugger

I just updated QT Creator to 4.13.0 and now I can't read from stdin while I'm in the debugger.
A few details...
I am running on macOS.
I am writing C++, but using C stdio library. (for historical reasons)
I am using clang 15.5.0 in c++11 mode.
I am using the 'Run from Terminal' debugger option.
Problem: Type as I might, when my code goes into fgets it never returns.
Simplified Example:
#include <stdio.h>
int main()
{
char buf[1024];
if (fgets(buf,1024, stdin)) // In debugger, this call never returns!
{
fprintf(stderr, "%s", buf);
}
return 0;
}
Note: When I run this outside of the debugger - no problems.
Has anyone run across this and fixed it? Any ideas on how to fix it?
Could be an issue with the terminal start application openTerminal.py inside QtCreator.
I had a similar issue, where the output of my console application appeared correctly in a terminal session when starting in debug mode without the debugger, but when starting using the debugger all system output and system error was written to Application Output widget making it impossible to read any values from std::in.
Solution was:
Manage Kits: Environment System Replace the long path ".../openTerminal.py"
by "/Applications/Utilities/Terminal.app"

Segmentation fault when stepping into a function defined in the same file using an ARM cross-toolchain

I have this simplified example,
int myf(void) {
int a = 1;
int b = 2;
return a + b;
}
int main(void) {
int sum = myf(); // <--- bp here
printf("Result: %d\n", sum);
return 0;
}
I have a breakpoint at int sum = myf() and I run the debugger. Gdb successfully stops at this point, but a step into command (into myf) leads to a segmentation fault. If I put a bp directly in myf and run the debugger, then the debugger stops there as expected, no problem. In a shared library, not even the breakpoints work. They are ignored completely. Stepping into shared library code leads to the same segmentation fault error.
Step over functionality is also "broken". Stepping over code sometimes jumps into random (I think) locations, like in a file named dl-minimal.c
The code behaves as expected if it's simply run and not debugged.
Other useful info that I get in the debugger console when I get the segmentation fault error:
No function contains specified address
Disassembler failed: Cannot access memory at address 0xe7f001dc
See the printscreen for the full dbg console output:
The error is reproducible only when using a crosstoolchain for an ARM board (i.MX6). I have no such problem when debugging locally, on a Linux machine. I am using qtCreator 5.15. My cross-toolchain is built with yocto and bitbake.
Any hints regarding possible causes?
Set the GDB search path - in Tools->Options->Debugger. In the Additional Startup Commands box. Place there the correct sysroot (corresponding to the platform you are running from), and follow with the full path of your shared libraries debug build, from the local machine.
Also, make sure to run as regular user (set in Tools->Options->Devices) - though you will need to switch to root user when you deploy.

Capturing shell script exit status in c++ [duplicate]

This question already has answers here:
How to get the exit code of program invoked by system call?
(3 answers)
Closed 5 years ago.
I have a requirement of developing a small dependency manager for a Qt based C++ application I am developing. This C++ application will be targeting Linux systems. So this is how it works. I execute a shell script through the system() function. In the shell script I check whether the required packages are installed, if not I exit the shell script with the status of the last executed command. My question is, how do we capture this in C++ and handle it? (I want to capture it so I can inform the user that some of the dependencies are not installed and seek user permission to install them)
C++ code :
system("./myscript.sh");
Shell code :
iwconfig
exit $?
I've tried this aproach earlier on:
in C++ :
int i = system("./myscript.sh");
if(i!=0)
QMessageBox::information(this, tr("test"), tr("program exited with exit code"+i));
But then I get the following error :
The inferior stopped because it received a signal from the operating system. Signal name : SIGSEGV Signal meaning : Segmentation fault
How to get it done??
Prototype of system command is:
int system(const char *command);
and it returns the exit code of the command, that it executed (the shell script in your example). So you have simply use:
int status = system("./myscript.sh");
I have a requirement of developing a small dependency manager for a Qt based C++ application I am developing.
You should consider instead making a proper package for your (or some common) distribution (e.g. some .deb file for Debian or Ubuntu), because package managers do this job (handing dependency management) better than you reasonably could.
The return code of system(3) is actually the status code given by waitpid(2). Read about exit status of bash and shells. So if the last command executed (by /bin/sh -c started by system(3)) crashed with a SIGSEGV (see signal(7)...) you could use WIFSIGNALED then WTERMSIG
I guess that some program run by your ./myscript.sh crashed badly.
You might consider using the shell trap builtin in your script to handle that.

Qt Creator - Code is running but I get an error message from the IDE

As soon as I run my code (note that I'm using C only, no QT and no C++) I get the following message from the application output inside the IDE:
Cannot obtain a handle to the inferior: The parameter is incorrect.
When I delete the makefiles and debug/release folders it's running but after some time I still get the error. It's not that much of a problem though, the code runs and everything is fine but this error pops up and it's quite annoying.
The content of the .pro file is:
TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt
QMAKE_CC = gcc -std=c99
SOURCES += main.c
Thanks in advance!
edit: I have added C++ tag, because this error occurs also for C++ console application as in my case.
I have met same problem. Tips and advices on forums are rather clueless, so I investigated problem myself and I have found that it's a bug in QtCreator.
There is dirty little program called qtcreator_process_stub. Whenever you run your program within IDE, IDE first runs qtcreator_process_stub and passes your program name as parameter (among some other parameters). qtcreator_process_stub then starts your program as separate process and prints its PID (and on windows also thread id). Information is printed to the pipe and then it is read by ConsoleProcess::readStubOutput(), which is part of Utils.dll library used by QtCreator.
The problem occurs when "inferior" process (your application) finishes execution before whole communication has been processed. ConsoleProcess::readStubOutput() attempts to use OpenProcess() on non-existing process with closed handle. OpenProcess() fails hence error "Cannot obtain a handle to the inferior: The parameter is incorrect.". Whole error is not handled very gently (Uhm, and now what?)... :-/
Solution:
When you add some user input action, pause, sleep, delay or just some loops, so that execution of your application is a bit longer error vanishes. There is enough time for ConsoleProcess::readStubOutput() to execute OpenProcess(), before your application quits. So as a workaroud I suggest to do that until the bug is fixed.
I got the same error repeatedly while working on a C++ project in Qt. I was able to solve it by copying one of the shared libraries(.dll) I was using in to the build folder.
So, if you are using any shared external libraries that are needed at runtime, make sure they are in the builds folder.