Problems with ld, libc, and "struct stat"
mafsys1234 at gmail.com
Wed Oct 16 11:45:37 UTC 2019
On 16/10/2019 10:15 pm, Jan Behrens wrote:
> On Wed, 16 Oct 2019 09:18:52 +0200
> David Demelier <markand at malikania.fr> wrote:
>> Le 15/10/2019 à 20:44, Jan Behrens a écrit :
>>> I stumbled across a weird problem related stat() that (according to my
>>> research) seems to be related to an update of the "struct stat"
>>> C-structure in recent Kernel versions.
>>> stat("testlib.c", &sb);
>> Please test the result of stat otherwise sb is left untouched (so all
>> member undefined).
> You are right, of course (this was just a quick and dirty demonstration).
Initialize sb - it's also quick and dirty to do and prevents accessing memory with garbage in it.
It's always a good habit to get into, regardless.
>>> But when I make a shared library like this, I get a different result:
>>> % ld -shared -o testlib.so testlib.o
>> Hmm, we usually never call the linker itself when creating shared libraries.
>> Try instead: cc -shared -o testlib.so testlib.o
> Thank you very much; I tried that, and it works properly:
> % cc -Wall -c -fPIC -o testlib.o testlib.c
> % cc -shared -o testlib.so testlib.o
> % cc -Wall -o testprog `pwd`/testlib.so testprog.c
> % ./testprog
> Size of testlib.c is 168 bytes.
> I will from now on use cc instead of ld to create shared libraries.
> I still wonder though if there is any documentation on this behavior
> (and where to find it), whether it's FreeBSD related or LLVM related.
> It feels a bit scary that using "ld" to make a shared library can
> result in weird runtime behavior without even raising a warning.
ld is doing what you told it, which is not much other than it's a shared library it's linking to.
If you're using ld then you need to specify -L or -rpath. How else is it to know where it's shared libraries are?
If you examined the runtime with gdb (or lldb) you would immediately answer your question. It's your best tool to answer lots of these types of questions.
> Do you know any link where I find a more detailed explanation about why
> I need to use "cc" instead of "ld" to create shared libraries? I assume
> that "cc" adds the necessary options to "ld" that are otherwise
> missing. But I don't see where this is documented.
This explains it succinctly:
(apart from the linux-isms)
Also this, in more detail:
More information about the freebsd-questions