threads.c 15 KB
Newer Older
1 2 3 4 5 6 7 8 9
/**
 * threads.c: set of generic threading related routines 
 *
 * See Copyright for the status of this software.
 *
 * Gary Pennington <Gary.Pennington@uk.sun.com>
 * daniel@veillard.com
 */

10
#define IN_LIBXML
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#include "libxml.h"

#include <string.h>

#include <libxml/threads.h>
#include <libxml/globals.h>

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_PTHREAD_H
#include <pthread.h>
#endif
30

31 32
#ifdef HAVE_WIN32_THREADS
#include <windows.h>
33
#ifndef HAVE_COMPILER_TLS
34 35 36
#include <process.h>
#endif
#endif
37 38 39 40 41

#if defined(SOLARIS)
#include <note.h>
#endif

42
/* #define DEBUG_THREADS */
43 44 45 46 47 48 49 50 51 52 53 54 55

/*
 * TODO: this module still uses malloc/free and not xmlMalloc/xmlFree
 *       to avoid some crazyness since xmlMalloc/xmlFree may actually
 *       be hosted on allocated blocks needing them for the allocation ...
 */

/*
 * xmlMutex are a simple mutual exception locks
 */
struct _xmlMutex {
#ifdef HAVE_PTHREAD_H
    pthread_mutex_t lock;
56
#elif defined HAVE_WIN32_THREADS
57
    HANDLE mutex;
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#else
    int empty;
#endif
};

/*
 * xmlRMutex are reentrant mutual exception locks
 */
struct _xmlRMutex {
#ifdef HAVE_PTHREAD_H
    pthread_mutex_t lock;
    unsigned int    held;
    unsigned int    waiters;
    pthread_t       tid;
    pthread_cond_t  cv;
73
#elif defined HAVE_WIN32_THREADS
74 75
    CRITICAL_SECTION cs;
    unsigned int count;
76 77 78 79 80 81 82 83 84
#else
    int empty;
#endif
};
/*
 * This module still has some internal static data.
 *   - xmlLibraryLock a global lock
 *   - globalkey used for per-thread data
 */
85

86 87
#ifdef HAVE_PTHREAD_H
static pthread_key_t	globalkey;
88
static pthread_t	mainthread;
89
static pthread_once_t once_control = PTHREAD_ONCE_INIT;
90
#elif defined HAVE_WIN32_THREADS
91 92 93 94
#if defined(HAVE_COMPILER_TLS)
static __declspec(thread) xmlGlobalState tlstate;
static __declspec(thread) int tlstate_inited = 0;
#else /* HAVE_COMPILER_TLS */
95
static DWORD globalkey = TLS_OUT_OF_INDEXES;
96
#endif /* HAVE_COMPILER_TLS */
97 98 99
static DWORD mainthread;
static int run_once_init = 1;
#endif /* HAVE_WIN32_THREADS */
100

101
static xmlRMutexPtr	xmlLibraryLock = NULL;
102
#ifdef LIBXML_THREAD_ENABLED
103
static void xmlOnceInit(void);
104
#endif
105 106

/**
107
 * xmlNewMutex:
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
 *
 * xmlNewMutex() is used to allocate a libxml2 token struct for use in
 * synchronizing access to data.
 *
 * Returns a new simple mutex pointer or NULL in case of error
 */
xmlMutexPtr
xmlNewMutex(void)
{
    xmlMutexPtr tok;

    if ((tok = malloc(sizeof(xmlMutex))) == NULL)
        return (NULL);
#ifdef HAVE_PTHREAD_H
    pthread_mutex_init(&tok->lock, NULL);
123
#elif defined HAVE_WIN32_THREADS
124
    tok->mutex = CreateMutex(NULL, FALSE, NULL);
125 126 127 128 129 130 131 132 133 134 135 136 137 138
#endif
    return (tok);
}

/**
 * xmlFreeMutex:
 * @tok:  the simple mutex
 *
 * xmlFreeMutex() is used to reclaim resources associated with a libxml2 token
 * struct.
 */
void
xmlFreeMutex(xmlMutexPtr tok)
{
139 140
    if (tok == NULL) return;

141 142
#ifdef HAVE_PTHREAD_H
    pthread_mutex_destroy(&tok->lock);
143
#elif defined HAVE_WIN32_THREADS
144
    CloseHandle(tok->mutex);
145 146 147 148 149 150 151 152 153 154 155
#endif
    free(tok);
}

/**
 * xmlMutexLock:
 * @tok:  the simple mutex
 *
 * xmlMutexLock() is used to lock a libxml2 token.
 */
void
156
xmlMutexLock(xmlMutexPtr tok)
157
{
158 159
    if (tok == NULL)
        return;
160 161
#ifdef HAVE_PTHREAD_H
    pthread_mutex_lock(&tok->lock);
162
#elif defined HAVE_WIN32_THREADS
163
    WaitForSingleObject(tok->mutex, INFINITE);
164 165 166 167 168 169 170 171 172 173 174
#endif

}

/**
 * xmlMutexUnlock:
 * @tok:  the simple mutex
 *
 * xmlMutexUnlock() is used to unlock a libxml2 token.
 */
void
175
xmlMutexUnlock(xmlMutexPtr tok)
176
{
177 178
    if (tok == NULL)
        return;
179 180
#ifdef HAVE_PTHREAD_H
    pthread_mutex_unlock(&tok->lock);
181
#elif defined HAVE_WIN32_THREADS
182
    ReleaseMutex(tok->mutex);
183 184 185 186
#endif
}

/**
187
 * xmlNewRMutex:
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
 *
 * xmlRNewMutex() is used to allocate a reentrant mutex for use in
 * synchronizing access to data. token_r is a re-entrant lock and thus useful
 * for synchronizing access to data structures that may be manipulated in a
 * recursive fashion.
 *
 * Returns the new reentrant mutex pointer or NULL in case of error
 */
xmlRMutexPtr
xmlNewRMutex(void)
{
    xmlRMutexPtr tok;

    if ((tok = malloc(sizeof(xmlRMutex))) == NULL)
        return (NULL);
#ifdef HAVE_PTHREAD_H
    pthread_mutex_init(&tok->lock, NULL);
    tok->held = 0;
    tok->waiters = 0;
207
    pthread_cond_init(&tok->cv, NULL);
208
#elif defined HAVE_WIN32_THREADS
209 210
    InitializeCriticalSection(&tok->cs);
    tok->count = 0;
211 212 213 214 215
#endif
    return (tok);
}

/**
216
 * xmlFreeRMutex:
217 218 219 220 221 222
 * @tok:  the reentrant mutex
 *
 * xmlRFreeMutex() is used to reclaim resources associated with a
 * reentrant mutex.
 */
void
223
xmlFreeRMutex(xmlRMutexPtr tok ATTRIBUTE_UNUSED)
224 225 226
{
#ifdef HAVE_PTHREAD_H
    pthread_mutex_destroy(&tok->lock);
227
#elif defined HAVE_WIN32_THREADS
228
    DeleteCriticalSection(&tok->cs);
229 230 231 232 233 234 235 236 237 238 239
#endif
    free(tok);
}

/**
 * xmlRMutexLock:
 * @tok:  the reentrant mutex
 *
 * xmlRMutexLock() is used to lock a libxml2 token_r.
 */
void
240
xmlRMutexLock(xmlRMutexPtr tok)
241
{
242 243
    if (tok == NULL)
        return;
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
#ifdef HAVE_PTHREAD_H
    pthread_mutex_lock(&tok->lock);
    if (tok->held) {
        if (pthread_equal(tok->tid, pthread_self())) {
            tok->held++;
            pthread_mutex_unlock(&tok->lock);
            return;
        } else {
            tok->waiters++;
            while (tok->held)
                pthread_cond_wait(&tok->cv, &tok->lock);
            tok->waiters--;
        }
    }
    tok->tid = pthread_self();
    tok->held = 1;
    pthread_mutex_unlock(&tok->lock);
261
#elif defined HAVE_WIN32_THREADS
262 263
    EnterCriticalSection(&tok->cs);
    ++tok->count;
264 265 266 267 268 269 270 271 272 273
#endif
}

/**
 * xmlRMutexUnlock:
 * @tok:  the reentrant mutex
 *
 * xmlRMutexUnlock() is used to unlock a libxml2 token_r.
 */
void
274
xmlRMutexUnlock(xmlRMutexPtr tok ATTRIBUTE_UNUSED)
275
{
276 277
    if (tok == NULL)
        return;
278 279 280 281 282 283 284 285 286
#ifdef HAVE_PTHREAD_H
    pthread_mutex_lock(&tok->lock);
    tok->held--;
    if (tok->held == 0) {
        if (tok->waiters)
            pthread_cond_signal(&tok->cv);
        tok->tid = 0;
    }
    pthread_mutex_unlock(&tok->lock);
287
#elif defined HAVE_WIN32_THREADS
288 289
    if (!--tok->count) 
	LeaveCriticalSection(&tok->cs);
290 291 292 293 294 295 296 297 298
#endif
}

/************************************************************************
 *									*
 *			Per thread global state handling		*
 *									*
 ************************************************************************/

299
#ifdef LIBXML_THREAD_ENABLED
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
/**
 * xmlFreeGlobalState:
 * @state:  a thread global state
 *
 * xmlFreeGlobalState() is called when a thread terminates with a non-NULL
 * global state. It is is used here to reclaim memory resources.
 */
static void
xmlFreeGlobalState(void *state)
{
    free(state);
}

/**
 * xmlNewGlobalState:
 *
 * xmlNewGlobalState() allocates a global state. This structure is used to
 * hold all data for use by a thread when supporting backwards compatibility
318
 * of libxml2 to pre-thread-safe behaviour.
319 320 321 322 323 324 325 326 327 328 329 330
 *
 * Returns the newly allocated xmlGlobalStatePtr or NULL in case of error
 */
static xmlGlobalStatePtr
xmlNewGlobalState(void)
{
    xmlGlobalState *gs;
    
    gs = malloc(sizeof(xmlGlobalState));
    if (gs == NULL)
	return(NULL);

William M. Brack's avatar
William M. Brack committed
331
    memset(gs, 0, sizeof(xmlGlobalState));
332 333 334
    xmlInitializeGlobalState(gs);
    return (gs);
}
335
#endif /* LIBXML_THREAD_ENABLED */
336 337


338
#ifdef HAVE_WIN32_THREADS
339 340
#if !defined(HAVE_COMPILER_TLS)
#if defined(LIBXML_STATIC) && !defined(LIBXML_STATIC_FOR_DLL)
341 342
typedef struct _xmlGlobalStateCleanupHelperParams
{
343 344
    HANDLE thread;
    void *memory;
345 346
} xmlGlobalStateCleanupHelperParams;

347
static void xmlGlobalStateCleanupHelper (void *p)
348
{
349 350 351 352 353 354
    xmlGlobalStateCleanupHelperParams *params = (xmlGlobalStateCleanupHelperParams *) p;
    WaitForSingleObject(params->thread, INFINITE);
    CloseHandle(params->thread);
    xmlFreeGlobalState(params->memory);
    free(params);
    _endthread();
355
}
356 357 358 359 360 361 362 363 364 365 366 367 368 369
#else /* LIBXML_STATIC && !LIBXML_STATIC_FOR_DLL */

typedef struct _xmlGlobalStateCleanupHelperParams
{
    void *memory;
    struct _xmlGlobalStateCleanupHelperParams * prev;
    struct _xmlGlobalStateCleanupHelperParams * next;
} xmlGlobalStateCleanupHelperParams;

static xmlGlobalStateCleanupHelperParams * cleanup_helpers_head = NULL;
static CRITICAL_SECTION cleanup_helpers_cs;

#endif /* LIBXMLSTATIC && !LIBXML_STATIC_FOR_DLL */
#endif /* HAVE_COMPILER_TLS */
370 371
#endif /* HAVE_WIN32_THREADS */

372 373 374 375 376 377 378
/**
 * xmlGetGlobalState:
 *
 * xmlGetGlobalState() is called to retrieve the global state for a thread.
 *
 * Returns the thread global state or NULL in case of error
 */
379 380 381 382 383 384
xmlGlobalStatePtr
xmlGetGlobalState(void)
{
#ifdef HAVE_PTHREAD_H
    xmlGlobalState *globalval;

385 386
    pthread_once(&once_control, xmlOnceInit);

387
    if ((globalval = (xmlGlobalState *)
388
		pthread_getspecific(globalkey)) == NULL) {
389 390 391 392
        xmlGlobalState *tsd = xmlNewGlobalState();

        pthread_setspecific(globalkey, tsd);
        return (tsd);
393 394
    }
    return (globalval);
395
#elif defined HAVE_WIN32_THREADS
396 397 398 399 400 401 402 403
#if defined(HAVE_COMPILER_TLS)
    if (!tlstate_inited) {
	tlstate_inited = 1;
	xmlInitializeGlobalState(&tlstate);
    }
    return &tlstate;
#else /* HAVE_COMPILER_TLS */
    xmlGlobalState *globalval;
404
    xmlGlobalStateCleanupHelperParams * p;
405 406 407 408 409

    if (run_once_init) { 
	run_once_init = 0; 
	xmlOnceInit(); 
    }
410 411 412 413 414 415 416
#if defined(LIBXML_STATIC) && !defined(LIBXML_STATIC_FOR_DLL)
    globalval = (xmlGlobalState *)TlsGetValue(globalkey);
#else
    p = (xmlGlobalStateCleanupHelperParams*)TlsGetValue(globalkey);
    globalval = (xmlGlobalState *)(p ? p->memory : NULL);
#endif
    if (globalval == NULL) {
417
	xmlGlobalState *tsd = xmlNewGlobalState();
418
	p = (xmlGlobalStateCleanupHelperParams *) malloc(sizeof(xmlGlobalStateCleanupHelperParams));
419
	p->memory = tsd;
420
#if defined(LIBXML_STATIC) && !defined(LIBXML_STATIC_FOR_DLL)
421 422 423 424
	DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), 
		GetCurrentProcess(), &p->thread, 0, TRUE, DUPLICATE_SAME_ACCESS);
	TlsSetValue(globalkey, tsd);
	_beginthread(xmlGlobalStateCleanupHelper, 0, p);
425 426 427 428 429 430 431 432 433 434
#else
	EnterCriticalSection(&cleanup_helpers_cs);	
        if (cleanup_helpers_head != NULL) {
            cleanup_helpers_head->prev = p;
        }
	p->next = cleanup_helpers_head;
	p->prev = NULL;
	cleanup_helpers_head = p;
	TlsSetValue(globalkey, p);
	LeaveCriticalSection(&cleanup_helpers_cs);	
435
#endif
436 437 438 439 440

	return (tsd);
    }
    return (globalval);
#endif /* HAVE_COMPILER_TLS */
441 442
#else
    return(NULL);
443 444 445 446 447 448 449 450 451
#endif
}

/************************************************************************
 *									*
 *			Library wide thread interfaces			*
 *									*
 ************************************************************************/

452 453 454 455 456 457 458 459 460 461 462 463
/**
 * xmlGetThreadId:
 *
 * xmlGetThreadId() find the current thread ID number
 *
 * Returns the current thread ID number
 */
int
xmlGetThreadId(void)
{
#ifdef HAVE_PTHREAD_H
    return((int) pthread_self());
464
#elif defined HAVE_WIN32_THREADS
465
    return GetCurrentThreadId();
466 467 468 469 470
#else
    return((int) 0);
#endif
}

471 472 473
/**
 * xmlIsMainThread:
 *
474
 * xmlIsMainThread() check whether the current thread is the main thread.
475 476 477 478 479 480
 *
 * Returns 1 if the current thread is the main thread, 0 otherwise
 */
int
xmlIsMainThread(void)
{
481 482
#ifdef HAVE_PTHREAD_H
    pthread_once(&once_control, xmlOnceInit);
483
#elif defined HAVE_WIN32_THREADS
484 485 486 487
    if (run_once_init) { 
	run_once_init = 0; 
	xmlOnceInit (); 
    }
488
#endif
489 490 491 492 493 494
        
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlIsMainThread()\n");
#endif
#ifdef HAVE_PTHREAD_H
    return(mainthread == pthread_self());
495
#elif defined HAVE_WIN32_THREADS
496
    return(mainthread == GetCurrentThreadId ());
497 498 499 500 501
#else
    return(1);
#endif
}

502 503 504 505 506 507 508 509 510
/**
 * xmlLockLibrary:
 *
 * xmlLockLibrary() is used to take out a re-entrant lock on the libxml2
 * library.
 */
void
xmlLockLibrary(void)
{
511 512 513
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlLockLibrary()\n");
#endif
514 515 516 517 518 519 520 521 522 523 524 525
    xmlRMutexLock(xmlLibraryLock);
}

/**
 * xmlUnlockLibrary:
 *
 * xmlUnlockLibrary() is used to release a re-entrant lock on the libxml2
 * library.
 */
void
xmlUnlockLibrary(void)
{
526 527 528
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlUnlockLibrary()\n");
#endif
529 530 531 532 533 534 535 536 537 538 539 540
    xmlRMutexUnlock(xmlLibraryLock);
}

/**
 * xmlInitThreads:
 *
 * xmlInitThreads() is used to to initialize all the thread related
 * data of the libxml2 library.
 */
void
xmlInitThreads(void)
{
541 542 543
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlInitThreads()\n");
#endif
544 545 546
#if defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS)
    InitializeCriticalSection(&cleanup_helpers_cs);
#endif
547 548 549 550 551 552 553 554 555 556 557
}

/**
 * xmlCleanupThreads:
 *
 * xmlCleanupThreads() is used to to cleanup all the thread related
 * data of the libxml2 library once processing has ended.
 */
void
xmlCleanupThreads(void)
{
558 559 560
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlCleanupThreads()\n");
#endif
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
#if defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS)
    if (globalkey != TLS_OUT_OF_INDEXES) {
	xmlGlobalStateCleanupHelperParams * p;
	EnterCriticalSection(&cleanup_helpers_cs);
	p = cleanup_helpers_head;
	while (p != NULL) {
		xmlGlobalStateCleanupHelperParams * temp = p;
		p = p->next;
		xmlFreeGlobalState(temp->memory);
		free(temp);
	}
	cleanup_helpers_head = 0;
	LeaveCriticalSection(&cleanup_helpers_cs);
	TlsFree(globalkey);
	globalkey = TLS_OUT_OF_INDEXES;
    }
    DeleteCriticalSection(&cleanup_helpers_cs);
#endif
579
}
580

581
#ifdef LIBXML_THREAD_ENABLED
582 583 584 585 586 587 588 589 590 591 592 593
/**
 * xmlOnceInit
 *
 * xmlOnceInit() is used to initialize the value of mainthread for use
 * in other routines. This function should only be called using
 * pthread_once() in association with the once_control variable to ensure
 * that the function is only called once. See man pthread_once for more
 * details.
 */
static void
xmlOnceInit(void) {
#ifdef HAVE_PTHREAD_H
594
    (void) pthread_key_create(&globalkey, xmlFreeGlobalState);
595
    mainthread = pthread_self();
596 597 598 599 600 601 602
#endif

#if defined(HAVE_WIN32_THREADS)
#if !defined(HAVE_COMPILER_TLS)
    globalkey = TlsAlloc();
#endif
    mainthread = GetCurrentThreadId();
603
#endif
604
}
605
#endif
606 607

/**
608 609 610 611
 * DllMain:
 * @hinstDLL: handle to DLL instance
 * @fdwReason: Reason code for entry
 * @lpvReserved: generic pointer (depends upon reason code)
612 613 614
 *
 * Entry point for Windows library. It is being used to free thread-specific
 * storage.
615 616
 *
 * Returns TRUE always
617
 */
618 619 620 621
#if defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS) && (!defined(LIBXML_STATIC) || defined(LIBXML_STATIC_FOR_DLL))
#if defined(LIBXML_STATIC_FOR_DLL)
BOOL WINAPI xmlDllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) 
#else
622
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) 
623
#endif
624 625 626 627
{
    switch(fdwReason) {
    case DLL_THREAD_DETACH:
	if (globalkey != TLS_OUT_OF_INDEXES) {
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
	    xmlGlobalState *globalval = NULL;
	    xmlGlobalStateCleanupHelperParams * p =
		(xmlGlobalStateCleanupHelperParams*)TlsGetValue(globalkey);
	    globalval = (xmlGlobalState *)(p ? p->memory : NULL);
            if (globalval) {
                xmlFreeGlobalState(globalval);
                TlsSetValue(globalkey,NULL);
            }
	    if (p)
	    {
		EnterCriticalSection(&cleanup_helpers_cs);
                if (p == cleanup_helpers_head)
		    cleanup_helpers_head = p->next;
                else
		    p->prev->next = p->next;
                if (p->next != NULL)
                    p->next->prev = p->prev;
		LeaveCriticalSection(&cleanup_helpers_cs);
		free(p);
647 648 649 650 651 652 653
	    }
	}
	break;
    }
    return TRUE;
}
#endif