threads.c 12.8 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
static void xmlOnceInit(void);
103 104

/**
105
 * xmlNewMutex:
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
 *
 * 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);
121
#elif defined HAVE_WIN32_THREADS
122
    tok->mutex = CreateMutex(NULL, FALSE, NULL);
123 124 125 126 127 128 129 130 131 132 133 134 135 136
#endif
    return (tok);
}

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

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

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

}

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

/**
185
 * xmlNewRMutex:
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
 *
 * 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;
205
    pthread_cond_init(&tok->cv, NULL);
206
#elif defined HAVE_WIN32_THREADS
207 208
    InitializeCriticalSection(&tok->cs);
    tok->count = 0;
209 210 211 212 213
#endif
    return (tok);
}

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

/**
 * xmlRMutexLock:
 * @tok:  the reentrant mutex
 *
 * xmlRMutexLock() is used to lock a libxml2 token_r.
 */
void
238
xmlRMutexLock(xmlRMutexPtr tok ATTRIBUTE_UNUSED)
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
{
#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);
257
#elif defined HAVE_WIN32_THREADS
258 259
    EnterCriticalSection(&tok->cs);
    ++tok->count;
260 261 262 263 264 265 266 267 268 269
#endif
}

/**
 * xmlRMutexUnlock:
 * @tok:  the reentrant mutex
 *
 * xmlRMutexUnlock() is used to unlock a libxml2 token_r.
 */
void
270
xmlRMutexUnlock(xmlRMutexPtr tok ATTRIBUTE_UNUSED)
271 272 273 274 275 276 277 278 279 280
{
#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);
281
#elif defined HAVE_WIN32_THREADS
282 283
    if (!--tok->count) 
	LeaveCriticalSection(&tok->cs);
284 285 286 287 288 289 290 291 292
#endif
}

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

293
#ifdef LIBXML_THREAD_ENABLED
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
/**
 * 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
312
 * of libxml2 to pre-thread-safe behaviour.
313 314 315 316 317 318 319 320 321 322 323 324
 *
 * 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
325
    memset(gs, 0, sizeof(xmlGlobalState));
326 327 328
    xmlInitializeGlobalState(gs);
    return (gs);
}
329
#endif /* LIBXML_THREAD_ENABLED */
330 331


332
#ifdef HAVE_WIN32_THREADS
333
#if !defined(HAVE_COMPILER_TLS) && defined(LIBXML_STATIC)
334 335
typedef struct _xmlGlobalStateCleanupHelperParams
{
336 337
    HANDLE thread;
    void *memory;
338 339
} xmlGlobalStateCleanupHelperParams;

340
static void xmlGlobalStateCleanupHelper (void *p)
341
{
342 343 344 345 346 347
    xmlGlobalStateCleanupHelperParams *params = (xmlGlobalStateCleanupHelperParams *) p;
    WaitForSingleObject(params->thread, INFINITE);
    CloseHandle(params->thread);
    xmlFreeGlobalState(params->memory);
    free(params);
    _endthread();
348
}
349
#endif /* HAVE_COMPILER_TLS && LIBXML_STATIC */
350 351
#endif /* HAVE_WIN32_THREADS */

352 353 354 355 356 357 358
/**
 * xmlGetGlobalState:
 *
 * xmlGetGlobalState() is called to retrieve the global state for a thread.
 *
 * Returns the thread global state or NULL in case of error
 */
359 360 361 362 363 364
xmlGlobalStatePtr
xmlGetGlobalState(void)
{
#ifdef HAVE_PTHREAD_H
    xmlGlobalState *globalval;

365 366
    pthread_once(&once_control, xmlOnceInit);

367
    if ((globalval = (xmlGlobalState *)
368
		pthread_getspecific(globalkey)) == NULL) {
369 370 371 372
        xmlGlobalState *tsd = xmlNewGlobalState();

        pthread_setspecific(globalkey, tsd);
        return (tsd);
373 374
    }
    return (globalval);
375
#elif defined HAVE_WIN32_THREADS
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
#if defined(HAVE_COMPILER_TLS)
    if (!tlstate_inited) {
	tlstate_inited = 1;
	xmlInitializeGlobalState(&tlstate);
    }
    return &tlstate;
#else /* HAVE_COMPILER_TLS */
    xmlGlobalState *globalval;

    if (run_once_init) { 
	run_once_init = 0; 
	xmlOnceInit(); 
    }
    if ((globalval = (xmlGlobalState *) TlsGetValue(globalkey)) == NULL) {
	xmlGlobalState *tsd = xmlNewGlobalState();
391
#if defined(LIBXML_STATIC)
392 393 394 395 396
	xmlGlobalStateCleanupHelperParams *p = 
	    (xmlGlobalStateCleanupHelperParams *) malloc(sizeof(xmlGlobalStateCleanupHelperParams));
	p->memory = tsd;
	DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), 
		GetCurrentProcess(), &p->thread, 0, TRUE, DUPLICATE_SAME_ACCESS);
397
#endif
398
	TlsSetValue(globalkey, tsd);
399
#if defined(LIBXML_STATIC)
400
	_beginthread(xmlGlobalStateCleanupHelper, 0, p);
401
#endif
402 403 404 405 406

	return (tsd);
    }
    return (globalval);
#endif /* HAVE_COMPILER_TLS */
407 408
#else
    return(NULL);
409 410 411 412 413 414 415 416 417
#endif
}

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

418 419 420 421 422 423 424 425 426 427 428 429
/**
 * 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());
430
#elif defined HAVE_WIN32_THREADS
431
    return GetCurrentThreadId();
432 433 434 435 436
#else
    return((int) 0);
#endif
}

437 438 439
/**
 * xmlIsMainThread:
 *
440
 * xmlIsMainThread() check whether the current thread is the main thread.
441 442 443 444 445 446
 *
 * Returns 1 if the current thread is the main thread, 0 otherwise
 */
int
xmlIsMainThread(void)
{
447 448
#ifdef HAVE_PTHREAD_H
    pthread_once(&once_control, xmlOnceInit);
449
#elif defined HAVE_WIN32_THREADS
450 451 452 453
    if (run_once_init) { 
	run_once_init = 0; 
	xmlOnceInit (); 
    }
454
#endif
455 456 457 458 459 460
        
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlIsMainThread()\n");
#endif
#ifdef HAVE_PTHREAD_H
    return(mainthread == pthread_self());
461
#elif defined HAVE_WIN32_THREADS
462
    return(mainthread == GetCurrentThreadId ());
463 464 465 466 467
#else
    return(1);
#endif
}

468 469 470 471 472 473 474 475 476
/**
 * xmlLockLibrary:
 *
 * xmlLockLibrary() is used to take out a re-entrant lock on the libxml2
 * library.
 */
void
xmlLockLibrary(void)
{
477 478 479
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlLockLibrary()\n");
#endif
480 481 482 483 484 485 486 487 488 489 490 491
    xmlRMutexLock(xmlLibraryLock);
}

/**
 * xmlUnlockLibrary:
 *
 * xmlUnlockLibrary() is used to release a re-entrant lock on the libxml2
 * library.
 */
void
xmlUnlockLibrary(void)
{
492 493 494
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlUnlockLibrary()\n");
#endif
495 496 497 498 499 500 501 502 503 504 505 506
    xmlRMutexUnlock(xmlLibraryLock);
}

/**
 * xmlInitThreads:
 *
 * xmlInitThreads() is used to to initialize all the thread related
 * data of the libxml2 library.
 */
void
xmlInitThreads(void)
{
507 508 509
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlInitThreads()\n");
#endif
510 511 512 513 514 515 516 517 518 519 520
}

/**
 * xmlCleanupThreads:
 *
 * xmlCleanupThreads() is used to to cleanup all the thread related
 * data of the libxml2 library once processing has ended.
 */
void
xmlCleanupThreads(void)
{
521 522 523
#ifdef DEBUG_THREADS
    xmlGenericError(xmlGenericErrorContext, "xmlCleanupThreads()\n");
#endif
524
}
525

526 527 528 529 530 531 532 533 534 535 536 537
/**
 * 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
538
    (void) pthread_key_create(&globalkey, xmlFreeGlobalState);
539
    mainthread = pthread_self();
540 541 542 543 544 545 546
#endif

#if defined(HAVE_WIN32_THREADS)
#if !defined(HAVE_COMPILER_TLS)
    globalkey = TlsAlloc();
#endif
    mainthread = GetCurrentThreadId();
547
#endif
548
}
549 550

/**
551 552 553 554
 * DllMain:
 * @hinstDLL: handle to DLL instance
 * @fdwReason: Reason code for entry
 * @lpvReserved: generic pointer (depends upon reason code)
555 556 557
 *
 * Entry point for Windows library. It is being used to free thread-specific
 * storage.
558 559
 *
 * Returns TRUE always
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
 */
#if defined(HAVE_WIN32_THREADS) && !defined(LIBXML_STATIC)
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) 
{
    switch(fdwReason) {
    case DLL_THREAD_DETACH:
	if (globalkey != TLS_OUT_OF_INDEXES) {
	    xmlGlobalState *globalval = (xmlGlobalState *)TlsGetValue(globalkey);
	    if (globalval) {
		xmlFreeGlobalState(globalval);
		TlsSetValue(globalkey, NULL);
	    }
	}
	break;
    case DLL_PROCESS_DETACH:
	if (globalkey != TLS_OUT_OF_INDEXES) {
	    TlsFree(globalkey);
	    globalkey = TLS_OUT_OF_INDEXES;
	}
	break;
    }
    return TRUE;
}
#endif