pthread.c 16.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * pthread emulation for re-entrant libcs
 *
 * Copyright 1999 Ove Kven
 * Copyright 2003 Alexandre Julliard
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 21 22 23 24
 */

#include "config.h"
#include "wine/port.h"

25 26
#ifdef HAVE_PTHREAD_H

27 28 29 30
#define _GNU_SOURCE /* we may need to override some GNU extensions */

#include <assert.h>
#include <errno.h>
31
#include <stdarg.h>
32 33 34 35 36 37 38
#include <stdlib.h>
#include <setjmp.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <string.h>
#include <sys/types.h>
39
#ifdef HAVE_SYS_SOCKET_H
40 41 42 43 44 45
# include <sys/socket.h>
#endif
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif

46
#include "windef.h"
47 48
#include "winbase.h"
#include "winternl.h"
49
#include "kernel_private.h"
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
#include "wine/pthread.h"

#define P_OUTPUT(stuff) write(2,stuff,strlen(stuff))

/* NOTE: This is a truly extremely incredibly ugly hack!
 * But it does seem to work... */

/* assume that pthread_mutex_t has room for at least one pointer,
 * and hope that the users of pthread_mutex_t considers it opaque
 * (never checks what's in it)
 * also: assume that static initializer sets pointer to NULL
 */
typedef struct
{
#ifdef __GLIBC__
  int reserved;
#endif
  CRITICAL_SECTION *critsect;
} *wine_mutex;

/* see wine_mutex above for comments */
typedef struct {
  RTL_RWLOCK *lock;
} *wine_rwlock;

struct pthread_thread_init
{
    void* (*start_routine)(void*);
    void* arg;
};

static DWORD CALLBACK pthread_thread_start(LPVOID data)
{
  struct pthread_thread_init init = *(struct pthread_thread_init*)data;
  HeapFree(GetProcessHeap(),0,data);
85
  return (DWORD_PTR)init.start_routine(init.arg);
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
}

static int wine_pthread_create(pthread_t* thread, const pthread_attr_t* attr, void*
                               (*start_routine)(void *), void* arg)
{
  HANDLE hThread;
  struct pthread_thread_init* idata = HeapAlloc(GetProcessHeap(), 0, sizeof(struct pthread_thread_init));

  idata->start_routine = start_routine;
  idata->arg = arg;
  hThread = CreateThread( NULL, 0, pthread_thread_start, idata, 0, (LPDWORD)thread);

  if(hThread)
    CloseHandle(hThread);
  else
  {
    HeapFree(GetProcessHeap(),0,idata); /* free idata struct on failure */
    return EAGAIN;
  }

  return 0;
}

static int wine_pthread_cancel(pthread_t thread)
{
  HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, (DWORD)thread);

  if(!TerminateThread(hThread, 0))
  {
    CloseHandle(hThread);
    return EINVAL;      /* return error */
  }

  CloseHandle(hThread);

  return 0;             /* return success */
}

static int wine_pthread_join(pthread_t thread, void **value_ptr)
{
  HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, (DWORD)thread);

  WaitForSingleObject(hThread, INFINITE);
  if(!GetExitCodeThread(hThread, (LPDWORD)value_ptr))
  {
    CloseHandle(hThread);
    return EINVAL; /* FIXME: make this more correctly match */
  }                /* windows errors */

  CloseHandle(hThread);
  return 0;
}

/*FIXME: not sure what to do with this one... */
static int wine_pthread_detach(pthread_t thread)
{
  P_OUTPUT("FIXME:pthread_detach\n");
  return 0;
}

/***** MUTEXES *****/

static int wine_pthread_mutex_init(pthread_mutex_t *mutex,
                                   const pthread_mutexattr_t *mutexattr)
{
  /* glibc has a tendency to initialize mutexes very often, even
     in situations where they are not really used later on.

     As for us, initializing a mutex is very expensive, we postpone
     the real initialization until the time the mutex is first used. */

  ((wine_mutex)mutex)->critsect = NULL;
  return 0;
}

static void mutex_real_init( pthread_mutex_t *mutex )
{
  CRITICAL_SECTION *critsect = HeapAlloc(GetProcessHeap(), 0, sizeof(CRITICAL_SECTION));
  RtlInitializeCriticalSection(critsect);

  if (InterlockedCompareExchangePointer((void**)&(((wine_mutex)mutex)->critsect),critsect,NULL) != NULL) {
    /* too late, some other thread already did it */
    RtlDeleteCriticalSection(critsect);
    HeapFree(GetProcessHeap(), 0, critsect);
  }
}

static int wine_pthread_mutex_lock(pthread_mutex_t *mutex)
{
  if (!((wine_mutex)mutex)->critsect)
    mutex_real_init( mutex );

  RtlEnterCriticalSection(((wine_mutex)mutex)->critsect);
  return 0;
}

static int wine_pthread_mutex_trylock(pthread_mutex_t *mutex)
{
  if (!((wine_mutex)mutex)->critsect)
    mutex_real_init( mutex );

187
  if (!RtlTryEnterCriticalSection(((wine_mutex)mutex)->critsect)) return EBUSY;
188 189 190 191 192
  return 0;
}

static int wine_pthread_mutex_unlock(pthread_mutex_t *mutex)
{
193 194 195
    CRITICAL_SECTION *crit = ((wine_mutex)mutex)->critsect;

    if (!crit) return 0;
196
    if (crit->OwningThread != ULongToHandle(GetCurrentThreadId())) return EPERM;
197 198
    RtlLeaveCriticalSection( crit );
    return 0;
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
}

static int wine_pthread_mutex_destroy(pthread_mutex_t *mutex)
{
  if (!((wine_mutex)mutex)->critsect) return 0;
  if (((wine_mutex)mutex)->critsect->RecursionCount) {
#if 0 /* there seems to be a bug in libc6 that makes this a bad idea */
    return EBUSY;
#else
    while (((wine_mutex)mutex)->critsect->RecursionCount)
      RtlLeaveCriticalSection(((wine_mutex)mutex)->critsect);
#endif
  }
  RtlDeleteCriticalSection(((wine_mutex)mutex)->critsect);
  HeapFree(GetProcessHeap(), 0, ((wine_mutex)mutex)->critsect);
  ((wine_mutex)mutex)->critsect = NULL;
  return 0;
}

/***** READ-WRITE LOCKS *****/

static void rwlock_real_init(pthread_rwlock_t *rwlock)
{
  RTL_RWLOCK *lock = HeapAlloc(GetProcessHeap(), 0, sizeof(RTL_RWLOCK));
  RtlInitializeResource(lock);

  if (InterlockedCompareExchangePointer((void**)&(((wine_rwlock)rwlock)->lock),lock,NULL) != NULL) {
    /* too late, some other thread already did it */
    RtlDeleteResource(lock);
    HeapFree(GetProcessHeap(), 0, lock);
  }
}

static int wine_pthread_rwlock_init(pthread_rwlock_t *rwlock, const pthread_rwlockattr_t *rwlock_attr)
{
  ((wine_rwlock)rwlock)->lock = NULL;
  return 0;
}

static int wine_pthread_rwlock_destroy(pthread_rwlock_t *rwlock)
{
  if (!((wine_rwlock)rwlock)->lock) return 0;
  RtlDeleteResource(((wine_rwlock)rwlock)->lock);
  HeapFree(GetProcessHeap(), 0, ((wine_rwlock)rwlock)->lock);
  return 0;
}

static int wine_pthread_rwlock_rdlock(pthread_rwlock_t *rwlock)
{
  if (!((wine_rwlock)rwlock)->lock)
    rwlock_real_init( rwlock );

  while(TRUE)
    if (RtlAcquireResourceShared(((wine_rwlock)rwlock)->lock, TRUE))
      return 0;
}

static int wine_pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock)
{
  if (!((wine_rwlock)rwlock)->lock)
    rwlock_real_init( rwlock );

261
  if (!RtlAcquireResourceShared(((wine_rwlock)rwlock)->lock, FALSE)) return EBUSY;
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
  return 0;
}

static int wine_pthread_rwlock_wrlock(pthread_rwlock_t *rwlock)
{
  if (!((wine_rwlock)rwlock)->lock)
    rwlock_real_init( rwlock );

  while(TRUE)
    if (RtlAcquireResourceExclusive(((wine_rwlock)rwlock)->lock, TRUE))
      return 0;
}

static int wine_pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock)
{
  if (!((wine_rwlock)rwlock)->lock)
    rwlock_real_init( rwlock );

280
  if (!RtlAcquireResourceExclusive(((wine_rwlock)rwlock)->lock, FALSE)) return EBUSY;
281 282 283 284 285 286 287 288 289 290
  return 0;
}

static int wine_pthread_rwlock_unlock(pthread_rwlock_t *rwlock)
{
  if (!((wine_rwlock)rwlock)->lock) return 0;
  RtlReleaseResource( ((wine_rwlock)rwlock)->lock );
  return 0;
}

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
/***** CONDITIONS *****/

/* The condition code is basically cut-and-pasted from Douglas
 * Schmidt's paper:
 *   "Strategies for Implementing POSIX Condition Variables on Win32",
 * at http://www.cs.wustl.edu/~schmidt/win32-cv-1.html and
 * http://www.cs.wustl.edu/~schmidt/win32-cv-2.html.
 * This paper formed the basis for the condition variable
 * impementation used in the ACE library.
 */

/* Possible problems with ACE:
 * - unimplemented pthread_mutexattr_init
 */
typedef struct {
  /* Number of waiting threads. */
  int waiters_count;

  /* Serialize access to <waiters_count>. */
  CRITICAL_SECTION waiters_count_lock;

  /*
   * Semaphore used to queue up threads waiting for the condition to
   * become signaled.
   */
  HANDLE sema;

  /*
   * An auto-reset event used by the broadcast/signal thread to wait
   * for all the waiting thread(s) to wake up and be released from the
   * semaphore.
   */
  HANDLE waiters_done;

  /*
   * Keeps track of whether we were broadcasting or signaling.  This
   * allows us to optimize the code if we're just signaling.
   */
  size_t was_broadcast;
} wine_cond_detail;

/* see wine_mutex above for comments */
typedef struct {
  wine_cond_detail *cond;
} *wine_cond;

static void wine_cond_real_init(pthread_cond_t *cond)
{
  wine_cond_detail *detail = HeapAlloc(GetProcessHeap(), 0, sizeof(wine_cond_detail));
  detail->waiters_count = 0;
  detail->was_broadcast = 0;
  detail->sema = CreateSemaphoreW( NULL, 0, 0x7fffffff, NULL );
  detail->waiters_done = CreateEventW( NULL, FALSE, FALSE, NULL );
  RtlInitializeCriticalSection (&detail->waiters_count_lock);

  if (InterlockedCompareExchangePointer((void**)&(((wine_cond)cond)->cond), detail, NULL) != NULL)
  {
    /* too late, some other thread already did it */
    P_OUTPUT("FIXME:pthread_cond_init:expect troubles...\n");
    CloseHandle(detail->sema);
    RtlDeleteCriticalSection(&detail->waiters_count_lock);
    CloseHandle(detail->waiters_done);
    HeapFree(GetProcessHeap(), 0, detail);
  }
}

357
static int wine_pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *cond_attr)
358 359 360 361 362 363 364
{
  /* The same as for wine_pthread_mutex_init, we postpone initialization
     until condition is really used.*/
  ((wine_cond)cond)->cond = NULL;
  return 0;
}

365
static int wine_pthread_cond_destroy(pthread_cond_t *cond)
366 367 368 369 370 371 372 373 374 375 376 377
{
  wine_cond_detail *detail = ((wine_cond)cond)->cond;

  if (!detail) return 0;
  CloseHandle(detail->sema);
  RtlDeleteCriticalSection(&detail->waiters_count_lock);
  CloseHandle(detail->waiters_done);
  HeapFree(GetProcessHeap(), 0, detail);
  ((wine_cond)cond)->cond = NULL;
  return 0;
}

378
static int wine_pthread_cond_signal(pthread_cond_t *cond)
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
{
  int have_waiters;
  wine_cond_detail *detail;

  if ( !((wine_cond)cond)->cond ) wine_cond_real_init(cond);
  detail = ((wine_cond)cond)->cond;

  RtlEnterCriticalSection (&detail->waiters_count_lock);
  have_waiters = detail->waiters_count > 0;
  RtlLeaveCriticalSection (&detail->waiters_count_lock);

  /* If there aren't any waiters, then this is a no-op. */
  if (have_waiters)
    ReleaseSemaphore(detail->sema, 1, NULL);

  return 0;
}

397
static int wine_pthread_cond_broadcast(pthread_cond_t *cond)
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
{
  int have_waiters = 0;
  wine_cond_detail *detail;

  if ( !((wine_cond)cond)->cond ) wine_cond_real_init(cond);
  detail = ((wine_cond)cond)->cond;

  /*
   * This is needed to ensure that <waiters_count> and <was_broadcast> are
   * consistent relative to each other.
   */
  RtlEnterCriticalSection (&detail->waiters_count_lock);

  if (detail->waiters_count > 0) {
    /*
     * We are broadcasting, even if there is just one waiter...
     * Record that we are broadcasting, which helps optimize
     * <pthread_cond_wait> for the non-broadcast case.
     */
    detail->was_broadcast = 1;
    have_waiters = 1;
  }

  if (have_waiters) {
    /* Wake up all the waiters atomically. */
    ReleaseSemaphore(detail->sema, detail->waiters_count, NULL);

    RtlLeaveCriticalSection (&detail->waiters_count_lock);

    /* Wait for all the awakened threads to acquire the counting semaphore. */
    WaitForSingleObject (detail->waiters_done, INFINITE);

    /*
     * This assignment is okay, even without the <waiters_count_lock> held
     * because no other waiter threads can wake up to access it.
     */
    detail->was_broadcast = 0;
  }
  else
    RtlLeaveCriticalSection (&detail->waiters_count_lock);
  return 0;
}

441
static int wine_pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
{
  wine_cond_detail *detail;
  int last_waiter;

  if ( !((wine_cond)cond)->cond ) wine_cond_real_init(cond);
  detail = ((wine_cond)cond)->cond;

  /* Avoid race conditions. */
  RtlEnterCriticalSection (&detail->waiters_count_lock);
  detail->waiters_count++;
  RtlLeaveCriticalSection (&detail->waiters_count_lock);

  RtlLeaveCriticalSection ( ((wine_mutex)mutex)->critsect );
  WaitForSingleObject(detail->sema, INFINITE);

  /* Reacquire lock to avoid race conditions. */
  RtlEnterCriticalSection (&detail->waiters_count_lock);

  /* We're no longer waiting... */
  detail->waiters_count--;

  /* Check to see if we're the last waiter after <pthread_cond_broadcast>. */
  last_waiter = detail->was_broadcast && detail->waiters_count == 0;

  RtlLeaveCriticalSection (&detail->waiters_count_lock);

  /*
   * If we're the last waiter thread during this particular broadcast
   * then let all the other threads proceed.
   */
  if (last_waiter) SetEvent(detail->waiters_done);
  RtlEnterCriticalSection (((wine_mutex)mutex)->critsect);
  return 0;
}

477 478
static int wine_pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
                                       const struct timespec *abstime)
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
{
  DWORD ms = abstime->tv_sec * 1000 + abstime->tv_nsec / 1000000;
  int last_waiter;
  wine_cond_detail *detail;

  if ( !((wine_cond)cond)->cond ) wine_cond_real_init(cond);
  detail = ((wine_cond)cond)->cond;

  /* Avoid race conditions. */
  RtlEnterCriticalSection (&detail->waiters_count_lock);
  detail->waiters_count++;
  RtlLeaveCriticalSection (&detail->waiters_count_lock);

  RtlLeaveCriticalSection (((wine_mutex)mutex)->critsect);
  WaitForSingleObject (detail->sema, ms);

  /* Reacquire lock to avoid race conditions. */
  RtlEnterCriticalSection (&detail->waiters_count_lock);

  /* We're no longer waiting... */
  detail->waiters_count--;

  /* Check to see if we're the last waiter after <pthread_cond_broadcast>. */
  last_waiter = detail->was_broadcast && detail->waiters_count == 0;

  RtlLeaveCriticalSection (&detail->waiters_count_lock);

  /*
   * If we're the last waiter thread during this particular broadcast
   * then let all the other threads proceed.
   */
  if (last_waiter) SetEvent (detail->waiters_done);
  RtlEnterCriticalSection (((wine_mutex)mutex)->critsect);
  return 0;
}

515 516 517 518 519 520 521 522 523 524 525 526 527 528
/***** MISC *****/

static pthread_t wine_pthread_self(void)
{
  return (pthread_t)GetCurrentThreadId();
}

static int wine_pthread_equal(pthread_t thread1, pthread_t thread2)
{
  return (DWORD)thread1 == (DWORD)thread2;
}

static void wine_pthread_exit(void *retval, char *currentframe)
{
529
    ExitThread((DWORD_PTR)retval);
530 531 532 533
}

static void *wine_get_thread_data(void)
{
534
    return kernel_get_thread_data()->pthread_data;
535 536 537 538
}

static void wine_set_thread_data( void *data )
{
539
    kernel_get_thread_data()->pthread_data = data;
540 541
}

542
static const struct wine_pthread_callbacks callbacks =
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
{
    wine_get_thread_data,           /* ptr_get_thread_data */
    wine_set_thread_data,           /* ptr_set_thread_data */
    wine_pthread_self,              /* ptr_pthread_self */
    wine_pthread_equal,             /* ptr_pthread_equal */
    wine_pthread_create,            /* ptr_pthread_create */
    wine_pthread_cancel,            /* ptr_pthread_cancel */
    wine_pthread_join,              /* ptr_pthread_join */
    wine_pthread_detach,            /* ptr_pthread_detach */
    wine_pthread_exit,              /* ptr_pthread_exit */
    wine_pthread_mutex_init,        /* ptr_pthread_mutex_init */
    wine_pthread_mutex_lock,        /* ptr_pthread_mutex_lock */
    wine_pthread_mutex_trylock,     /* ptr_pthread_mutex_trylock */
    wine_pthread_mutex_unlock,      /* ptr_pthread_mutex_unlock */
    wine_pthread_mutex_destroy,     /* ptr_pthread_mutex_destroy */
    wine_pthread_rwlock_init,       /* ptr_pthread_rwlock_init */
    wine_pthread_rwlock_destroy,    /* ptr_pthread_rwlock_destroy */
    wine_pthread_rwlock_rdlock,     /* ptr_pthread_rwlock_rdlock */
    wine_pthread_rwlock_tryrdlock,  /* ptr_pthread_rwlock_tryrdlock */
    wine_pthread_rwlock_wrlock,     /* ptr_pthread_rwlock_wrlock */
    wine_pthread_rwlock_trywrlock,  /* ptr_pthread_rwlock_trywrlock */
564 565 566 567 568 569 570
    wine_pthread_rwlock_unlock,     /* ptr_pthread_rwlock_unlock */
    wine_pthread_cond_init,         /* ptr_pthread_cond_init */
    wine_pthread_cond_destroy,      /* ptr_pthread_cond_destroy */
    wine_pthread_cond_signal,       /* ptr_pthread_cond_signal */
    wine_pthread_cond_broadcast,    /* ptr_pthread_cond_broadcast */
    wine_pthread_cond_wait,         /* ptr_pthread_cond_wait */
    wine_pthread_cond_timedwait     /* ptr_pthread_cond_timedwait */
571
};
572

573 574
static struct wine_pthread_functions pthread_functions;

575 576
void PTHREAD_Init(void)
{
577 578
    wine_pthread_get_functions( &pthread_functions, sizeof(pthread_functions) );
    pthread_functions.init_process( &callbacks, sizeof(callbacks) );
579 580
}

581
#endif /* HAVE_PTHREAD_H */