Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to call dlclose(NULL)?

I experience a crash when I pass a null pointer to dlclose.

Should I check for null before calling dlclose?

POSIX tells nothing about this: http://pubs.opengroup.org/onlinepubs/7908799/xsh/dlclose.html

Is it undefined behaviour or a bug in dlclose implementation?

like image 868
Vanuan Avatar asked Jul 10 '12 12:07

Vanuan


3 Answers

This is tricky. POSIX states that

if handle does not refer to an open object, dlclose() returns a non-zero value

from which you could infer that it should detect, for an arbitrary pointer, whether that pointer refers to an open object. The Linux/Glibc version apparently does no such check, so you'll want to check for NULL yourself.

[Aside, the Linux manpage isn't very helpful either. It's quite implicit about libdl functions' behavior, deferring to POSIX without very clearly claiming conformance.]

like image 81
Fred Foo Avatar answered Nov 18 '22 04:11

Fred Foo


It also says nothing about being accepting a NULL and not crashing. We can assume from your test that it doesn't do an explicit NULL check, and it does need to use the pointer somehow to perform the closing action … so there you have it.

like image 33
Asherah Avatar answered Nov 18 '22 04:11

Asherah


Following the malloc/free convention (1), it is a bug. If it follows the fopen/fclose convention (2) it is not. So if there is a bug, it is in the standard because it lacks convention for dealing with zombies.

  • Convention (1) works well with C++11 move semantics
  • Convention (2) leaves more responsibility to the caller. In particular, a dtor must explicitly check for null if a move operation has been done.

I think this is something that should be revised for an upcoming POSIX revision in order to avoid confusion.


Update

I found from this answer https://stackoverflow.com/a/6277781/877329, and then reading man pthread_join that you can call pthread_join with an invalid tid, supporting the malloc/free convension. Another issue I have found with the dynamic loader interface is that it does not use the standard error handling system, but has its own dlerrorfunction.

like image 1
user877329 Avatar answered Nov 18 '22 04:11

user877329