threads.c 26.3 KB
Newer Older
1
/**
2
 * threads.c: set of generic threading related routines
3 4 5 6 7 8 9
 *
 * 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
#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>
29
#elif defined HAVE_WIN32_THREADS
30
#include <windows.h>
31
#ifndef HAVE_COMPILER_TLS
32 33 34
#include <process.h>
#endif
#endif
35

36 37 38 39 40
#ifdef HAVE_BEOS_THREADS
#include <OS.h>
#include <TLS.h>
#endif

41 42 43 44
#if defined(SOLARIS)
#include <note.h>
#endif

45
/* #define DEBUG_THREADS */
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
#ifdef HAVE_PTHREAD_H

static int libxml_is_threaded = -1;
#ifdef __GNUC__
#ifdef linux
#if (__GNUC__ == 3 && __GNUC_MINOR__ >= 3) || (__GNUC__ > 3)
extern int pthread_once (pthread_once_t *__once_control,
                         void (*__init_routine) (void))
	   __attribute((weak));
extern void *pthread_getspecific (pthread_key_t __key)
	   __attribute((weak));
extern int pthread_setspecific (pthread_key_t __key,
                                __const void *__pointer)
	   __attribute((weak));
extern int pthread_key_create (pthread_key_t *__key,
                               void (*__destr_function) (void *))
	   __attribute((weak));
64 65
extern int pthread_key_delete (pthread_key_t __key)
	   __attribute((weak));
66 67 68 69 70 71 72 73 74 75
extern int pthread_mutex_init ()
	   __attribute((weak));
extern int pthread_mutex_destroy ()
	   __attribute((weak));
extern int pthread_mutex_lock ()
	   __attribute((weak));
extern int pthread_mutex_unlock ()
	   __attribute((weak));
extern int pthread_cond_init ()
	   __attribute((weak));
76 77 78 79
extern int pthread_cond_destroy ()
	   __attribute((weak));
extern int pthread_cond_wait ()
	   __attribute((weak));
80 81 82 83 84 85
extern int pthread_equal ()
	   __attribute((weak));
extern pthread_t pthread_self ()
	   __attribute((weak));
extern int pthread_key_create ()
	   __attribute((weak));
86 87
extern int pthread_key_delete ()
	   __attribute((weak));
88 89 90 91 92 93 94
extern int pthread_cond_signal ()
	   __attribute((weak));
#endif
#endif /* linux */
#endif /* __GNUC__ */
#endif /* HAVE_PTHREAD_H */

95 96 97 98 99 100 101 102 103 104 105 106
/*
 * 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;
107
#elif defined HAVE_WIN32_THREADS
108
    HANDLE mutex;
109
#elif defined HAVE_BEOS_THREADS
110 111
    sem_id sem;
    thread_id tid;
112 113 114 115 116 117 118 119 120 121 122
#else
    int empty;
#endif
};

/*
 * xmlRMutex are reentrant mutual exception locks
 */
struct _xmlRMutex {
#ifdef HAVE_PTHREAD_H
    pthread_mutex_t lock;
123 124 125 126
    unsigned int held;
    unsigned int waiters;
    pthread_t tid;
    pthread_cond_t cv;
127
#elif defined HAVE_WIN32_THREADS
128 129
    CRITICAL_SECTION cs;
    unsigned int count;
130
#elif defined HAVE_BEOS_THREADS
131 132 133
    xmlMutexPtr lock;
    thread_id tid;
    int32 count;
134 135 136 137
#else
    int empty;
#endif
};
138

139 140 141 142 143
/*
 * This module still has some internal static data.
 *   - xmlLibraryLock a global lock
 *   - globalkey used for per-thread data
 */
144

145
#ifdef HAVE_PTHREAD_H
146 147
static pthread_key_t globalkey;
static pthread_t mainthread;
148
static pthread_once_t once_control = PTHREAD_ONCE_INIT;
149
static pthread_mutex_t global_init_lock = PTHREAD_MUTEX_INITIALIZER;
150
#elif defined HAVE_WIN32_THREADS
151 152 153 154
#if defined(HAVE_COMPILER_TLS)
static __declspec(thread) xmlGlobalState tlstate;
static __declspec(thread) int tlstate_inited = 0;
#else /* HAVE_COMPILER_TLS */
155
static DWORD globalkey = TLS_OUT_OF_INDEXES;
156
#endif /* HAVE_COMPILER_TLS */
157
static DWORD mainthread;
158
static struct {
159 160
    DWORD done;
    DWORD control;
161
} run_once = { 0, 0};
162
static volatile LPCRITICAL_SECTION global_init_lock = NULL;
163

164 165 166 167 168
/* endif HAVE_WIN32_THREADS */
#elif defined HAVE_BEOS_THREADS
int32 globalkey = 0;
thread_id mainthread = 0;
int32 run_once_init = 0;
169 170
static int32 global_init_lock = -1;
static vint32 global_init_count = 0;
171
#endif
172

173 174
static xmlRMutexPtr xmlLibraryLock = NULL;

175
#ifdef LIBXML_THREAD_ENABLED
176
static void xmlOnceInit(void);
177
#endif
178 179

/**
180
 * xmlNewMutex:
181 182 183 184 185 186 187 188 189 190 191 192 193 194
 *
 * 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
195
    if (libxml_is_threaded != 0)
196
        pthread_mutex_init(&tok->lock, NULL);
197
#elif defined HAVE_WIN32_THREADS
198
    tok->mutex = CreateMutex(NULL, FALSE, NULL);
199
#elif defined HAVE_BEOS_THREADS
200 201 202 203 204
    if ((tok->sem = create_sem(1, "xmlMutex")) < B_OK) {
        free(tok);
        return NULL;
    }
    tok->tid = -1;
205 206 207 208 209 210 211 212 213 214 215 216 217 218
#endif
    return (tok);
}

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

222
#ifdef HAVE_PTHREAD_H
223
    if (libxml_is_threaded != 0)
224
        pthread_mutex_destroy(&tok->lock);
225
#elif defined HAVE_WIN32_THREADS
226
    CloseHandle(tok->mutex);
227
#elif defined HAVE_BEOS_THREADS
228
    delete_sem(tok->sem);
229 230 231 232 233 234 235 236 237 238 239
#endif
    free(tok);
}

/**
 * xmlMutexLock:
 * @tok:  the simple mutex
 *
 * xmlMutexLock() is used to lock a libxml2 token.
 */
void
240
xmlMutexLock(xmlMutexPtr tok)
241
{
242 243
    if (tok == NULL)
        return;
244
#ifdef HAVE_PTHREAD_H
245
    if (libxml_is_threaded != 0)
246
        pthread_mutex_lock(&tok->lock);
247
#elif defined HAVE_WIN32_THREADS
248
    WaitForSingleObject(tok->mutex, INFINITE);
249
#elif defined HAVE_BEOS_THREADS
250
    if (acquire_sem(tok->sem) != B_NO_ERROR) {
251
#ifdef DEBUG_THREADS
252 253 254
        xmlGenericError(xmlGenericErrorContext,
                        "xmlMutexLock():BeOS:Couldn't aquire semaphore\n");
        exit();
255
#endif
256 257
    }
    tok->tid = find_thread(NULL);
258 259 260 261 262 263 264 265 266 267 268
#endif

}

/**
 * xmlMutexUnlock:
 * @tok:  the simple mutex
 *
 * xmlMutexUnlock() is used to unlock a libxml2 token.
 */
void
269
xmlMutexUnlock(xmlMutexPtr tok)
270
{
271 272
    if (tok == NULL)
        return;
273
#ifdef HAVE_PTHREAD_H
274
    if (libxml_is_threaded != 0)
275
        pthread_mutex_unlock(&tok->lock);
276
#elif defined HAVE_WIN32_THREADS
277
    ReleaseMutex(tok->mutex);
278
#elif defined HAVE_BEOS_THREADS
279 280 281 282
    if (tok->tid == find_thread(NULL)) {
        tok->tid = -1;
        release_sem(tok->sem);
    }
283 284 285 286
#endif
}

/**
287
 * xmlNewRMutex:
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
 *
 * 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
304
    if (libxml_is_threaded != 0) {
305 306 307 308
        pthread_mutex_init(&tok->lock, NULL);
        tok->held = 0;
        tok->waiters = 0;
        pthread_cond_init(&tok->cv, NULL);
309
    }
310
#elif defined HAVE_WIN32_THREADS
311 312
    InitializeCriticalSection(&tok->cs);
    tok->count = 0;
313
#elif defined HAVE_BEOS_THREADS
314 315 316 317 318
    if ((tok->lock = xmlNewMutex()) == NULL) {
        free(tok);
        return NULL;
    }
    tok->count = 0;
319 320 321 322 323
#endif
    return (tok);
}

/**
324
 * xmlFreeRMutex:
325 326 327 328 329 330
 * @tok:  the reentrant mutex
 *
 * xmlRFreeMutex() is used to reclaim resources associated with a
 * reentrant mutex.
 */
void
331
xmlFreeRMutex(xmlRMutexPtr tok ATTRIBUTE_UNUSED)
332
{
333 334
    if (tok == NULL)
        return;
335
#ifdef HAVE_PTHREAD_H
336
    if (libxml_is_threaded != 0) {
337 338
        pthread_mutex_destroy(&tok->lock);
        pthread_cond_destroy(&tok->cv);
339
    }
340
#elif defined HAVE_WIN32_THREADS
341
    DeleteCriticalSection(&tok->cs);
342
#elif defined HAVE_BEOS_THREADS
343
    xmlFreeMutex(tok->lock);
344 345 346 347 348 349 350 351 352 353 354
#endif
    free(tok);
}

/**
 * xmlRMutexLock:
 * @tok:  the reentrant mutex
 *
 * xmlRMutexLock() is used to lock a libxml2 token_r.
 */
void
355
xmlRMutexLock(xmlRMutexPtr tok)
356
{
357 358
    if (tok == NULL)
        return;
359
#ifdef HAVE_PTHREAD_H
360 361 362
    if (libxml_is_threaded == 0)
        return;

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    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);
379
#elif defined HAVE_WIN32_THREADS
380 381
    EnterCriticalSection(&tok->cs);
    ++tok->count;
382
#elif defined HAVE_BEOS_THREADS
383 384 385 386 387 388 389
    if (tok->lock->tid == find_thread(NULL)) {
        tok->count++;
        return;
    } else {
        xmlMutexLock(tok->lock);
        tok->count = 1;
    }
390 391 392 393 394 395 396 397 398 399
#endif
}

/**
 * xmlRMutexUnlock:
 * @tok:  the reentrant mutex
 *
 * xmlRMutexUnlock() is used to unlock a libxml2 token_r.
 */
void
400
xmlRMutexUnlock(xmlRMutexPtr tok ATTRIBUTE_UNUSED)
401
{
402 403
    if (tok == NULL)
        return;
404
#ifdef HAVE_PTHREAD_H
405 406
    if (libxml_is_threaded == 0)
        return;
407

408 409 410 411 412
    pthread_mutex_lock(&tok->lock);
    tok->held--;
    if (tok->held == 0) {
        if (tok->waiters)
            pthread_cond_signal(&tok->cv);
413
        memset(&tok->tid, 0, sizeof(tok->tid));
414 415
    }
    pthread_mutex_unlock(&tok->lock);
416
#elif defined HAVE_WIN32_THREADS
417 418
    if (!--tok->count)
        LeaveCriticalSection(&tok->cs);
419
#elif defined HAVE_BEOS_THREADS
420 421 422 423 424 425 426
    if (tok->lock->tid == find_thread(NULL)) {
        tok->count--;
        if (tok->count == 0) {
            xmlMutexUnlock(tok->lock);
        }
        return;
    }
427 428 429
#endif
}

430 431 432 433 434 435 436 437 438 439 440 441
/**
 * xmlGlobalInitMutexLock
 *
 * Makes sure that the global initialization mutex is initialized and
 * locks it.
 */
void
__xmlGlobalInitMutexLock(void)
{
    /* Make sure the global init lock is initialized and then lock it. */
#ifdef HAVE_PTHREAD_H
    /* The mutex is statically initialized, so we just lock it. */
442
    if (pthread_mutex_lock != NULL)
443
        pthread_mutex_lock(&global_init_lock);
444 445 446 447 448
#elif defined HAVE_WIN32_THREADS
    LPCRITICAL_SECTION cs;

    /* Create a new critical section */
    if (global_init_lock == NULL) {
449 450 451 452 453 454 455
        cs = malloc(sizeof(CRITICAL_SECTION));
        if (cs == NULL) {
            xmlGenericError(xmlGenericErrorContext,
                            "xmlGlobalInitMutexLock: out of memory\n");
            return;
        }
        InitializeCriticalSection(cs);
456

457
        /* Swap it into the global_init_lock */
458
#ifdef InterlockedCompareExchangePointer
459 460 461 462
        InterlockedCompareExchangePointer(&global_init_lock, cs, NULL);
#else /* Use older void* version */
        InterlockedCompareExchange((void **) &global_init_lock,
                                   (void *) cs, NULL);
463
#endif /* InterlockedCompareExchangePointer */
464

465 466 467 468 469 470 471
        /* If another thread successfully recorded its critical
         * section in the global_init_lock then discard the one
         * allocated by this thread. */
        if (global_init_lock != cs) {
            DeleteCriticalSection(cs);
            free(cs);
        }
472 473 474 475 476 477 478 479 480 481 482
    }

    /* Lock the chosen critical section */
    EnterCriticalSection(global_init_lock);
#elif defined HAVE_BEOS_THREADS
    int32 sem;

    /* Allocate a new semaphore */
    sem = create_sem(1, "xmlGlobalinitMutex");

    while (global_init_lock == -1) {
483 484 485 486 487 488
        if (atomic_add(&global_init_count, 1) == 0) {
            global_init_lock = sem;
        } else {
            snooze(1);
            atomic_add(&global_init_count, -1);
        }
489 490 491 492 493 494
    }

    /* If another thread successfully recorded its critical
     * section in the global_init_lock then discard the one
     * allocated by this thread. */
    if (global_init_lock != sem)
495
        delete_sem(sem);
496 497 498 499

    /* Acquire the chosen semaphore */
    if (acquire_sem(global_init_lock) != B_NO_ERROR) {
#ifdef DEBUG_THREADS
500 501 502
        xmlGenericError(xmlGenericErrorContext,
                        "xmlGlobalInitMutexLock():BeOS:Couldn't acquire semaphore\n");
        exit();
503 504 505 506 507 508 509 510 511
#endif
    }
#endif
}

void
__xmlGlobalInitMutexUnlock(void)
{
#ifdef HAVE_PTHREAD_H
512
    if (pthread_mutex_unlock != NULL)
513
        pthread_mutex_unlock(&global_init_lock);
514
#elif defined HAVE_WIN32_THREADS
515 516 517
    if (global_init_lock != NULL) {
	LeaveCriticalSection(global_init_lock);
    }
518 519 520 521 522
#elif defined HAVE_BEOS_THREADS
    release_sem(global_init_lock);
#endif
}

523 524 525 526 527 528
/**
 * xmlGlobalInitMutexDestroy
 *
 * Makes sure that the global initialization mutex is destroyed before
 * application termination.
 */
529 530
void
__xmlGlobalInitMutexDestroy(void)
531
{
532 533
#ifdef HAVE_PTHREAD_H
#elif defined HAVE_WIN32_THREADS
534 535 536 537
    if (global_init_lock != NULL) {
        DeleteCriticalSection(global_init_lock);
        free(global_init_lock);
        global_init_lock = NULL;
538 539 540 541
    }
#endif
}

542 543 544 545 546 547
/************************************************************************
 *									*
 *			Per thread global state handling		*
 *									*
 ************************************************************************/

548
#ifdef LIBXML_THREAD_ENABLED
549 550 551
#ifdef xmlLastError
#undef xmlLastError
#endif
552

553 554 555 556 557 558 559 560 561 562
/**
 * 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)
{
563 564 565 566
    xmlGlobalState *gs = (xmlGlobalState *) state;

    /* free any memory allocated in the thread's xmlLastError */
    xmlResetError(&(gs->xmlLastError));
567 568 569 570 571 572 573 574
    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
575
 * of libxml2 to pre-thread-safe behaviour.
576 577 578 579 580 581 582
 *
 * Returns the newly allocated xmlGlobalStatePtr or NULL in case of error
 */
static xmlGlobalStatePtr
xmlNewGlobalState(void)
{
    xmlGlobalState *gs;
583

584
    gs = malloc(sizeof(xmlGlobalState));
585 586 587 588 589
    if (gs == NULL) {
	xmlGenericError(xmlGenericErrorContext,
			"xmlGetGlobalState: out of memory\n");
        return (NULL);
    }
590

William M. Brack's avatar
William M. Brack committed
591
    memset(gs, 0, sizeof(xmlGlobalState));
592 593 594
    xmlInitializeGlobalState(gs);
    return (gs);
}
595
#endif /* LIBXML_THREAD_ENABLED */
596

597
#ifdef HAVE_PTHREAD_H
598
#elif defined HAVE_WIN32_THREADS
599 600
#if !defined(HAVE_COMPILER_TLS)
#if defined(LIBXML_STATIC) && !defined(LIBXML_STATIC_FOR_DLL)
601
typedef struct _xmlGlobalStateCleanupHelperParams {
602 603
    HANDLE thread;
    void *memory;
604 605
} xmlGlobalStateCleanupHelperParams;

606 607
static void XMLCDECL
xmlGlobalStateCleanupHelper(void *p)
608
{
609 610
    xmlGlobalStateCleanupHelperParams *params =
        (xmlGlobalStateCleanupHelperParams *) p;
611 612 613 614 615
    WaitForSingleObject(params->thread, INFINITE);
    CloseHandle(params->thread);
    xmlFreeGlobalState(params->memory);
    free(params);
    _endthread();
616
}
617 618
#else /* LIBXML_STATIC && !LIBXML_STATIC_FOR_DLL */

619
typedef struct _xmlGlobalStateCleanupHelperParams {
620
    void *memory;
621 622
    struct _xmlGlobalStateCleanupHelperParams *prev;
    struct _xmlGlobalStateCleanupHelperParams *next;
623 624
} xmlGlobalStateCleanupHelperParams;

625
static xmlGlobalStateCleanupHelperParams *cleanup_helpers_head = NULL;
626 627 628 629
static CRITICAL_SECTION cleanup_helpers_cs;

#endif /* LIBXMLSTATIC && !LIBXML_STATIC_FOR_DLL */
#endif /* HAVE_COMPILER_TLS */
630 631
#endif /* HAVE_WIN32_THREADS */

632
#if defined HAVE_BEOS_THREADS
633

634 635 636 637 638 639
/**
 * xmlGlobalStateCleanup:
 * @data: unused parameter
 *
 * Used for Beos only
 */
640 641
void
xmlGlobalStateCleanup(void *data)
642
{
643 644 645 646
    void *globalval = tls_get(globalkey);

    if (globalval != NULL)
        xmlFreeGlobalState(globalval);
647 648 649
}
#endif

650 651 652 653 654 655 656
/**
 * xmlGetGlobalState:
 *
 * xmlGetGlobalState() is called to retrieve the global state for a thread.
 *
 * Returns the thread global state or NULL in case of error
 */
657 658 659 660 661 662
xmlGlobalStatePtr
xmlGetGlobalState(void)
{
#ifdef HAVE_PTHREAD_H
    xmlGlobalState *globalval;

663
    if (libxml_is_threaded == 0)
664
        return (NULL);
665

666 667
    pthread_once(&once_control, xmlOnceInit);

668
    if ((globalval = (xmlGlobalState *)
669
         pthread_getspecific(globalkey)) == NULL) {
670
        xmlGlobalState *tsd = xmlNewGlobalState();
671 672
	if (tsd == NULL)
	    return(NULL);
673 674 675

        pthread_setspecific(globalkey, tsd);
        return (tsd);
676 677
    }
    return (globalval);
678
#elif defined HAVE_WIN32_THREADS
679 680
#if defined(HAVE_COMPILER_TLS)
    if (!tlstate_inited) {
681 682
        tlstate_inited = 1;
        xmlInitializeGlobalState(&tlstate);
683 684 685 686
    }
    return &tlstate;
#else /* HAVE_COMPILER_TLS */
    xmlGlobalState *globalval;
687
    xmlGlobalStateCleanupHelperParams *p;
688

689
    xmlOnceInit();
690
#if defined(LIBXML_STATIC) && !defined(LIBXML_STATIC_FOR_DLL)
691
    globalval = (xmlGlobalState *) TlsGetValue(globalkey);
692
#else
693 694
    p = (xmlGlobalStateCleanupHelperParams *) TlsGetValue(globalkey);
    globalval = (xmlGlobalState *) (p ? p->memory : NULL);
695 696
#endif
    if (globalval == NULL) {
697 698 699 700 701 702 703 704 705
        xmlGlobalState *tsd = xmlNewGlobalState();

        if (tsd == NULL)
	    return(NULL);
        p = (xmlGlobalStateCleanupHelperParams *)
            malloc(sizeof(xmlGlobalStateCleanupHelperParams));
	if (p == NULL) {
            xmlGenericError(xmlGenericErrorContext,
                            "xmlGetGlobalState: out of memory\n");
706
            xmlFreeGlobalState(tsd);
707 708 709
	    return(NULL);
	}
        p->memory = tsd;
710
#if defined(LIBXML_STATIC) && !defined(LIBXML_STATIC_FOR_DLL)
711 712 713 714 715
        DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
                        GetCurrentProcess(), &p->thread, 0, TRUE,
                        DUPLICATE_SAME_ACCESS);
        TlsSetValue(globalkey, tsd);
        _beginthread(xmlGlobalStateCleanupHelper, 0, p);
716
#else
717
        EnterCriticalSection(&cleanup_helpers_cs);
718 719 720
        if (cleanup_helpers_head != NULL) {
            cleanup_helpers_head->prev = p;
        }
721 722 723 724 725
        p->next = cleanup_helpers_head;
        p->prev = NULL;
        cleanup_helpers_head = p;
        TlsSetValue(globalkey, p);
        LeaveCriticalSection(&cleanup_helpers_cs);
726
#endif
727

728
        return (tsd);
729 730 731
    }
    return (globalval);
#endif /* HAVE_COMPILER_TLS */
732 733 734 735 736
#elif defined HAVE_BEOS_THREADS
    xmlGlobalState *globalval;

    xmlOnceInit();

737
    if ((globalval = (xmlGlobalState *) tls_get(globalkey)) == NULL) {
738
        xmlGlobalState *tsd = xmlNewGlobalState();
739 740
	if (tsd == NULL)
	    return (NULL);
741 742 743 744 745 746

        tls_set(globalkey, tsd);
        on_exit_thread(xmlGlobalStateCleanup, NULL);
        return (tsd);
    }
    return (globalval);
747
#else
748
    return (NULL);
749 750 751 752 753 754 755 756 757
#endif
}

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

758 759 760 761
/**
 * xmlGetThreadId:
 *
 * xmlGetThreadId() find the current thread ID number
762 763
 * Note that this is likely to be broken on some platforms using pthreads
 * as the specification doesn't mandate pthread_t to be an integer type
764 765 766 767 768 769 770
 *
 * Returns the current thread ID number
 */
int
xmlGetThreadId(void)
{
#ifdef HAVE_PTHREAD_H
771 772 773
    pthread_t id;
    int ret;

774
    if (libxml_is_threaded == 0)
775
        return (0);
776 777 778 779
    id = pthread_self();
    /* horrible but preserves compat, see warning above */
    memcpy(&ret, &id, sizeof(ret));
    return (ret);
780
#elif defined HAVE_WIN32_THREADS
781
    return GetCurrentThreadId();
782
#elif defined HAVE_BEOS_THREADS
783
    return find_thread(NULL);
784
#else
785
    return ((int) 0);
786 787 788
#endif
}

789 790 791
/**
 * xmlIsMainThread:
 *
792
 * xmlIsMainThread() check whether the current thread is the main thread.
793 794 795 796 797 798
 *
 * Returns 1 if the current thread is the main thread, 0 otherwise
 */
int
xmlIsMainThread(void)
{
799
#ifdef HAVE_PTHREAD_H
800 801 802
    if (libxml_is_threaded == -1)
        xmlInitThreads();
    if (libxml_is_threaded == 0)
803
        return (1);
804
    pthread_once(&once_control, xmlOnceInit);
805
#elif defined HAVE_WIN32_THREADS
806
    xmlOnceInit();
807
#elif defined HAVE_BEOS_THREADS
808
    xmlOnceInit();
809
#endif
810

811 812 813 814
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlIsMainThread()\n");
#endif
#ifdef HAVE_PTHREAD_H
815
    return (pthread_equal(mainthread,pthread_self()));
816
#elif defined HAVE_WIN32_THREADS
817
    return (mainthread == GetCurrentThreadId());
818
#elif defined HAVE_BEOS_THREADS
819
    return (mainthread == find_thread(NULL));
820
#else
821
    return (1);
822 823 824
#endif
}

825 826 827 828 829 830 831 832 833
/**
 * xmlLockLibrary:
 *
 * xmlLockLibrary() is used to take out a re-entrant lock on the libxml2
 * library.
 */
void
xmlLockLibrary(void)
{
834 835 836
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlLockLibrary()\n");
#endif
837 838 839 840 841 842 843 844 845 846 847 848
    xmlRMutexLock(xmlLibraryLock);
}

/**
 * xmlUnlockLibrary:
 *
 * xmlUnlockLibrary() is used to release a re-entrant lock on the libxml2
 * library.
 */
void
xmlUnlockLibrary(void)
{
849 850 851
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlUnlockLibrary()\n");
#endif
852 853 854 855 856 857 858 859 860 861 862 863
    xmlRMutexUnlock(xmlLibraryLock);
}

/**
 * xmlInitThreads:
 *
 * xmlInitThreads() is used to to initialize all the thread related
 * data of the libxml2 library.
 */
void
xmlInitThreads(void)
{
864 865 866
#ifdef HAVE_PTHREAD_H
    if (libxml_is_threaded == -1) {
        if ((pthread_once != NULL) &&
867 868 869
            (pthread_getspecific != NULL) &&
            (pthread_setspecific != NULL) &&
            (pthread_key_create != NULL) &&
870
            (pthread_key_delete != NULL) &&
871 872 873 874 875
            (pthread_mutex_init != NULL) &&
            (pthread_mutex_destroy != NULL) &&
            (pthread_mutex_lock != NULL) &&
            (pthread_mutex_unlock != NULL) &&
            (pthread_cond_init != NULL) &&
876 877
            (pthread_cond_destroy != NULL) &&
            (pthread_cond_wait != NULL) &&
878 879 880 881 882
            (pthread_equal != NULL) &&
            (pthread_self != NULL) &&
            (pthread_cond_signal != NULL)) {
            libxml_is_threaded = 1;

883
/* fprintf(stderr, "Running multithreaded\n"); */
884 885
        } else {

886
/* fprintf(stderr, "Running without multithread\n"); */
887 888
            libxml_is_threaded = 0;
        }
889
    }
890 891
#elif defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS) && (!defined(LIBXML_STATIC) || defined(LIBXML_STATIC_FOR_DLL))
    InitializeCriticalSection(&cleanup_helpers_cs);
892
#endif
893 894 895 896 897 898 899
}

/**
 * xmlCleanupThreads:
 *
 * xmlCleanupThreads() is used to to cleanup all the thread related
 * data of the libxml2 library once processing has ended.
900 901 902 903 904 905 906 907
 *
 * WARNING: if your application is multithreaded or has plugin support
 *          calling this may crash the application if another thread or
 *          a plugin is still using libxml2. It's sometimes very hard to
 *          guess if libxml2 is in use in the application, some libraries
 *          or plugins may use it without notice. In case of doubt abstain
 *          from calling this function or do it just before calling exit()
 *          to avoid leak reports from valgrind !
908 909 910 911
 */
void
xmlCleanupThreads(void)
{
912 913 914
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlCleanupThreads()\n");
#endif
915 916 917 918
#ifdef HAVE_PTHREAD_H
    if ((libxml_is_threaded)  && (pthread_key_delete != NULL))
        pthread_key_delete(globalkey);
#elif defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS) && (!defined(LIBXML_STATIC) || defined(LIBXML_STATIC_FOR_DLL))
919
    if (globalkey != TLS_OUT_OF_INDEXES) {
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
        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;
935 936 937
    }
    DeleteCriticalSection(&cleanup_helpers_cs);
#endif
938
}
939

940
#ifdef LIBXML_THREAD_ENABLED
941

942 943 944 945 946 947 948 949 950 951
/**
 * 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
952 953
xmlOnceInit(void)
{
954
#ifdef HAVE_PTHREAD_H
955
    (void) pthread_key_create(&globalkey, xmlFreeGlobalState);
956
    mainthread = pthread_self();
957
#elif defined(HAVE_WIN32_THREADS)
958
    if (!run_once.done) {
959
        if (InterlockedIncrement(&run_once.control) == 1) {
960
#if !defined(HAVE_COMPILER_TLS)
961
            globalkey = TlsAlloc();
962
#endif
963 964
            mainthread = GetCurrentThreadId();
            run_once.done = 1;
965
        } else {
966 967 968 969 970 971
            /* Another thread is working; give up our slice and
             * wait until they're done. */
            while (!run_once.done)
                Sleep(0);
        }
    }
972
#elif defined HAVE_BEOS_THREADS
973 974 975 976 977 978
    if (atomic_add(&run_once_init, 1) == 0) {
        globalkey = tls_allocate();
        tls_set(globalkey, NULL);
        mainthread = find_thread(NULL);
    } else
        atomic_add(&run_once_init, -1);
979
#endif
980
}
981
#endif
982 983

/**
984 985 986 987
 * DllMain:
 * @hinstDLL: handle to DLL instance
 * @fdwReason: Reason code for entry
 * @lpvReserved: generic pointer (depends upon reason code)
988 989 990
 *
 * Entry point for Windows library. It is being used to free thread-specific
 * storage.
991 992
 *
 * Returns TRUE always
993
 */
994 995
#ifdef HAVE_PTHREAD_H
#elif defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS) && (!defined(LIBXML_STATIC) || defined(LIBXML_STATIC_FOR_DLL))
996
#if defined(LIBXML_STATIC_FOR_DLL)
997 998
BOOL XMLCALL
xmlDllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
999
#else
1000 1001
BOOL WINAPI
DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1002
#endif
1003
{
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
    switch (fdwReason) {
        case DLL_THREAD_DETACH:
            if (globalkey != TLS_OUT_OF_INDEXES) {
                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);
                }
1027
            }
1028
            break;
1029 1030 1031 1032
    }
    return TRUE;
}
#endif
1033 1034
#define bottom_threads
#include "elfgcchack.h"