threads.c 26.6 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
#define WIN32_LEAN_AND_MEAN
31
#include <windows.h>
32
#ifndef HAVE_COMPILER_TLS
33 34 35
#include <process.h>
#endif
#endif
36

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

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

46
/* #define DEBUG_THREADS */
47

48 49
#ifdef HAVE_PTHREAD_H

50 51 52
#if defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 303) && \
    defined(__GLIBC__) && defined(__linux__)

53
static int libxml_is_threaded = -1;
54 55 56

#define XML_PTHREAD_WEAK

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#pragma weak pthread_once
#pragma weak pthread_getspecific
#pragma weak pthread_setspecific
#pragma weak pthread_key_create
#pragma weak pthread_key_delete
#pragma weak pthread_mutex_init
#pragma weak pthread_mutex_destroy
#pragma weak pthread_mutex_lock
#pragma weak pthread_mutex_unlock
#pragma weak pthread_cond_init
#pragma weak pthread_cond_destroy
#pragma weak pthread_cond_wait
#pragma weak pthread_equal
#pragma weak pthread_self
#pragma weak pthread_key_create
#pragma weak pthread_key_delete
#pragma weak pthread_cond_signal
74 75 76 77 78 79 80

#else /* __GNUC__, __GLIBC__, __linux__ */

static int libxml_is_threaded = 1;

#endif /* __GNUC__, __GLIBC__, __linux__ */

81 82
#endif /* HAVE_PTHREAD_H */

83 84 85 86 87 88 89 90 91 92 93 94
/*
 * 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;
95
#elif defined HAVE_WIN32_THREADS
96
    HANDLE mutex;
97
#elif defined HAVE_BEOS_THREADS
98 99
    sem_id sem;
    thread_id tid;
100 101 102 103 104 105 106 107 108 109 110
#else
    int empty;
#endif
};

/*
 * xmlRMutex are reentrant mutual exception locks
 */
struct _xmlRMutex {
#ifdef HAVE_PTHREAD_H
    pthread_mutex_t lock;
111 112 113 114
    unsigned int held;
    unsigned int waiters;
    pthread_t tid;
    pthread_cond_t cv;
115
#elif defined HAVE_WIN32_THREADS
116 117
    CRITICAL_SECTION cs;
    unsigned int count;
118
#elif defined HAVE_BEOS_THREADS
119 120 121
    xmlMutexPtr lock;
    thread_id tid;
    int32 count;
122 123 124 125
#else
    int empty;
#endif
};
126

127 128 129 130 131
/*
 * This module still has some internal static data.
 *   - xmlLibraryLock a global lock
 *   - globalkey used for per-thread data
 */
132

133
#ifdef HAVE_PTHREAD_H
134 135
static pthread_key_t globalkey;
static pthread_t mainthread;
136
static pthread_once_t once_control = PTHREAD_ONCE_INIT;
137
static pthread_once_t once_control_init = PTHREAD_ONCE_INIT;
138
static pthread_mutex_t global_init_lock = PTHREAD_MUTEX_INITIALIZER;
139
#elif defined HAVE_WIN32_THREADS
140 141 142 143
#if defined(HAVE_COMPILER_TLS)
static __declspec(thread) xmlGlobalState tlstate;
static __declspec(thread) int tlstate_inited = 0;
#else /* HAVE_COMPILER_TLS */
144
static DWORD globalkey = TLS_OUT_OF_INDEXES;
145
#endif /* HAVE_COMPILER_TLS */
146
static DWORD mainthread;
147
static struct {
148
    DWORD done;
149
    LONG control;
150
} run_once = { 0, 0};
151
static volatile LPCRITICAL_SECTION global_init_lock = NULL;
152

153 154 155 156 157
/* endif HAVE_WIN32_THREADS */
#elif defined HAVE_BEOS_THREADS
int32 globalkey = 0;
thread_id mainthread = 0;
int32 run_once_init = 0;
158 159
static int32 global_init_lock = -1;
static vint32 global_init_count = 0;
160
#endif
161

162 163
static xmlRMutexPtr xmlLibraryLock = NULL;

164
#ifdef LIBXML_THREAD_ENABLED
165
static void xmlOnceInit(void);
166
#endif
167 168

/**
169
 * xmlNewMutex:
170 171 172 173 174 175 176 177 178 179 180 181 182 183
 *
 * 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
184
    if (libxml_is_threaded != 0)
185
        pthread_mutex_init(&tok->lock, NULL);
186
#elif defined HAVE_WIN32_THREADS
187
    tok->mutex = CreateMutex(NULL, FALSE, NULL);
188
#elif defined HAVE_BEOS_THREADS
189 190 191 192 193
    if ((tok->sem = create_sem(1, "xmlMutex")) < B_OK) {
        free(tok);
        return NULL;
    }
    tok->tid = -1;
194 195 196 197 198 199 200 201 202 203 204 205 206 207
#endif
    return (tok);
}

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

211
#ifdef HAVE_PTHREAD_H
212
    if (libxml_is_threaded != 0)
213
        pthread_mutex_destroy(&tok->lock);
214
#elif defined HAVE_WIN32_THREADS
215
    CloseHandle(tok->mutex);
216
#elif defined HAVE_BEOS_THREADS
217
    delete_sem(tok->sem);
218 219 220 221 222 223 224 225 226 227 228
#endif
    free(tok);
}

/**
 * xmlMutexLock:
 * @tok:  the simple mutex
 *
 * xmlMutexLock() is used to lock a libxml2 token.
 */
void
229
xmlMutexLock(xmlMutexPtr tok)
230
{
231 232
    if (tok == NULL)
        return;
233
#ifdef HAVE_PTHREAD_H
234
    if (libxml_is_threaded != 0)
235
        pthread_mutex_lock(&tok->lock);
236
#elif defined HAVE_WIN32_THREADS
237
    WaitForSingleObject(tok->mutex, INFINITE);
238
#elif defined HAVE_BEOS_THREADS
239
    if (acquire_sem(tok->sem) != B_NO_ERROR) {
240
#ifdef DEBUG_THREADS
241 242
        xmlGenericError(xmlGenericErrorContext,
                        "xmlMutexLock():BeOS:Couldn't aquire semaphore\n");
243
#endif
244 245
    }
    tok->tid = find_thread(NULL);
246 247 248 249 250 251 252 253 254 255 256
#endif

}

/**
 * xmlMutexUnlock:
 * @tok:  the simple mutex
 *
 * xmlMutexUnlock() is used to unlock a libxml2 token.
 */
void
257
xmlMutexUnlock(xmlMutexPtr tok)
258
{
259 260
    if (tok == NULL)
        return;
261
#ifdef HAVE_PTHREAD_H
262
    if (libxml_is_threaded != 0)
263
        pthread_mutex_unlock(&tok->lock);
264
#elif defined HAVE_WIN32_THREADS
265
    ReleaseMutex(tok->mutex);
266
#elif defined HAVE_BEOS_THREADS
267 268 269 270
    if (tok->tid == find_thread(NULL)) {
        tok->tid = -1;
        release_sem(tok->sem);
    }
271 272 273 274
#endif
}

/**
275
 * xmlNewRMutex:
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
 *
 * 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
292
    if (libxml_is_threaded != 0) {
293 294 295 296
        pthread_mutex_init(&tok->lock, NULL);
        tok->held = 0;
        tok->waiters = 0;
        pthread_cond_init(&tok->cv, NULL);
297
    }
298
#elif defined HAVE_WIN32_THREADS
299 300
    InitializeCriticalSection(&tok->cs);
    tok->count = 0;
301
#elif defined HAVE_BEOS_THREADS
302 303 304 305 306
    if ((tok->lock = xmlNewMutex()) == NULL) {
        free(tok);
        return NULL;
    }
    tok->count = 0;
307 308 309 310 311
#endif
    return (tok);
}

/**
312
 * xmlFreeRMutex:
313 314 315 316 317 318
 * @tok:  the reentrant mutex
 *
 * xmlRFreeMutex() is used to reclaim resources associated with a
 * reentrant mutex.
 */
void
319
xmlFreeRMutex(xmlRMutexPtr tok ATTRIBUTE_UNUSED)
320
{
321 322
    if (tok == NULL)
        return;
323
#ifdef HAVE_PTHREAD_H
324
    if (libxml_is_threaded != 0) {
325 326
        pthread_mutex_destroy(&tok->lock);
        pthread_cond_destroy(&tok->cv);
327
    }
328
#elif defined HAVE_WIN32_THREADS
329
    DeleteCriticalSection(&tok->cs);
330
#elif defined HAVE_BEOS_THREADS
331
    xmlFreeMutex(tok->lock);
332 333 334 335 336 337 338 339 340 341 342
#endif
    free(tok);
}

/**
 * xmlRMutexLock:
 * @tok:  the reentrant mutex
 *
 * xmlRMutexLock() is used to lock a libxml2 token_r.
 */
void
343
xmlRMutexLock(xmlRMutexPtr tok)
344
{
345 346
    if (tok == NULL)
        return;
347
#ifdef HAVE_PTHREAD_H
348 349 350
    if (libxml_is_threaded == 0)
        return;

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    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);
367
#elif defined HAVE_WIN32_THREADS
368
    EnterCriticalSection(&tok->cs);
369
    tok->count++;
370
#elif defined HAVE_BEOS_THREADS
371 372 373 374 375 376 377
    if (tok->lock->tid == find_thread(NULL)) {
        tok->count++;
        return;
    } else {
        xmlMutexLock(tok->lock);
        tok->count = 1;
    }
378 379 380 381 382 383 384 385 386 387
#endif
}

/**
 * xmlRMutexUnlock:
 * @tok:  the reentrant mutex
 *
 * xmlRMutexUnlock() is used to unlock a libxml2 token_r.
 */
void
388
xmlRMutexUnlock(xmlRMutexPtr tok ATTRIBUTE_UNUSED)
389
{
390 391
    if (tok == NULL)
        return;
392
#ifdef HAVE_PTHREAD_H
393 394
    if (libxml_is_threaded == 0)
        return;
395

396 397 398 399 400
    pthread_mutex_lock(&tok->lock);
    tok->held--;
    if (tok->held == 0) {
        if (tok->waiters)
            pthread_cond_signal(&tok->cv);
401
        memset(&tok->tid, 0, sizeof(tok->tid));
402 403
    }
    pthread_mutex_unlock(&tok->lock);
404
#elif defined HAVE_WIN32_THREADS
405 406
    if (tok->count > 0) {
	tok->count--;
407
        LeaveCriticalSection(&tok->cs);
408
    }
409
#elif defined HAVE_BEOS_THREADS
410 411 412 413 414 415 416
    if (tok->lock->tid == find_thread(NULL)) {
        tok->count--;
        if (tok->count == 0) {
            xmlMutexUnlock(tok->lock);
        }
        return;
    }
417 418 419
#endif
}

420 421 422 423 424 425 426 427 428 429 430 431
/**
 * 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. */
432 433 434 435 436
#ifdef XML_PTHREAD_WEAK
    if (pthread_mutex_lock == NULL)
        return;
#endif /* XML_PTHREAD_WEAK */
    pthread_mutex_lock(&global_init_lock);
437 438 439 440 441
#elif defined HAVE_WIN32_THREADS
    LPCRITICAL_SECTION cs;

    /* Create a new critical section */
    if (global_init_lock == NULL) {
442 443 444 445 446 447 448
        cs = malloc(sizeof(CRITICAL_SECTION));
        if (cs == NULL) {
            xmlGenericError(xmlGenericErrorContext,
                            "xmlGlobalInitMutexLock: out of memory\n");
            return;
        }
        InitializeCriticalSection(cs);
449

450
        /* Swap it into the global_init_lock */
451
#ifdef InterlockedCompareExchangePointer
452 453
        InterlockedCompareExchangePointer((void **) &global_init_lock,
                                          cs, NULL);
454 455 456
#else /* Use older void* version */
        InterlockedCompareExchange((void **) &global_init_lock,
                                   (void *) cs, NULL);
457
#endif /* InterlockedCompareExchangePointer */
458

459 460 461 462 463 464 465
        /* 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);
        }
466 467 468 469 470 471 472 473 474 475 476
    }

    /* 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) {
477 478 479 480 481 482
        if (atomic_add(&global_init_count, 1) == 0) {
            global_init_lock = sem;
        } else {
            snooze(1);
            atomic_add(&global_init_count, -1);
        }
483 484 485 486 487 488
    }

    /* 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)
489
        delete_sem(sem);
490 491 492 493

    /* Acquire the chosen semaphore */
    if (acquire_sem(global_init_lock) != B_NO_ERROR) {
#ifdef DEBUG_THREADS
494 495
        xmlGenericError(xmlGenericErrorContext,
                        "xmlGlobalInitMutexLock():BeOS:Couldn't acquire semaphore\n");
496 497 498 499 500 501 502 503 504
#endif
    }
#endif
}

void
__xmlGlobalInitMutexUnlock(void)
{
#ifdef HAVE_PTHREAD_H
505 506 507 508 509
#ifdef XML_PTHREAD_WEAK
    if (pthread_mutex_unlock == NULL)
        return;
#endif /* XML_PTHREAD_WEAK */
    pthread_mutex_unlock(&global_init_lock);
510
#elif defined HAVE_WIN32_THREADS
511 512 513
    if (global_init_lock != NULL) {
	LeaveCriticalSection(global_init_lock);
    }
514 515 516 517 518
#elif defined HAVE_BEOS_THREADS
    release_sem(global_init_lock);
#endif
}

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

538 539 540 541 542 543
/************************************************************************
 *									*
 *			Per thread global state handling		*
 *									*
 ************************************************************************/

544
#ifdef LIBXML_THREAD_ENABLED
545 546 547
#ifdef xmlLastError
#undef xmlLastError
#endif
548

549 550 551 552 553 554 555 556 557 558
/**
 * 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)
{
559 560 561 562
    xmlGlobalState *gs = (xmlGlobalState *) state;

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

580
    gs = malloc(sizeof(xmlGlobalState));
581 582 583 584 585
    if (gs == NULL) {
	xmlGenericError(xmlGenericErrorContext,
			"xmlGetGlobalState: out of memory\n");
        return (NULL);
    }
586

William M. Brack's avatar
William M. Brack committed
587
    memset(gs, 0, sizeof(xmlGlobalState));
588 589 590
    xmlInitializeGlobalState(gs);
    return (gs);
}
591
#endif /* LIBXML_THREAD_ENABLED */
592

593
#ifdef HAVE_PTHREAD_H
594
#elif defined HAVE_WIN32_THREADS
595 596
#if !defined(HAVE_COMPILER_TLS)
#if defined(LIBXML_STATIC) && !defined(LIBXML_STATIC_FOR_DLL)
597
typedef struct _xmlGlobalStateCleanupHelperParams {
598 599
    HANDLE thread;
    void *memory;
600 601
} xmlGlobalStateCleanupHelperParams;

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

615
typedef struct _xmlGlobalStateCleanupHelperParams {
616
    void *memory;
617 618
    struct _xmlGlobalStateCleanupHelperParams *prev;
    struct _xmlGlobalStateCleanupHelperParams *next;
619 620
} xmlGlobalStateCleanupHelperParams;

621
static xmlGlobalStateCleanupHelperParams *cleanup_helpers_head = NULL;
622 623 624 625
static CRITICAL_SECTION cleanup_helpers_cs;

#endif /* LIBXMLSTATIC && !LIBXML_STATIC_FOR_DLL */
#endif /* HAVE_COMPILER_TLS */
626 627
#endif /* HAVE_WIN32_THREADS */

628
#if defined HAVE_BEOS_THREADS
629

630 631 632 633 634 635
/**
 * xmlGlobalStateCleanup:
 * @data: unused parameter
 *
 * Used for Beos only
 */
636 637
void
xmlGlobalStateCleanup(void *data)
638
{
639 640 641 642
    void *globalval = tls_get(globalkey);

    if (globalval != NULL)
        xmlFreeGlobalState(globalval);
643 644 645
}
#endif

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

659
    if (libxml_is_threaded == 0)
660
        return (NULL);
661

662 663
    pthread_once(&once_control, xmlOnceInit);

664
    if ((globalval = (xmlGlobalState *)
665
         pthread_getspecific(globalkey)) == NULL) {
666
        xmlGlobalState *tsd = xmlNewGlobalState();
667 668
	if (tsd == NULL)
	    return(NULL);
669 670 671

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

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

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

724
        return (tsd);
725 726 727
    }
    return (globalval);
#endif /* HAVE_COMPILER_TLS */
728 729 730 731 732
#elif defined HAVE_BEOS_THREADS
    xmlGlobalState *globalval;

    xmlOnceInit();

733
    if ((globalval = (xmlGlobalState *) tls_get(globalkey)) == NULL) {
734
        xmlGlobalState *tsd = xmlNewGlobalState();
735 736
	if (tsd == NULL)
	    return (NULL);
737 738 739 740 741 742

        tls_set(globalkey, tsd);
        on_exit_thread(xmlGlobalStateCleanup, NULL);
        return (tsd);
    }
    return (globalval);
743
#else
744
    return (NULL);
745 746 747 748 749 750 751 752 753
#endif
}

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

754 755 756 757
/**
 * xmlGetThreadId:
 *
 * xmlGetThreadId() find the current thread ID number
758 759
 * 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
760 761 762 763 764 765 766
 *
 * Returns the current thread ID number
 */
int
xmlGetThreadId(void)
{
#ifdef HAVE_PTHREAD_H
767 768 769
    pthread_t id;
    int ret;

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

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

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

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

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

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

880
/* fprintf(stderr, "Running multithreaded\n"); */
881 882
        } else {

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

/**
 * xmlCleanupThreads:
 *
 * xmlCleanupThreads() is used to to cleanup all the thread related
 * data of the libxml2 library once processing has ended.
898 899 900 901 902 903 904 905
 *
 * 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 !
906 907 908 909
 */
void
xmlCleanupThreads(void)
{
910 911 912
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlCleanupThreads()\n");
#endif
913
#ifdef HAVE_PTHREAD_H
914
    if (libxml_is_threaded != 0)
915
        pthread_key_delete(globalkey);
916
    once_control = once_control_init;
917
#elif defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS) && (!defined(LIBXML_STATIC) || defined(LIBXML_STATIC_FOR_DLL))
918
    if (globalkey != TLS_OUT_OF_INDEXES) {
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
        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;
934 935 936
    }
    DeleteCriticalSection(&cleanup_helpers_cs);
#endif
937
}
938

939
#ifdef LIBXML_THREAD_ENABLED
940

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

/**
986 987 988 989
 * DllMain:
 * @hinstDLL: handle to DLL instance
 * @fdwReason: Reason code for entry
 * @lpvReserved: generic pointer (depends upon reason code)
990 991 992
 *
 * Entry point for Windows library. It is being used to free thread-specific
 * storage.
993 994
 *
 * Returns TRUE always
995
 */
996 997
#ifdef HAVE_PTHREAD_H
#elif defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS) && (!defined(LIBXML_STATIC) || defined(LIBXML_STATIC_FOR_DLL))
998
#if defined(LIBXML_STATIC_FOR_DLL)
999 1000 1001
int XMLCALL
xmlDllMain(ATTRIBUTE_UNUSED void *hinstDLL, unsigned long fdwReason,
           ATTRIBUTE_UNUSED void *lpvReserved)
1002
#else
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
/* declare to avoid "no previous prototype for 'DllMain'" warning */
/* Note that we do NOT want to include this function declaration in
   a public header because it's meant to be called by Windows itself,
   not a program that uses this library.  This also has to be exported. */

XMLPUBFUN BOOL WINAPI
DllMain (HINSTANCE hinstDLL,
         DWORD     fdwReason,
         LPVOID    lpvReserved);

1013
BOOL WINAPI
1014 1015
DllMain(ATTRIBUTE_UNUSED HINSTANCE hinstDLL, DWORD fdwReason,
        ATTRIBUTE_UNUSED LPVOID lpvReserved)
1016
#endif
1017
{
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    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);
                }
1041
            }
1042
            break;
1043 1044 1045 1046
    }
    return TRUE;
}
#endif
1047 1048
#define bottom_threads
#include "elfgcchack.h"