printf() doesn't work in source code? - c++

I'm trying to modify VLFeat source code in particular the function vl_vlad_code in this file. Now, since it is the first time that I edit the source code of such a library, I started with something simple, like printing an Hello World! at the beginning of the fucntion:
void
vl_vlad_encode (void * enc, vl_type dataType,
void const * means, vl_size dimension, vl_size numClusters,
void const * data, vl_size numData,
void const * assignments,
int flags)
{
printf("Hello World!");
...
Then (following this document convention):
I removed the binary code with rm -rf VLFEATROOT/bin
I recompiled the library with make in VLFEATROOT (with no errors)
However, when I call vl_vlad_code from my application nothing is printed. Notice that the library works fine in my C++ application, it just "ignores" my changes.
Just for completeness, I use Ubuntu 16.04 and this are the compiling options regarding VLFeat that I use in my Eclipse CDT project:
... -I/home/luca/vlfeat ... -L/home/luca/vlfeat/bin/glnxa64 ... -lvl
UPDATE:
Following suggestions in the comments, I tried to write something to a file in this way:
void
vl_vlad_encode (void * enc, vl_type dataType,
void const * means, vl_size dimension, vl_size numClusters,
void const * data, vl_size numData,
void const * assignments,
int flags)
{
FILE *f = fopen("/home/luca/file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);
And no file is created!

It is possible that when you run the application you are actually linking with a system-wide installed library. As a test, try adding the directory where you built the library to the LD_LIBRARY_PATH environment variable then run your program.
From the command line you could do:
export LD_LIBRARY_PATH=/path/to/your/lib:${LD_LIBRARY_PATH}
If you are using an IDE, you should set the variable inside of its environment settings.
Paths in this variable will be searched before your system libs are searched.
You can always find out exactly where the libraries your executable is linking to are located by running:
ldd /path/to/your/executable

The problem was a copy of libvl.so in /usr/loca/lib. After deleting it the problem was solved and the message is correctly printed.

Related

Can't step into function during debugging session in Clion

I am trying out CLion as new IDE and I have this odd problem with debugging. I am trying to step into function cropImage (not method) but all I can get when stepping into is to get to constructor of CRect.
int main ( void )
{
cropImage( "./sample/input_00.raw", "./output_00.raw", CRect(1,2,3,4), ENDIAN_LITTLE);
return 0;
}
Also, when I try to put breakpoint inside function cropImage() it just get ignored. What am I doing wrong? I think this is pretty much basic function of debugger to step into function, not only methods...
I am using CLion on Linux with GDB and g++.
EDIT:
Just to clarify the code and issue here is how the file main.cpp looks
bool cropImage ( const char * srcFileName,
const char * dstFileName,
const CRect & rc,
int byteOrder )
{
// Open streams, create objects, do stuff
}
int main ( void )
{
cropImage( "./sample/input_00.raw", "./output_00.raw", CRect(1,2,3,4), ENDIAN_LITTLE);
return 0;
}
Everything works from CLI ( using gdb on binary created from CLion ), it just that inside of IDE it ignores any breakpoint inside cropImage() function.
So I find this workaround. Ref: https://intellij-support.jetbrains.com/hc/en-us/community/posts/206606815-Integrated-GDB-and-a-frame-not-available-error
Seems like it's issue on ArchLinux. Even though CLion detects gdb automatically without problems, frames doesn't exist and manually specifying path to gdb (/usr/bin/gdb) fixed this.

Visual Studio 2010 debugger points to wrong line

The debugger in Visual Studio 2010 is recently pointing at the wrong lines and/or skipping lines and I have no idea why this is. This is a CUDA project and only happens in CUDA files. I've noticed the following:
It always happens at the same part of the program.
The lines it points to are always the same, i.e. not random.
Putting extra code after the culprit lines changes which lines it points to.
It only happens in .cu-files. Moving the code to a .cpp-file does not recreate the problem.
What I have tried:
Clean and rebuilt the solution.
Install SP1 for MSVC10 and do all possible updates via Windows Updates
Set the compiler to not use optimizations in debug mode for both C/C++ and CUDA C/C++
Manually delete all created files and then rebuild from the solution folder.
Deleting the folder C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
Recreating the solution only using the source files.
Disabling my extensions.
I've managed to reduce the code to the following which might reproduce the problem. Mind that this code has to be inside a .cu-file and most probably needs to be compiled with the cuda compiler for C/C++. Including boost is not really necessary, but this example does show what problems I'm having. A shorter example is at the back.
#include <boost/numeric/ublas/matrix.hpp>
using boost::numeric::ublas::matrix;
struct foo {
foo() : mat(NULL) {}
matrix<float>* mat;
};
bool func(foo *data) {
bool status; // <- skipped line
status = false;
if (status) {
std::cout << "test\n";
return (status); // <- error reported here
}
int size = data->mat->size1(); // instead of here
return status;
}
int main(int args, char* argv[]) {
func(NULL); // force error by passing NULL pointer
return 0;
}
Does anyone have any idea how to solve this or how this could be happening? It's pretty annoying having to debug this way.
Shorter example only showing the skipping lines. No external libraries necessary.
bool func() {
bool status; // <- skipped line
status = false;
return status;
}
int main(int args, char* argv[]) {
func();
return 0;
}
Since the program only contains CPU instructions and variable declarations of types that have no construction contain no instructions, the debugger will not stop there. It just executes instructions and then uses the debugging information that the compiler provided to find the relevant line of source code.

How to use dlsym reliably when you have duplicated symbols?

Good evening, I'm currently working on a Plugin system in C++/Linux based on the Plux.net model.
To keep it simple, I basicly declare a symbol (lets call it pluginInformation) with extern C (to unmangle) and my plugin manager look for that symbol in the pre configured imports (.so).
The thing is that the main application declares the same symbol, not only that but any dependency it have may have the symbol aswell. (since in this pluginInformation, modules can publish plugs and/or slots).
So when my PluginManager starts, it first try to find the symbol in the main program (passing NULL to dlopen), then it tries to find the symbol in any of its dependencies (using dl_iterate_phdr). And last it will dlopen a set of configure imports (it will read the path of the .so that the user configured, dlopen them and finally dlsym the pluginInformation symbol).
The collection of pluginInformation found in all the modules is used then to build the extension three.
If I declare the symbol in the main program and load the imports using dlopen, it works (as long as I pass the flag RTLD_DEEPBIND when dlopening the imports).
But for the application dependencies I dont have the option of passing the flag (I can but it doesnt do anything) since this .sos were loaded at the start up of the application.
Now when I try to use any of the symbols I got from the dependencies (the ones loaded at start up) I get a segmentation fault. I assume the problem is that I have several symbols with the same name in the symbol table, the weird thing is that it seems to correctly identify that there are several symbols and it even gives me the correct path of the .so where the symbol is declared, but as soon as I access the symbol a segmentation fault occurs. If I only declare the symbol in the main program or in one of the dependencies everything works correctly.
How can I manage duplicate symbols between the main program and the strat up imports with dlsym?.
I have been thinking in keep the mangling and then just try to find my symbol pasring the symbol table, but im not sure this is even possible (listing all the symbols in a module programmatically).
PD: Sorry I didnt post any code, but im not at home right now, I hope the description of what im trying to do is clear enough, if not I can post some code tomorrow.
Here is an alternate approach.
The application itself exports one or more plugin item registration functions. For example:
int register_plugin_item(const char *const text,
const char *const icon,
void (*enter)(void *),
void (*click)(void *),
void (*leave)(void *),
void *data);
Per registered item, there are two string slots (text and icon), three function slots (enter, click, and leave), and an opaque reference that is given to the functions as a parameter when called.
(Note that you'll need to use the -rdynamic compiler option when compiling the main application (the object file implementing the above function), to make sure the linker adds the register_plugin_item symbol to the dynamic symbol table.)
Each plugin calls the register_plugin_item() function for each of the items it wants, in a constructor function (that is automatically run at library load time). It is possible, and often useful, for the function to first examine the environment it runs in to determine which features to register, or which optimized variants of functions to use for each plugin item.
Here is a trivial example plugin. Note how all the symbols are static, so that the plugin does not pollute the dynamic symbol table, or cause any symbol conflicts.
#include <stdlib.h>
#include <stdio.h>
extern int register_plugin_item(const char *const,
const char *const,
void (*enter)(void *),
void (*click)(void *),
void (*leave)(void *),
void *);
static void enter(void *msg)
{
fprintf(stderr, "Plugin: Enter '%s'\n", (char *)msg);
}
static void leave(void *msg)
{
fprintf(stderr, "Plugin: Leave '%s'\n", (char *)msg);
}
static void click(void *msg)
{
fprintf(stderr, "Plugin: Click '%s'\n", (char *)msg);
}
static void init(void) __attribute__((constructor));
static void init(void)
{
register_plugin_item("one", "icon-one.gif",
enter, leave, click,
"1");
register_plugin_item("two", "icon-two.gif",
enter, leave, click,
"2");
}
The above plugin exports two items. For testing, create at least a couple of variants of the above; you will see that there are no symbol conflicts even if the plugins use same (static) variables and function names.
Here is an example application that loads the specified plugins, and tests each registered item:
#include <stdlib.h>
#include <dlfcn.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
struct item {
struct item *next;
const char *text;
const char *icon;
void *data;
void (*enter)(void *);
void (*leave)(void *);
void (*click)(void *);
};
static struct item *list = NULL;
int register_plugin_item(const char *const text,
const char *const icon,
void (*enter)(void *),
void (*click)(void *),
void (*leave)(void *),
void *data)
{
struct item *curr;
curr = malloc(sizeof *curr);
if (!curr)
return ENOMEM;
curr->text = text;
curr->icon = icon;
curr->data = data;
curr->enter = enter;
curr->leave = leave;
curr->click = click;
/* Prepend to list */
curr->next = list;
list = curr;
return 0;
}
int main(int argc, char *argv[])
{
int arg;
void *handle;
struct item *curr;
if (argc < 2 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
fprintf(stderr, "\n");
fprintf(stderr, "Usage: %s [ -h | --help ]\n", argv[0]);
fprintf(stderr, " %s PLUGIN.so ... \n", argv[0]);
fprintf(stderr, "\n");
fprintf(stderr, "Please supply full plugin paths, unless\n");
fprintf(stderr, "the plugins reside in a standard library directory,\n");
fprintf(stderr, "or in a directory listed in LD_LIBRARY_PATH.\n");
fprintf(stderr, "\n");
return 1;
}
for (arg = 1; arg < argc; arg++) {
handle = dlopen(argv[arg], RTLD_NOW);
if (handle != NULL)
fprintf(stderr, "%s: Loaded.\n", argv[arg]);
else
fprintf(stderr, "%s.\n", dlerror());
/* Note: We deliberately "leak" the handle,
* so that the plugin is not unloaded. */
}
for (curr = list; curr != NULL; curr = curr->next) {
if (curr->text)
printf("Item '%s':\n", curr->text);
else
printf("Unnamed item:\n");
if (curr->icon)
printf("\tIcon is '%s'\n", curr->icon);
else
printf("\tNo icon\n");
if (curr->data)
printf("\tCustom data at %p\n", curr->data);
else
printf("\tNo custom data\n");
if (curr->enter)
printf("\tEnter handler at %p\n", curr->enter);
else
printf("\tNo enter handler\n");
if (curr->click)
printf("\tClick handler at %p\n", curr->click);
else
printf("\tNo click handler\n");
if (curr->leave)
printf("\tLeave handler at %p\n", curr->leave);
else
printf("\tNo leave handler\n");
if (curr->enter || curr->click || curr->leave) {
printf("\tTest calls:\n");
if (curr->enter)
curr->enter(curr->data);
if (curr->click)
curr->click(curr->data);
if (curr->leave)
curr->leave(curr->data);
printf("\tTest calls done.\n");
}
}
return 0;
}
If the application is app.c, and you have plugins plugin-foo.c and plugin-bar.c, you can compile them using e.g.
gcc -W -Wall -rdynamic app.c -ldl -o app
gcc -W -Wall -fpic -c plugin-foo.c
gcc -shared -Wl,-soname,plugin-foo.so plugin-foo.o -o plugin-foo.so
gcc -W -Wall -fpic -c plugin-bar.c
gcc -shared -Wl,-soname,plugin-bar.so plugin-bar.o -o plugin-bar.so
and run using e.g.
./app --help
./app ./plugin-foo.so
./app ./plugin-foo.so ./plugin-bar.so
Note that if the same plugin is defined more than once, the constructor is only executed once for that library. There will be no duplicate registrations.
The interface between the plugins and the application is completely up to you. In this example, there is only one function. A real application would probably have more. The application can also export other functions, for example for the plugin to query application configuration.
Designing a good interface is a whole different topic, and definitely deserves at least as much thought as you put in the implementation.
The Plux.NET plugin platform allows plugins to export their own slots, too. This alternate approach allows that in many ways. One of them is to export a plugin registration function -- that is, for registering plugins instead of individual items -- that takes a function pointer:
int register_plugin(const char *const name,
int (*extend)(const char *const, ...));
If the plugin provides slots, it provides its own registration function as the extend function pointer. The application also exports a function, for example
int plugin_extend(const char *const name, ...);
that the plugins can use to call other plugins' registration functions. (The implementation of plugin_extend() in the main application involves searching for a suitable extend function already registered, then calling it/them.)
Implementation-wise, allowing plugins to export slots complicates implementation quite a bit. In particular, when and in which order should the slots exported by the plugins become available? Is there a specific order in which plugins must be loaded, to make sure all possible slots are exported? What happens if there is a circular dependency? Should plugins specify which other plugins they rely on before the registrations commence?
If each plugin is a separate entity that does not export any slots of its own, only plugs into main application slots, you avoid most of the complexity in the implementation.
The order in which registered items are examined is a detail you probably need to think about, though. The above example program uses a linked list, in which the items end up in reverse order compared to the registration order, and registration order is the same as the order in which the plugin file names are first specified on the command line. If you have a plugin directory, which is automatically scanned (using e.g. opendir()/readdir()/dlopen()/closedir() loop), then the plugin registration order is semi-random (depending on the filesystem; usually changing only when plugins are added or removed).
Corrections? Questions? Comments?

ibmemcached Linking Error: undefined reference to `memcached_exist'

I am trying to write a sample code using libmemcached c/c++ client version (0.53)
gcc -o test test.c -I/home/libmemcached/include -L/home/libmemcached/lib -lmemcached -lmemcachedutil
However i get an error
/tmp/ccoaToYP.o: In function main':
test.c:(.text+0x255): undefined reference tomemcached_exist'
Has anyone come across this issue ? I cannot use version higher than 0.53 (basically any 1.0) due to limitation with installed gcc. I see that this command was added for 0.53.
Also, The path and ld_library_path are straightforward too.
PATH is set with /bin:/sbin:/usr/bin:/usr/sbin:/usr/bin/X11:/usr/sbin.
LD_LIBRARY_PATH is set with /home/libmemcached/lib:/usr/lib:/usr/lib64:/lib
$ nm libmemcached.so | grep -i memcached_exist
00014bc2 T _Z15memcached_existP12memcached_stPKcj
00014b06 T _Z22memcached_exist_by_keyP12memcached_stPKcjS2_j
$
If i comment out the memcached_exist call, rest of code compiles and executes just fine.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <libmemcached/memcached.h>
int main(int argc, char *argv[])
{
memcached_server_st *servers = NULL;
memcached_st *memc;
memcached_return rc;
char *key= "keystring";
char *value= "keyvalue";
uint32_t flags;
char return_key[MEMCACHED_MAX_KEY];
size_t return_key_length;
char *return_value;
size_t return_value_length;
memc= memcached_create(NULL);
servers= memcached_server_list_append(servers, "localhost", 11211, &rc);
rc= memcached_server_push(memc, servers);
if (rc == MEMCACHED_SUCCESS)
fprintf(stderr,"Added server successfully\n");
else
fprintf(stderr,"Couldn't add server: %s\n",memcached_strerror(memc, rc));
rc= memcached_set(memc, key, strlen(key), value, strlen(value), (time_t)0, (uint32_t)0);
if (rc == MEMCACHED_SUCCESS)
fprintf(stderr,"Key stored successfully\n");
else
fprintf(stderr,"Couldn't store key: %s\n",memcached_strerror(memc, rc));
return_value= memcached_get(memc, key, strlen(key), &return_value_length, &flags, &rc);
if (rc == MEMCACHED_SUCCESS)
{
fprintf(stderr,"Key %s returned %s\n",key, return_value);
}
rc = memcached_exist(memc, key, strlen(key));
fprintf(stderr," Error Code: %s\n",memcached_strerror(memc, rc));
return 0;
}
Thanks
Antony
If you don't want to compile as C++, you can always call the mangled name directly. If you want this code to be reusable and to be able to upgrade the libraries easily, etc, you shouldn't do that. For a more extensible solution, I'll add to H2CO3's answer.
If you want to for some reason keep all your main source compiled as C, you can create a .cpp file that has stubs that call the C++ library functions. For example:
// libraries.cpp
//
// (includes needed to memcached lib call and types)
extern "C" memcached_return memcached_exist(memcached_st *memc, char *key, size_t len)
{
return memcached_exist(memc, key, len);
}
Then you can compile libraries.cpp and link against the memcached libs using g++ to a libraries.o and link against that on your gcc line.
Name mangling. The shared object file contains mangled C++ function (method?) names, while your code is compiled as C, containing the non-mangled name memcached_exist. Try compiling your file as C++.

Make local c library function accessable globally

I'm using a C library called GLC to record my OpenGL buffer programmatically.
GLC listens to key presses, which is not really a nice solution to trigger programmatically.
Therefore I want to execute the recording from GLC via a function call in my software.
My C++ software is linking to the library which includes the desired function start_capture(). Via nm I can see this function is local, marked with a lower case t.
Since it has to be global to access it in my software I want to recompile the library (which I've already done). But I have no idea what to change to make it accessible....
Here is the declaration from start_capture(), in the header file lib.h
...
__PRIVATE int start_capture(); // No idea where the __PRIVATE is coming from
...
This is the definition/implementation of the start_capture() function in the main.c:
int start_capture()
...
return ret;
}
And this is my dlopen to get the function:
void *handle_so;
void (*start_capture_custom)();
char *error_so;
handle_so = dlopen("/home/jrick/fuerte_workspace/sandbox/Bag2Film/helper/libglc-hook.so", RTLD_LAZY);
if (!handle_so)
{
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
dlerror(); /* Clear any existing error */
start_capture_custom = (void (*)())dlsym(handle_so, "start_capture");
if ((error_so = dlerror()) != NULL)
{
fprintf(stderr, "%s\n", error_so);
exit(1);
}
start_capture_custom();
dlclose(handle_so);
start_capture();
So what am I supposed to change to access this via the library file?
I hope this was enough description to make the problem clear. If not, I'll answer as fast as I can.
__PRIVATE is a #define for a GCC extension to hide a symbol. See https://github.com/nullkey/glc/blob/master/src/glc/common/glc.h#L60 for the definition and http://gcc.gnu.org/wiki/Visibility for more info about the GCC extension.
https://stackoverflow.com/a/12011284/2146478 provides a solution that will unhide symbols without recompiling. You would want to do something like:
$ objcopy --globalize-symbol=start_capture /path/to/your/lib.a /path/to/new/lib.a