Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C11 thread-safety with respect to functions that return pointers to static buffers

Consider functions like localtime in the C standard library which return a pointer to a (historically) static buffer. Does C11 make these buffers thread-local?

Per 7.1.4 in C11:

Unless explicitly stated otherwise in the detailed descriptions that follow, library functions shall prevent data races as follows: A library function shall not directly or indirectly access objects accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function's arguments. A library function shall not directly or indirectly modify objects accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function's non-const arguments. Implementations may share their own internal objects between threads if the objects are not visible to users and are protected against data races.

Consider for example localtime. The struct tm to which its return value points does not seem to qualify as an "internal object" since it's accessible to the caller, so it seems that an invocation of localtime in another thread may not clobber the result previously returned in the first thread. This would imply that localtime needs to use a different buffer for each thread.

However, nowhere does the standard specify an end to the lifetime of the object whose address is returned, and I see no reason a program continuing to use this struct tm after the calling thread terminates would be invalid. Thus, the object cannot have thread storage duration.

The only way I can find that an implementation could meet all the requirements is to leak memory all over the place, which is surely not what's intended. Am I missing something obvious, or is C11's treatment of thread-safety with respect to legacy interfaces really this poorly thought-out?

like image 665
R.. GitHub STOP HELPING ICE Avatar asked Feb 04 '12 05:02

R.. GitHub STOP HELPING ICE


1 Answers

... unless explicitly stated otherwise: The introductory chapter of 7.27.3 Time conversion functions explicitly states that these functions are not supposed to avoid data races. (As is the case for many other library functions.)

There are derived function with _s suffix in the bounds checking extension in normative annex K that are designed to avoid race conditions.

like image 133
Jens Gustedt Avatar answered Oct 02 '22 18:10

Jens Gustedt