lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Fri, Mar 23, 2012 at 2:20 AM, William Ahern
<william@25thandclement.com> wrote:
> There's no easy way around this. The C standard doesn't provide a
> thread-safe version of strerror, not even the new C11 standard which
> provides threading. See section 7.23.6.2 of C11.

Yes, that was my conundrum (I'm facing the same question in my own
library, which is why I asked).  There's no easy way around it, but if
using strerror() were actively dangerous then the only safe choice
would be not to use it at all.  It would be unfortunate to give up
this functionality.

Basically I was hoping someone would say something like "I've looked
into this, and no modern platform will ever crash due to strerror
races."  :)

> IMO, this is mostly  a quality of implementation issue. Any implementation
> worth its salt should either return static, constant strings (at least for
> the known errnos), or use thread-local-storage for its buffers.

Apple's libc doesn't:
http://opensource.apple.com/source/Libc/Libc-763.12/string/strerror-fbsd.c

And the following program aborts rapidly (0-150 iterations) on OS X
(but not Linux):

#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>

void loop(int num) {
  char expected[80];
  int count = 0;
  strerror_r(num, expected, sizeof(expected));
  while (1) {
    if (strcmp(expected, strerror(num))) {
      fprintf(stderr, "Failed after %d interations\n", count);
      abort();
    }
    count++;
  }
}

void *thread(void *arg) { loop(1); }

int main() {
  pthread_t th;
  pthread_create(&th, NULL, &thread, NULL);
  loop(2);
  return 0;
}

Josh