Problems with ld, libc, and "struct stat"

Jan Behrens jbe-mlist at magnetkern.de
Tue Oct 15 18:44:09 UTC 2019


Hello,

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.

Consider the following two files.

testlib.c:
#include <sys/stat.h>
#include <stdio.h>
void testfunc() {
  struct stat sb;
  stat("testlib.c", &sb);
  printf("Size of testlib.c is %i bytes.\n", (int)sb.st_size);
}

testprog.c:
extern void testfunc(void);
int main(int argc, char **argv) {
  testfunc();
  return 0;
}

Now I run:

% cc -Wall -c -fPIC -o testlib.o testlib.c
% cc -Wall -o testprog testlib.o testprog.c
% ./testprog 
Size of testlib.c is 168 bytes.

But when I make a shared library like this, I get a different result:

% ld -shared -o testlib.so testlib.o
% cc -Wall -o testprog `pwd`/testlib.so testprog.c
% ./testprog
Size of testlib.c is 394655000 bytes.

This result is obviously wrong. Note that I did not get any compiler or
linker warnings or errors; yet there happens a bad error during runtime!

With several attempts of trial and error, I figured out that the
problem does not appear when appending "-L/usr/lib -lc" to the ld call
when linking the shared library:

% ld -shared -o testlib.so testlib.o -L/usr/lib -lc
% cc -Wall -o testprog `pwd`/testlib.so testprog.c
% ./testprog
Size of testlib.c is 168 bytes.

Can anyone tell me why is that and if I am supposed to always add
"-L/usr/lib -lc" when creating an *.so file?

Is this maybe a bug in FreeBSD or ld? Or am I using the linker in a
wrong way?


Kind regards,
Jan Behrens


More information about the freebsd-questions mailing list