Bug 47843

Summary: Non-threadsafe use of memory pool by apr_thread_pool_create() and thread_pool_func()
Product: APR Reporter: Alex Korobka <akorobka>
Component: APR-utilAssignee: Apache Portable Runtime bugs mailinglist <bugs>
Status: RESOLVED FIXED    
Severity: critical Keywords: PatchAvailable
Priority: P2    
Version: HEAD   
Target Milestone: ---   
Hardware: PC   
OS: Linux   
Attachments: Lock thread pool mutex around the call to apr_thread_create

Description Alex Korobka 2009-09-15 10:42:36 UTC
When creating a thread pool apr_thread_pool_create() calls apr_thread_create() without acquiring the corresponding thread pool mutex.

while (init_threads) {
        rv = apr_thread_create(&t, NULL, thread_pool_func, *me, (*me)->pool);
        ...   
}

apr_thread_create() proceeds to allocate and initialize its internal objects from the pool before spawning a thread,

    (*new) = (apr_thread_t *)apr_pcalloc(pool, sizeof(apr_thread_t));
    ...
    (*new)->td = (pthread_t *)apr_pcalloc(pool, sizeof(pthread_t));
    ...
    (*new)->data = data;
    (*new)->func = func;
    ...
    stat = apr_pool_create(&(*new)->pool, pool);
    ...
    if ((stat = pthread_create((*new)->td, temp, dummy_worker, (*new))) == 0) {
    ...

The new thread starts in dummy_worker(), which passes control to the thread_pool_func(). The latter acquires the thread pool mutex and allocates apr_thread_list_elt object from the same memory pool. If apr_thread_pool_create() needs to start more than one initial thread, the memory pool may end up being used concurrently by two threads, one executing apr_thread_create() and another executing thread_pool_func(). This may result in data corruption as APR memory pools are not thread-safe.

Proposed fix - hold thread pool mutex around the call to apr_thread_create() in apr_thread_pool_create().
Comment 1 William A. Rowe Jr. 2009-09-24 22:17:47 UTC
Suggestion, sometimes complex requests are best handled with an actual
patch which illustrates the fix.  Agreed there is an issue, and I don't
want to move this off my plate, but can you offer the appropriate
correction in the form of an attached diff and mark this bug with the
keyword "PatchAvailable" please?
Comment 2 Alex Korobka 2009-09-25 09:42:44 UTC
Created attachment 24312 [details]
Lock thread pool mutex around the call to apr_thread_create
Comment 3 Jeff Trawick 2010-09-27 08:01:59 UTC
Thanks for the patch!
It has been committed to apr trunk as well as apr-util branches 1.3.x and higher.