What's wrong with this code?

Dan Nelson dnelson at allantgroup.com
Tue Dec 13 06:07:59 UTC 2011

In the last episode (Dec 13), John Levine said:
> This tiny routine is in a .so loadable module I use.  (It's part of the
> mailfront SMTP daemon.)
> static const char* date_string(void)
> {
>   static char datebuf[64];
>   time_t now = time(0);
>   struct tm* tm = gmtime(&now);
>   strftime(datebuf, sizeof datebuf - 1, "%d %b %Y %H:%M:%S -0000", tm);
>   return datebuf;
> }
> I was getting bogus dates.  Running it under GDB, time() is returning 1,
> -and setting errno to 22, which is EINVAL.  Changing the call to
> time to time(NULL) or time(&now) made no difference.

The manpage says that time() can fail for any of the reasons described in
gettimeofday(2), but time() actually calls clock_gettime(CLOCK_SECOND),
which technically could return EINVAL if the first argument isn't a valid
clock_id.  CLOCK_SECOND is valid, though, so in practice it should never
fail with EINVAL.  You could try adding a printf to
sys/kern/kern_time.c:kern_clock_gettime() to see if it's really failing
> I changed it to a call to gettimeofday(), which works fine.  But what
> could the problem have been?  When I splice this routine into a tiny test
> program that calls it and prints out the result, it works fine.
> The obvious problem, since it's in a .so, is that it's linking to
> something other than the system library time() function, but I did an nm
> on the .so, and it said this, which sure looks like the system time()
> function to me:
>                  U time@@FBSD_1.0
> Setting a breakpoint in gdb gets a complaint about trying to set a
> breakpoint in /lib/libc.so.7.

Setting a breakpoint in a llibc should work fine, since time() is a regular
function and not a syscall stub.  Have you built a libc with debugging
symbols? ( easy way: add DEBUG_FLAGS=-g to the top of
/usr/src/lib/libc/Makefile, and run "make obj && make clean && make depend
&& make && make install" in that directory )
> Any ideas what the problem was?

	Dan Nelson
	dnelson at allantgroup.com

More information about the freebsd-questions mailing list