# dlopen error



## jrm@ (Apr 14, 2016)

I'm working on porting a C++ application to FreeBSD.  It's compiling, but a call to dlopen() is failing.  Here's a code snippet.

```
static void *lib=NULL;
lib=dlopen(filename,RTLD_NOW);

const char* blah;
if(blah=dlerror()) {
    info(filename);
    cout << blah << "\n";
}
```
The output is:

```
/home/jrm/cold/lib/cold/libCode61.so.1.0.0
Invalid shared object handle 0x802045cd0
```
The library name is correct and has permissions -rwxr-xr-x.
I can post truss, nm, or objdump output if it's helpful.


----------



## zirias@ (Apr 14, 2016)

Well, dlopen(3) says that dlopen() returns `NULL` on error and that dlerror() returns the last error that occured during any dl*() call. Looking at the your code snippet, dlerror() is called without checking dlopen()'s return value. Did you check it is indeed `NULL`? If not, the output could be bogus, caused by some earlier call to a dl*() function.

Suggested code:
	
	



```
static void *lib=NULL;
lib=dlopen(filename,RTLD_NOW);

const char* blah;
if(!lib && blah=dlerror()) {
    info(filename);
    cout << blah << "\n";
}
```


----------



## jrm@ (Apr 15, 2016)

Thank you Zirias!  The call to dlopen() is in fact not returning NULL.  I'm not clear why dlerror() is not returning NULL though, because there is no previous error AFICT.  I'm curious why this didn't cause problems upstream because the Linux man page says the same about dlopen() and dlerror().   I'll investigate that one at a later time.   Staring at this (messy) code for hours has numbed my brain a bit and I missed this obvious one.  Thanks again.


----------



## zirias@ (Apr 15, 2016)

Yeah messy code is messy ... this is very hypothetical, but maybe dlerror() on FreeBSD relies more on the user to actually follow the contract than the Linux version does? So that calling it when no error condition is actually met could lead to false positives? Good luck porting!


----------



## SirDice (Apr 15, 2016)

jrm said:


> The library name is correct and has permissions -rwxr-xr-x.


Libraries don't need execute permissions.


----------



## jrm@ (Apr 15, 2016)

SirDice said:


> Libraries don't need execute permissions.


I guess the developer was creative with the install flags.  I just listed the permissions to confirm they were readable.


----------



## zirias@ (Apr 15, 2016)

They don't need it, but it's common practice to install them +x because on some systems (*), they _do_ need it -- and it doesn't hurt. Some people over at GNU even get creative with that, try the command `/lib/`cc -dumpmachine`/libc.so.6` on a Linux box 

(*) AFAIK, Windows is one of them


----------

