win32_threads.c 101 KB
Newer Older
1
/*
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (c) 1994 by Xerox Corporation.  All rights reserved.
 * Copyright (c) 1996 by Silicon Graphics.  All rights reserved.
 * Copyright (c) 1998 by Fergus Henderson.  All rights reserved.
 * Copyright (c) 2000-2008 by Hewlett-Packard Development Company.
 * All rights reserved.
 *
 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
 * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
 *
 * Permission is hereby granted to use or copy this program
 * for any purpose,  provided the above notices are retained on all copies.
 * Permission to modify the code and to distribute modified code is granted,
 * provided the above notices are retained, and a notice that the code was
 * modified is included with the above copyright notice.
 */

eg's avatar
eg committed
18 19
#include "private/gc_priv.h"

20
#if defined(GC_WIN32_THREADS)
eg's avatar
eg committed
21

22 23 24 25
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN 1
#endif
#define NOSERVICE
eg's avatar
eg committed
26 27 28 29 30 31
#include <windows.h>

#ifdef THREAD_LOCAL_ALLOC
# include "private/thread_local_alloc.h"
#endif /* THREAD_LOCAL_ALLOC */

32
/* Allocation lock declarations.        */
eg's avatar
eg committed
33
#if !defined(USE_PTHREAD_LOCKS)
34 35 36 37
  GC_INNER CRITICAL_SECTION GC_allocate_ml;
# ifdef GC_ASSERTIONS
    GC_INNER DWORD GC_lock_holder = NO_THREAD;
        /* Thread id for current holder of allocation lock */
38
# endif
eg's avatar
eg committed
39
#else
40 41 42 43
  GC_INNER pthread_mutex_t GC_allocate_ml = PTHREAD_MUTEX_INITIALIZER;
# ifdef GC_ASSERTIONS
    GC_INNER unsigned long GC_lock_holder = NO_THREAD;
# endif
eg's avatar
eg committed
44
#endif
eg's avatar
eg committed
45

46 47 48 49 50
#undef CreateThread
#undef ExitThread
#undef _beginthreadex
#undef _endthreadex

51
#ifdef GC_PTHREADS
52
# include <errno.h> /* for EAGAIN */
53

eg's avatar
eg committed
54
 /* Cygwin-specific forward decls */
55 56
# undef pthread_create
# undef pthread_join
eg's avatar
eg committed
57
# undef pthread_detach
eg's avatar
eg committed
58

59 60
# ifndef GC_NO_PTHREAD_SIGMASK
#   undef pthread_sigmask
61
# endif
eg's avatar
eg committed
62

63 64
  STATIC void * GC_pthread_start(void * arg);
  STATIC void GC_thread_exit_proc(void *arg);
eg's avatar
eg committed
65

eg's avatar
eg committed
66
# include <pthread.h>
67 68
# ifdef CAN_CALL_ATFORK
#   include <unistd.h>
69 70
# endif

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
#elif !defined(MSWINCE)
# include <process.h>  /* For _beginthreadex, _endthreadex */
# include <errno.h> /* for errno, EAGAIN */

#endif /* !GC_PTHREADS && !MSWINCE */

/* DllMain-based thread registration is currently incompatible  */
/* with thread-local allocation, pthreads and WinCE.            */
#if (defined(GC_DLL) || defined(GC_INSIDE_DLL)) \
        && !defined(GC_NO_THREADS_DISCOVERY) && !defined(MSWINCE) \
        && !defined(THREAD_LOCAL_ALLOC) && !defined(GC_PTHREADS)
# include "atomic_ops.h"

  /* This code operates in two distinct modes, depending on     */
  /* the setting of GC_win32_dll_threads.                       */
  /* If GC_win32_dll_threads is set, all threads in the process */
  /* are implicitly registered with the GC by DllMain.          */
  /* No explicit registration is required, and attempts at      */
  /* explicit registration are ignored.  This mode is           */
  /* very different from the Posix operation of the collector.  */
  /* In this mode access to the thread table is lock-free.      */
  /* Hence there is a static limit on the number of threads.    */

# ifdef GC_DISCOVER_TASK_THREADS
    /* GC_DISCOVER_TASK_THREADS should be used if DllMain-based */
    /* thread registration is required but it is impossible to  */
    /* call GC_use_threads_discovery before other GC routines.  */
#   define GC_win32_dll_threads TRUE
99
# else
100 101 102 103 104
    STATIC GC_bool GC_win32_dll_threads = FALSE;
    /* GC_win32_dll_threads must be set (if needed) at the      */
    /* application initialization time, i.e. before any         */
    /* collector or thread calls.  We make it a "dynamic"       */
    /* option only to avoid multiple library versions.          */
105
# endif
106

eg's avatar
eg committed
107
#else
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
  /* If GC_win32_dll_threads is FALSE (or the collector is      */
  /* built without GC_DLL defined), things operate in a way     */
  /* that is very similar to Posix platforms, and new threads   */
  /* must be registered with the collector, e.g. by using       */
  /* preprocessor-based interception of the thread primitives.  */
  /* In this case, we use a real data structure for the thread  */
  /* table.  Note that there is no equivalent of linker-based   */
  /* call interception, since we don't have ELF-like            */
  /* facilities.  The Windows analog appears to be "API         */
  /* hooking", which really seems to be a standard way to       */
  /* do minor binary rewriting (?).  I'd prefer not to have     */
  /* the basic collector rely on such facilities, but an        */
  /* optional package that intercepts thread calls this way     */
  /* would probably be nice.                                    */
# ifndef GC_NO_THREADS_DISCOVERY
#   define GC_NO_THREADS_DISCOVERY
# endif
eg's avatar
eg committed
125
# define GC_win32_dll_threads FALSE
126
# undef MAX_THREADS
127 128
# define MAX_THREADS 1 /* dll_thread_table[] is always empty.   */
#endif /* GC_NO_THREADS_DISCOVERY */
eg's avatar
eg committed
129

130
/* We have two versions of the thread table.  Which one */
131
/* we us depends on whether or not GC_win32_dll_threads */
132 133 134 135 136 137 138 139
/* is set.  Note that before initialization, we don't   */
/* add any entries to either table, even if DllMain is  */
/* called.  The main thread will be added on            */
/* initialization.                                      */

/* The type of the first argument to InterlockedExchange.       */
/* Documented to be LONG volatile *, but at least gcc likes     */
/* this better.                                                 */
eg's avatar
eg committed
140 141
typedef LONG * IE_t;

142
STATIC GC_bool GC_thr_initialized = FALSE;
eg's avatar
eg committed
143

144 145 146
#ifndef GC_ALWAYS_MULTITHREADED
  GC_INNER GC_bool GC_need_to_lock = FALSE;
#endif
eg's avatar
eg committed
147 148 149

static GC_bool parallel_initialized = FALSE;

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
/* GC_use_threads_discovery() is currently incompatible with pthreads   */
/* and WinCE.  It might be possible to get DllMain-based thread         */
/* registration to work with Cygwin, but if you try it then you are on  */
/* your own.                                                            */
GC_API void GC_CALL GC_use_threads_discovery(void)
{
# ifdef GC_NO_THREADS_DISCOVERY
    ABORT("GC DllMain-based thread registration unsupported");
# else
    /* Turn on GC_win32_dll_threads. */
    GC_ASSERT(!parallel_initialized);
    /* Note that GC_use_threads_discovery is expected to be called by   */
    /* the client application (not from DllMain) at start-up.           */
#   ifndef GC_DISCOVER_TASK_THREADS
      GC_win32_dll_threads = TRUE;
#   endif
    GC_init_parallel();
# endif
}
169 170

STATIC DWORD GC_main_thread = 0;
eg's avatar
eg committed
171

172
#define ADDR_LIMIT ((ptr_t)(word)-1)
eg's avatar
eg committed
173 174 175

struct GC_Thread_Rep {
  union {
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
#   ifndef GC_NO_THREADS_DISCOVERY
      volatile AO_t in_use;
                        /* Updated without lock.                */
                        /* We assert that unused                */
                        /* entries have invalid ids of          */
                        /* zero and zero stack fields.          */
                        /* Used only with GC_win32_dll_threads. */
#   endif
    struct GC_Thread_Rep * next;
                        /* Hash table link without              */
                        /* GC_win32_dll_threads.                */
                        /* More recently allocated threads      */
                        /* with a given pthread id come         */
                        /* first.  (All but the first are       */
                        /* guaranteed to be dead, but we may    */
                        /* not yet have registered the join.)   */
  } tm; /* table_management */
eg's avatar
eg committed
193
  DWORD id;
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211

# ifdef MSWINCE
    /* According to MSDN specs for WinCE targets:                       */
    /* - DuplicateHandle() is not applicable to thread handles; and     */
    /* - the value returned by GetCurrentThreadId() could be used as    */
    /* a "real" thread handle (for SuspendThread(), ResumeThread() and  */
    /* GetThreadContext()).                                             */
#   define THREAD_HANDLE(t) (HANDLE)(word)(t)->id
# else
    HANDLE handle;
#   define THREAD_HANDLE(t) (t)->handle
# endif

  ptr_t stack_base;     /* The cold end of the stack.   */
                        /* 0 ==> entry not valid.       */
                        /* !in_use ==> stack_base == 0  */
  ptr_t last_stack_min; /* Last known minimum (hottest) address */
                        /* in stack or ADDR_LIMIT if unset      */
212 213 214 215 216
# ifdef IA64
    ptr_t backing_store_end;
    ptr_t backing_store_ptr;
# endif

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
  ptr_t thread_blocked_sp;      /* Protected by GC lock.                */
                                /* NULL value means thread unblocked.   */
                                /* If set to non-NULL, thread will      */
                                /* acquire GC lock before doing any     */
                                /* pointer manipulations.  Thus it does */
                                /* not need to stop this thread.        */

  struct GC_traced_stack_sect_s *traced_stack_sect;
                                /* Points to the "stack section" data   */
                                /* held in stack by the innermost       */
                                /* GC_call_with_gc_active() of this     */
                                /* thread.  May be NULL.                */

  unsigned short finalizer_skipped;
  unsigned char finalizer_nested;
                                /* Used by GC_check_finalizer_nested()  */
                                /* to minimize the level of recursion   */
                                /* when a client finalizer allocates    */
                                /* memory (initially both are 0).       */

  unsigned char suspended; /* really of GC_bool type */
eg's avatar
eg committed
238

239
# ifdef GC_PTHREADS
240 241 242
    unsigned char flags;        /* Protected by GC lock.                */
#   define FINISHED 1           /* Thread has exited.                   */
#   define DETACHED 2           /* Thread is intended to be detached.   */
243
#   define KNOWN_FINISHED(t) (((t) -> flags) & FINISHED)
244 245
    pthread_t pthread_id;
    void *status;  /* hold exit value until join in case it's a pointer */
246 247
# else
#   define KNOWN_FINISHED(t) 0
eg's avatar
eg committed
248
# endif
249

eg's avatar
eg committed
250 251
# ifdef THREAD_LOCAL_ALLOC
    struct thread_local_freelists tlfs;
eg's avatar
eg committed
252 253 254
# endif
};

eg's avatar
eg committed
255
typedef struct GC_Thread_Rep * GC_thread;
256
typedef volatile struct GC_Thread_Rep * GC_vthread;
eg's avatar
eg committed
257

258 259 260 261 262 263 264
#ifndef GC_NO_THREADS_DISCOVERY
  /* We assumed that volatile ==> memory ordering, at least among       */
  /* volatiles.  This code should consistently use atomic_ops.          */
  STATIC volatile GC_bool GC_please_stop = FALSE;
#elif defined(GC_ASSERTIONS)
  STATIC GC_bool GC_please_stop = FALSE;
#endif
eg's avatar
eg committed
265

266 267 268 269 270 271 272
/*
 * We track thread attachments while the world is supposed to be stopped.
 * Unfortunately, we can't stop them from starting, since blocking in
 * DllMain seems to cause the world to deadlock.  Thus we have to recover
 * If we notice this in the middle of marking.
 */

273 274 275
#ifndef GC_NO_THREADS_DISCOVERY
  STATIC volatile AO_t GC_attached_thread = FALSE;
#endif
276

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
#if defined(WRAP_MARK_SOME) && !defined(GC_PTHREADS)
  /* Return TRUE if an thread was attached since we last asked or */
  /* since GC_attached_thread was explicitly reset.               */
  GC_INNER GC_bool GC_started_thread_while_stopped(void)
  {
#   ifndef GC_NO_THREADS_DISCOVERY
      if (GC_win32_dll_threads) {
#       ifdef AO_HAVE_compare_and_swap_release
          if (AO_compare_and_swap_release(&GC_attached_thread, TRUE,
                                          FALSE /* stored */))
            return TRUE;
#       else
          AO_nop_full(); /* Prior heap reads need to complete earlier. */
          if (AO_load(&GC_attached_thread)) {
            AO_store(&GC_attached_thread, FALSE);
            return TRUE;
          }
#       endif
      }
#   endif
297
    return FALSE;
298
  }
299
#endif /* WRAP_MARK_SOME */
eg's avatar
eg committed
300

301 302 303 304
/* Thread table used if GC_win32_dll_threads is set.    */
/* This is a fixed size array.                          */
/* Since we use runtime conditionals, both versions     */
/* are always defined.                                  */
eg's avatar
eg committed
305 306
# ifndef MAX_THREADS
#   define MAX_THREADS 512
307
# endif
308

309 310 311
/* Things may get quite slow for large numbers of threads,      */
/* since we look them up with sequential search.                */
volatile struct GC_Thread_Rep dll_thread_table[MAX_THREADS];
312

313 314 315
STATIC volatile LONG GC_max_thread_index = 0;
                        /* Largest index in dll_thread_table    */
                        /* that was ever used.                  */
316

317 318 319
/* And now the version used if GC_win32_dll_threads is not set. */
/* This is a chained hash table, with much of the code borrowed */
/* From the Posix implementation.                               */
320
#ifndef THREAD_TABLE_SZ
321
# define THREAD_TABLE_SZ 256    /* Power of 2 (for speed). */
322
#endif
323 324 325 326 327 328 329 330 331 332 333 334 335
#define THREAD_TABLE_INDEX(id) /* id is of DWORD type */ \
                (int)((((id) >> 8) ^ (id)) % THREAD_TABLE_SZ)
STATIC GC_thread GC_threads[THREAD_TABLE_SZ];

/* It may not be safe to allocate when we register the first thread.    */
/* Thus we allocated one statically.  It does not contain any field we  */
/* need to push ("next" and "status" fields are unused).                */
static struct GC_Thread_Rep first_thread;
static GC_bool first_thread_used = FALSE;

/* Add a thread to GC_threads.  We assume it wasn't already there.      */
/* Caller holds allocation lock.                                        */
/* Unlike the pthreads version, the id field is set by the caller.      */
336
STATIC GC_thread GC_new_thread(DWORD id)
eg's avatar
eg committed
337
{
338 339
  int hv = THREAD_TABLE_INDEX(id);
  GC_thread result;
eg's avatar
eg committed
340

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
  GC_ASSERT(I_HOLD_LOCK());
  if (!EXPECT(first_thread_used, TRUE)) {
    result = &first_thread;
    first_thread_used = TRUE;
  } else {
    GC_ASSERT(!GC_win32_dll_threads);
    result = (struct GC_Thread_Rep *)
                GC_INTERNAL_MALLOC(sizeof(struct GC_Thread_Rep), NORMAL);
    /* result can be NULL */
    if (result == 0) return(0);
  }
  /* result -> id = id; Done by caller.       */
  result -> tm.next = GC_threads[hv];
  GC_threads[hv] = result;
# ifdef GC_PTHREADS
    GC_ASSERT(result -> flags == 0);
# endif
  GC_ASSERT(result -> thread_blocked_sp == NULL);
  return(result);
}
eg's avatar
eg committed
361

362 363
STATIC GC_bool GC_in_thread_creation = FALSE;
                                /* Protected by allocation lock. */
364

365 366 367 368 369 370 371 372 373 374
GC_INLINE void GC_record_stack_base(GC_vthread me,
                                    const struct GC_stack_base *sb)
{
  me -> stack_base = sb -> mem_base;
# ifdef IA64
    me -> backing_store_end = sb -> reg_base;
# endif
  if (me -> stack_base == NULL)
    ABORT("Bad stack base in GC_register_my_thread");
}
375

376 377 378 379 380 381 382
/* This may be called from DllMain, and hence operates under unusual    */
/* constraints.  In particular, it must be lock-free if                 */
/* GC_win32_dll_threads is set.  Always called from the thread being    */
/* added.  If GC_win32_dll_threads is not set, we already hold the      */
/* allocation lock except possibly during single-threaded startup code. */
STATIC GC_thread GC_register_my_thread_inner(const struct GC_stack_base *sb,
                                             DWORD thread_id)
eg's avatar
eg committed
383
{
384
  GC_vthread me;
eg's avatar
eg committed
385

386 387 388
  /* The following should be a no-op according to the win32     */
  /* documentation.  There is empirical evidence that it        */
  /* isn't.             - HB                                    */
eg's avatar
eg committed
389
# if defined(MPROTECT_VDB)
390 391 392 393 394 395
    if (GC_incremental
#       ifdef GWW_VDB
          && !GC_gww_dirty_init()
#       endif
        )
      GC_set_write_fault_handler();
eg's avatar
eg committed
396 397
# endif

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 441 442
# ifndef GC_NO_THREADS_DISCOVERY
    if (GC_win32_dll_threads) {
      int i;
      /* It appears to be unsafe to acquire a lock here, since this     */
      /* code is apparently not preemptible on some systems.            */
      /* (This is based on complaints, not on Microsoft's official      */
      /* documentation, which says this should perform "only simple     */
      /* initialization tasks".)                                        */
      /* Hence we make do with nonblocking synchronization.             */
      /* It has been claimed that DllMain is really only executed with  */
      /* a particular system lock held, and thus careful use of locking */
      /* around code that doesn't call back into the system libraries   */
      /* might be OK.  But this hasn't been tested across all win32     */
      /* variants.                                                      */
                  /* cast away volatile qualifier */
      for (i = 0;
           InterlockedExchange((void*)&dll_thread_table[i].tm.in_use, 1) != 0;
           i++) {
        /* Compare-and-swap would make this cleaner, but that's not     */
        /* supported before Windows 98 and NT 4.0.  In Windows 2000,    */
        /* InterlockedExchange is supposed to be replaced by            */
        /* InterlockedExchangePointer, but that's not really what I     */
        /* want here.                                                   */
        /* FIXME: We should eventually declare Win95 dead and use AO_   */
        /* primitives here.                                             */
        if (i == MAX_THREADS - 1)
          ABORT("Too many threads");
      }
      /* Update GC_max_thread_index if necessary.  The following is     */
      /* safe, and unlike CompareExchange-based solutions seems to work */
      /* on all Windows95 and later platforms.                          */
      /* Unfortunately, GC_max_thread_index may be temporarily out of   */
      /* bounds, so readers have to compensate.                         */
      while (i > GC_max_thread_index) {
        InterlockedIncrement((IE_t)&GC_max_thread_index);
      }
      if (GC_max_thread_index >= MAX_THREADS) {
        /* We overshot due to simultaneous increments.  */
        /* Setting it to MAX_THREADS-1 is always safe.  */
        GC_max_thread_index = MAX_THREADS - 1;
      }
      me = dll_thread_table + i;
    } else
# endif
  /* else */ /* Not using DllMain */ {
443 444
    GC_ASSERT(I_HOLD_LOCK());
    GC_in_thread_creation = TRUE; /* OK to collect from unknown thread. */
eg's avatar
eg committed
445
    me = GC_new_thread(thread_id);
446
    GC_in_thread_creation = FALSE;
447
    if (me == 0)
448
      ABORT("Failed to allocate memory for thread registering");
eg's avatar
eg committed
449
  }
450 451
# ifdef GC_PTHREADS
    /* me can be NULL -> segfault */
eg's avatar
eg committed
452 453
    me -> pthread_id = pthread_self();
# endif
454 455 456 457 458 459 460 461 462 463
# ifndef MSWINCE
    /* GetCurrentThread() returns a pseudohandle (a const value).       */
    if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
                        GetCurrentProcess(),
                        (HANDLE*)&(me -> handle),
                        0 /* dwDesiredAccess */, FALSE /* bInheritHandle */,
                        DUPLICATE_SAME_ACCESS)) {
        ABORT_ARG1("DuplicateHandle failed",
                   ": errcode= 0x%X", (unsigned)GetLastError());
    }
464
# endif
465 466 467 468 469 470
  me -> last_stack_min = ADDR_LIMIT;
  GC_record_stack_base(me, sb);
  /* Up until this point, GC_push_all_stacks considers this thread      */
  /* invalid.                                                           */
  /* Up until this point, this entry is viewed as reserved but invalid  */
  /* by GC_delete_thread.                                               */
eg's avatar
eg committed
471 472
  me -> id = thread_id;
# if defined(THREAD_LOCAL_ALLOC)
473
    GC_init_thread_local((GC_tlfs)(&(me->tlfs)));
474
# endif
475 476 477 478 479 480 481 482 483 484 485 486
# ifndef GC_NO_THREADS_DISCOVERY
    if (GC_win32_dll_threads) {
      if (GC_please_stop) {
        AO_store(&GC_attached_thread, TRUE);
        AO_nop_full(); /* Later updates must become visible after this. */
      }
      /* We'd like to wait here, but can't, since waiting in DllMain    */
      /* provokes deadlocks.                                            */
      /* Thus we force marking to be restarted instead.                 */
    } else
# endif
  /* else */ {
487
    GC_ASSERT(!GC_please_stop);
488 489
        /* Otherwise both we and the thread stopping code would be      */
        /* holding the allocation lock.                                 */
490
  }
eg's avatar
eg committed
491 492 493 494 495 496 497
  return (GC_thread)(me);
}

/*
 * GC_max_thread_index may temporarily be larger than MAX_THREADS.
 * To avoid subscript errors, we check on access.
 */
498
GC_INLINE LONG GC_get_max_thread_index(void)
eg's avatar
eg committed
499 500
{
  LONG my_max = GC_max_thread_index;
501
  if (my_max >= MAX_THREADS) return MAX_THREADS - 1;
eg's avatar
eg committed
502 503 504
  return my_max;
}

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
/* Return the GC_thread corresponding to a thread id.  May be called    */
/* without a lock, but should be called in contexts in which the        */
/* requested thread cannot be asynchronously deleted, e.g. from the     */
/* thread itself.                                                       */
/* This version assumes that either GC_win32_dll_threads is set, or     */
/* we hold the allocator lock.                                          */
/* Also used (for assertion checking only) from thread_local_alloc.c.   */
STATIC GC_thread GC_lookup_thread_inner(DWORD thread_id)
{
# ifndef GC_NO_THREADS_DISCOVERY
    if (GC_win32_dll_threads) {
      int i;
      LONG my_max = GC_get_max_thread_index();
      for (i = 0; i <= my_max &&
                  (!AO_load_acquire(&dll_thread_table[i].tm.in_use)
                  || dll_thread_table[i].id != thread_id);
           /* Must still be in_use, since nobody else can store our     */
           /* thread_id.                                                */
           i++) {
        /* empty */
      }
      return i <= my_max ? (GC_thread)(dll_thread_table + i) : NULL;
    } else
# endif
  /* else */ {
    GC_thread p = GC_threads[THREAD_TABLE_INDEX(thread_id)];

eg's avatar
eg committed
532
    GC_ASSERT(I_HOLD_LOCK());
533
    while (p != 0 && p -> id != thread_id) p = p -> tm.next;
eg's avatar
eg committed
534 535
    return(p);
  }
eg's avatar
eg committed
536 537
}

538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 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 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
#ifdef LINT2
# define CHECK_LOOKUP_MY_THREAD(me) \
        if (!(me)) ABORT("GC_lookup_thread_inner(GetCurrentThreadId) failed")
#else
# define CHECK_LOOKUP_MY_THREAD(me) /* empty */
#endif

/* Called by GC_finalize() (in case of an allocation failure observed). */
/* GC_reset_finalizer_nested() is the same as in pthread_support.c.     */
GC_INNER void GC_reset_finalizer_nested(void)
{
  GC_thread me = GC_lookup_thread_inner(GetCurrentThreadId());
  CHECK_LOOKUP_MY_THREAD(me);
  me->finalizer_nested = 0;
}

/* Checks and updates the thread-local level of finalizers recursion.   */
/* Returns NULL if GC_invoke_finalizers() should not be called by the   */
/* collector (to minimize the risk of a deep finalizers recursion),     */
/* otherwise returns a pointer to the thread-local finalizer_nested.    */
/* Called by GC_notify_or_invoke_finalizers() only (the lock is held).  */
/* GC_check_finalizer_nested() is the same as in pthread_support.c.     */
GC_INNER unsigned char *GC_check_finalizer_nested(void)
{
  GC_thread me = GC_lookup_thread_inner(GetCurrentThreadId());
  unsigned nesting_level;
  CHECK_LOOKUP_MY_THREAD(me);
  nesting_level = me->finalizer_nested;
  if (nesting_level) {
    /* We are inside another GC_invoke_finalizers().            */
    /* Skip some implicitly-called GC_invoke_finalizers()       */
    /* depending on the nesting (recursion) level.              */
    if (++me->finalizer_skipped < (1U << nesting_level)) return NULL;
    me->finalizer_skipped = 0;
  }
  me->finalizer_nested = (unsigned char)(nesting_level + 1);
  return &me->finalizer_nested;
}

#if defined(GC_ASSERTIONS) && defined(THREAD_LOCAL_ALLOC)
  /* This is called from thread-local GC_malloc(). */
  GC_bool GC_is_thread_tsd_valid(void *tsd)
  {
    GC_thread me;
    DCL_LOCK_STATE;

    LOCK();
    me = GC_lookup_thread_inner(GetCurrentThreadId());
    UNLOCK();
    return (word)tsd >= (word)(&me->tlfs)
            && (word)tsd < (word)(&me->tlfs) + sizeof(me->tlfs);
  }
#endif /* GC_ASSERTIONS && THREAD_LOCAL_ALLOC */

GC_API int GC_CALL GC_thread_is_registered(void)
{
    DWORD thread_id = GetCurrentThreadId();
    GC_thread me;
    DCL_LOCK_STATE;

    LOCK();
    me = GC_lookup_thread_inner(thread_id);
    UNLOCK();
    return me != NULL;
}

GC_API void GC_CALL GC_register_altstack(void *stack GC_ATTR_UNUSED,
                                         GC_word stack_size GC_ATTR_UNUSED,
                                         void *altstack GC_ATTR_UNUSED,
                                         GC_word altstack_size GC_ATTR_UNUSED)
{
  /* TODO: Implement */
}

/* Make sure thread descriptor t is not protected by the VDB            */
/* implementation.                                                      */
/* Used to prevent write faults when the world is (partially) stopped,  */
/* since it may have been stopped with a system lock held, and that     */
/* lock may be required for fault handling.                             */
#if defined(MPROTECT_VDB)
# define UNPROTECT_THREAD(t) \
    if (!GC_win32_dll_threads && GC_incremental && t != &first_thread) { \
      GC_ASSERT(SMALL_OBJ(GC_size(t))); \
      GC_remove_protection(HBLKPTR(t), 1, FALSE); \
    } else (void)0
#else
# define UNPROTECT_THREAD(t) (void)0
#endif

#ifdef CYGWIN32
# define GC_PTHREAD_PTRVAL(pthread_id) pthread_id
#elif defined(GC_WIN32_PTHREADS) || defined(GC_PTHREADS_PARAMARK)
# include <pthread.h> /* to check for winpthreads */
# if defined(__WINPTHREADS_VERSION_MAJOR)
#   define GC_PTHREAD_PTRVAL(pthread_id) pthread_id
633
# else
634 635 636 637 638 639 640 641 642 643 644 645 646 647
#   define GC_PTHREAD_PTRVAL(pthread_id) pthread_id.p
# endif
#endif

/* If a thread has been joined, but we have not yet             */
/* been notified, then there may be more than one thread        */
/* in the table with the same win32 id.                         */
/* This is OK, but we need a way to delete a specific one.      */
/* Assumes we hold the allocation lock unless                   */
/* GC_win32_dll_threads is set.  Does not actually free         */
/* GC_thread entry (only unlinks it).                           */
/* If GC_win32_dll_threads is set it should be called from the  */
/* thread being deleted.                                        */
STATIC void GC_delete_gc_thread_no_free(GC_vthread t)
eg's avatar
eg committed
648
{
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
# ifndef MSWINCE
    CloseHandle(t->handle);
# endif
# ifndef GC_NO_THREADS_DISCOVERY
    if (GC_win32_dll_threads) {
      /* This is intended to be lock-free.                              */
      /* It is either called synchronously from the thread being        */
      /* deleted, or by the joining thread.                             */
      /* In this branch asynchronous changes to (*t) are possible.      */
      /* It's not allowed to call GC_printf (and the friends) here,     */
      /* see GC_stop_world() for the information.                       */
      t -> stack_base = 0;
      t -> id = 0;
      AO_store_release(&t->tm.in_use, FALSE);
    } else
# endif
  /* else */ {
    DWORD id = ((GC_thread)t) -> id;
                /* Cast away volatile qualifier, since we have lock.    */
    int hv = THREAD_TABLE_INDEX(id);
eg's avatar
eg committed
669 670 671 672
    register GC_thread p = GC_threads[hv];
    register GC_thread prev = 0;

    GC_ASSERT(I_HOLD_LOCK());
673 674 675
    while (p != (GC_thread)t) {
      prev = p;
      p = p -> tm.next;
eg's avatar
eg committed
676 677
    }
    if (prev == 0) {
678
      GC_threads[hv] = p -> tm.next;
eg's avatar
eg committed
679
    } else {
680
      prev -> tm.next = p -> tm.next;
eg's avatar
eg committed
681 682 683 684
    }
  }
}

685 686 687 688 689 690
/* Delete a thread from GC_threads.  We assume it is there.     */
/* (The code intentionally traps if it wasn't.)  Assumes we     */
/* hold the allocation lock unless GC_win32_dll_threads is set. */
/* If GC_win32_dll_threads is set then it should be called from */
/* the thread being deleted.  It is also safe to delete the     */
/* main thread (unless GC_win32_dll_threads).                   */
691
STATIC void GC_delete_thread(DWORD id)
eg's avatar
eg committed
692 693
{
  if (GC_win32_dll_threads) {
694
    GC_vthread t = GC_lookup_thread_inner(id);
eg's avatar
eg committed
695 696

    if (0 == t) {
697
      WARN("Removing nonexistent thread, id = %" WARN_PRIdPTR "\n", id);
eg's avatar
eg committed
698
    } else {
699
      GC_delete_gc_thread_no_free(t);
eg's avatar
eg committed
700 701
    }
  } else {
702
    int hv = THREAD_TABLE_INDEX(id);
eg's avatar
eg committed
703 704
    register GC_thread p = GC_threads[hv];
    register GC_thread prev = 0;
705

eg's avatar
eg committed
706 707
    GC_ASSERT(I_HOLD_LOCK());
    while (p -> id != id) {
708 709
      prev = p;
      p = p -> tm.next;
eg's avatar
eg committed
710
    }
711 712 713
#   ifndef MSWINCE
      CloseHandle(p->handle);
#   endif
eg's avatar
eg committed
714
    if (prev == 0) {
715
      GC_threads[hv] = p -> tm.next;
eg's avatar
eg committed
716
    } else {
717 718 719 720
      prev -> tm.next = p -> tm.next;
    }
    if (p != &first_thread) {
      GC_INTERNAL_FREE(p);
eg's avatar
eg committed
721 722 723 724
    }
  }
}

725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
GC_API void GC_CALL GC_allow_register_threads(void)
{
  /* Check GC is initialized and the current thread is registered. */
  GC_ASSERT(GC_lookup_thread_inner(GetCurrentThreadId()) != 0);
# if !defined(GC_ALWAYS_MULTITHREADED) && !defined(PARALLEL_MARK) \
     && !defined(GC_NO_THREADS_DISCOVERY)
      /* GC_init() does not call GC_init_parallel() in this case.   */
    parallel_initialized = TRUE;
# endif
  set_need_to_lock();
}

GC_API int GC_CALL GC_register_my_thread(const struct GC_stack_base *sb)
{
  GC_thread me;
  DWORD thread_id = GetCurrentThreadId();
  DCL_LOCK_STATE;

  if (GC_need_to_lock == FALSE)
    ABORT("Threads explicit registering is not previously enabled");
eg's avatar
eg committed
745

746
  /* We lock here, since we want to wait for an ongoing GC.     */
747
  LOCK();
748 749 750 751 752 753 754 755 756 757
  me = GC_lookup_thread_inner(thread_id);
  if (me == 0) {
#   ifdef GC_PTHREADS
      me = GC_register_my_thread_inner(sb, thread_id);
      me -> flags |= DETACHED;
          /* Treat as detached, since we do not need to worry about     */
          /* pointer results.                                           */
#   else
      GC_register_my_thread_inner(sb, thread_id);
#   endif
eg's avatar
eg committed
758 759
    UNLOCK();
    return GC_SUCCESS;
760 761 762 763 764 765 766 767 768 769 770 771 772
  } else
#   ifdef GC_PTHREADS
      /* else */ if ((me -> flags & FINISHED) != 0) {
        GC_record_stack_base(me, sb);
        me -> flags &= ~FINISHED; /* but not DETACHED */
#       ifdef THREAD_LOCAL_ALLOC
          GC_init_thread_local((GC_tlfs)(&me->tlfs));
#       endif
        UNLOCK();
        return GC_SUCCESS;
      } else
#   endif
  /* else */ {
773
    UNLOCK();
eg's avatar
eg committed
774 775 776 777
    return GC_DUPLICATE;
  }
}

778 779
/* Similar to that in pthread_support.c.        */
STATIC void GC_wait_for_gc_completion(GC_bool wait_for_all)
eg's avatar
eg committed
780
{
781 782 783 784 785 786 787 788 789 790 791 792
  GC_ASSERT(I_HOLD_LOCK());
  if (GC_incremental && GC_collection_in_progress()) {
    word old_gc_no = GC_gc_no;

    /* Make sure that no part of our stack is still on the mark stack,  */
    /* since it's about to be unmapped.                                 */
    do {
      ENTER_GC();
      GC_in_thread_creation = TRUE;
      GC_collect_a_little_inner(1);
      GC_in_thread_creation = FALSE;
      EXIT_GC();
eg's avatar
eg committed
793

794
      UNLOCK();
795 796 797 798 799
      Sleep(0); /* yield */
      LOCK();
    } while (GC_incremental && GC_collection_in_progress()
             && (wait_for_all || old_gc_no == GC_gc_no));
  }
800
}
eg's avatar
eg committed
801

802 803 804
GC_API int GC_CALL GC_unregister_my_thread(void)
{
  DCL_LOCK_STATE;
805

806 807 808
# ifdef DEBUG_THREADS
    GC_log_printf("Unregistering thread 0x%lx\n", (long)GetCurrentThreadId());
# endif
809

810
  if (GC_win32_dll_threads) {
811 812 813 814 815 816 817
#   if defined(THREAD_LOCAL_ALLOC)
      /* Can't happen: see GC_use_threads_discovery(). */
      GC_ASSERT(FALSE);
#   else
      /* FIXME: Should we just ignore this? */
      GC_delete_thread(GetCurrentThreadId());
#   endif
818
  } else {
819 820 821 822
#   if defined(THREAD_LOCAL_ALLOC) || defined(GC_PTHREADS)
      GC_thread me;
#   endif
    DWORD thread_id = GetCurrentThreadId();
823

824
    LOCK();
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
    GC_wait_for_gc_completion(FALSE);
#   if defined(THREAD_LOCAL_ALLOC) || defined(GC_PTHREADS)
      me = GC_lookup_thread_inner(thread_id);
      CHECK_LOOKUP_MY_THREAD(me);
      GC_ASSERT(!KNOWN_FINISHED(me));
#   endif
#   if defined(THREAD_LOCAL_ALLOC)
      GC_ASSERT(GC_getspecific(GC_thread_key) == &me->tlfs);
      GC_destroy_thread_local(&(me->tlfs));
#   endif
#   ifdef GC_PTHREADS
      if ((me -> flags & DETACHED) == 0) {
        me -> flags |= FINISHED;
      } else
#   endif
    /* else */ {
      GC_delete_thread(thread_id);
eg's avatar
eg committed
842
    }
843 844 845 846
#   if defined(THREAD_LOCAL_ALLOC)
      /* It is required to call remove_specific defined in specific.c. */
      GC_remove_specific(GC_thread_key);
#   endif
847
    UNLOCK();
eg's avatar
eg committed
848
  }
849
  return GC_SUCCESS;
850
}
eg's avatar
eg committed
851

852 853
/* Wrapper for functions that are likely to block for an appreciable    */
/* length of time.                                                      */
eg's avatar
eg committed
854

855 856
/* GC_do_blocking_inner() is nearly the same as in pthread_support.c    */
GC_INNER void GC_do_blocking_inner(ptr_t data, void * context GC_ATTR_UNUSED)
eg's avatar
eg committed
857
{
858 859 860 861 862 863 864
  struct blocking_data * d = (struct blocking_data *) data;
  DWORD thread_id = GetCurrentThreadId();
  GC_thread me;
# ifdef IA64
    ptr_t stack_ptr = GC_save_regs_in_stack();
# endif
  DCL_LOCK_STATE;
865

866 867 868 869 870 871
  LOCK();
  me = GC_lookup_thread_inner(thread_id);
  CHECK_LOOKUP_MY_THREAD(me);
  GC_ASSERT(me -> thread_blocked_sp == NULL);
# ifdef IA64
    me -> backing_store_ptr = stack_ptr;
eg's avatar
eg committed
872
# endif
873 874 875 876 877 878 879 880 881 882
  me -> thread_blocked_sp = (ptr_t) &d; /* save approx. sp */
  /* Save context here if we want to support precise stack marking */
  UNLOCK();
  d -> client_data = (d -> fn)(d -> client_data);
  LOCK();   /* This will block if the world is stopped. */
# if defined(CPPCHECK)
    GC_noop1((word)me->thread_blocked_sp);
# endif
  me -> thread_blocked_sp = NULL;
  UNLOCK();
eg's avatar
eg committed
883 884
}

885 886 887 888 889 890
/* GC_call_with_gc_active() has the opposite to GC_do_blocking()        */
/* functionality.  It might be called from a user function invoked by   */
/* GC_do_blocking() to temporarily back allow calling any GC function   */
/* and/or manipulating pointers to the garbage collected heap.          */
GC_API void * GC_CALL GC_call_with_gc_active(GC_fn_type fn,
                                             void * client_data)
eg's avatar
eg committed
891
{
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
  struct GC_traced_stack_sect_s stacksect;
  DWORD thread_id = GetCurrentThreadId();
  GC_thread me;
  DCL_LOCK_STATE;

  LOCK();   /* This will block if the world is stopped.         */
  me = GC_lookup_thread_inner(thread_id);
  CHECK_LOOKUP_MY_THREAD(me);
  /* Adjust our stack base value (this could happen unless      */
  /* GC_get_stack_base() was used which returned GC_SUCCESS).   */
  GC_ASSERT(me -> stack_base != NULL);
  if ((word)me->stack_base < (word)(&stacksect))
    me -> stack_base = (ptr_t)(&stacksect);

  if (me -> thread_blocked_sp == NULL) {
    /* We are not inside GC_do_blocking() - do nothing more.    */
    UNLOCK();
    client_data = fn(client_data);
    /* Prevent treating the above as a tail call.       */
    GC_noop1((word)(&stacksect));
    return client_data; /* result */
  }

  /* Setup new "stack section". */
  stacksect.saved_stack_ptr = me -> thread_blocked_sp;
# ifdef IA64
    /* This is the same as in GC_call_with_stack_base().        */
    stacksect.backing_store_end = GC_save_regs_in_stack();
    /* Unnecessarily flushes register stack,    */
    /* but that probably doesn't hurt.          */
    stacksect.saved_backing_store_ptr = me -> backing_store_ptr;
# endif
  stacksect.prev = me -> traced_stack_sect;
  me -> thread_blocked_sp = NULL;
  me -> traced_stack_sect = &stacksect;

  UNLOCK();
  client_data = fn(client_data);
  GC_ASSERT(me -> thread_blocked_sp == NULL);
  GC_ASSERT(me -> traced_stack_sect == &stacksect);

  /* Restore original "stack section".  */
  LOCK();
# if defined(CPPCHECK)
    GC_noop1((word)me->traced_stack_sect);
# endif
  me -> traced_stack_sect = stacksect.prev;
# ifdef IA64
    me -> backing_store_ptr = stacksect.saved_backing_store_ptr;
# endif
  me -> thread_blocked_sp = stacksect.saved_stack_ptr;
  UNLOCK();

  return client_data; /* result */
}

#ifdef GC_PTHREADS

  /* A quick-and-dirty cache of the mapping between pthread_t   */
  /* and win32 thread id.                                       */
# define PTHREAD_MAP_SIZE 512
  DWORD GC_pthread_map_cache[PTHREAD_MAP_SIZE] = {0};
# define PTHREAD_MAP_INDEX(pthread_id) \
                ((NUMERIC_THREAD_ID(pthread_id) >> 5) % PTHREAD_MAP_SIZE)
        /* It appears pthread_t is really a pointer type ... */
# define SET_PTHREAD_MAP_CACHE(pthread_id, win32_id) \
      (void)(GC_pthread_map_cache[PTHREAD_MAP_INDEX(pthread_id)] = (win32_id))
# define GET_PTHREAD_MAP_CACHE(pthread_id) \
          GC_pthread_map_cache[PTHREAD_MAP_INDEX(pthread_id)]

  /* Return a GC_thread corresponding to a given pthread_t.     */
  /* Returns 0 if it's not there.                               */
  /* We assume that this is only called for pthread ids that    */
  /* have not yet terminated or are still joinable, and         */
  /* cannot be concurrently terminated.                         */
  /* Assumes we do NOT hold the allocation lock.                */
  STATIC GC_thread GC_lookup_pthread(pthread_t id)
  {
#   ifndef GC_NO_THREADS_DISCOVERY
      if (GC_win32_dll_threads) {
        int i;
        LONG my_max = GC_get_max_thread_index();

        for (i = 0; i <= my_max &&
                    (!AO_load_acquire(&dll_thread_table[i].tm.in_use)
                    || THREAD_EQUAL(dll_thread_table[i].pthread_id, id));
                    /* Must still be in_use, since nobody else can      */
                    /* store our thread_id.                             */
             i++) {
          /* empty */
        }
        return i <= my_max ? (GC_thread)(dll_thread_table + i) : NULL;
      } else
#   endif
    /* else */ {
      /* We first try the cache.  If that fails, we use a very slow     */
      /* approach.                                                      */
      DWORD win32_id = GET_PTHREAD_MAP_CACHE(id);
      int hv_guess = THREAD_TABLE_INDEX(win32_id);
      int hv;
      GC_thread p;
      DCL_LOCK_STATE;

      LOCK();
      for (p = GC_threads[hv_guess]; 0 != p; p = p -> tm.next) {
        if (THREAD_EQUAL(p -> pthread_id, id))
          goto foundit;
      }
      for (hv = 0; hv < THREAD_TABLE_SZ; ++hv) {
        for (p = GC_threads[hv]; 0 != p; p = p -> tm.next) {
          if (THREAD_EQUAL(p -> pthread_id, id))
            goto foundit;
        }
      }
      p = 0;
     foundit:
      UNLOCK();
      return p;
    }
  }

#endif /* GC_PTHREADS */

#ifdef CAN_HANDLE_FORK
    /* Similar to that in pthread_support.c but also rehashes the table */
    /* since hash map key (thread_id) differs from that in the parent.  */
    STATIC void GC_remove_all_threads_but_me(void)
    {
      int hv;
      GC_thread p, next, me = NULL;
      DWORD thread_id;
      pthread_t pthread_id = pthread_self(); /* same as in parent */

      GC_ASSERT(!GC_win32_dll_threads);
      for (hv = 0; hv < THREAD_TABLE_SZ; ++hv) {
        for (p = GC_threads[hv]; 0 != p; p = next) {
          next = p -> tm.next;
          if (THREAD_EQUAL(p -> pthread_id, pthread_id)
              && me == NULL) { /* ignore dead threads with the same id */
            me = p;
            p -> tm.next = 0;
          } else {
#           ifdef THREAD_LOCAL_ALLOC
              if ((p -> flags & FINISHED) == 0) {
                /* Cannot call GC_destroy_thread_local here (see the    */
                /* corresponding comment in pthread_support.c).         */
                GC_remove_specific_after_fork(GC_thread_key, p -> pthread_id);
              }
#           endif
            if (&first_thread != p)
              GC_INTERNAL_FREE(p);
          }
        }
        GC_threads[hv] = NULL;
      }

      /* Put "me" back to GC_threads.   */
      GC_ASSERT(me != NULL);
      thread_id = GetCurrentThreadId(); /* differs from that in parent */
      GC_threads[THREAD_TABLE_INDEX(thread_id)] = me;

      /* Update Win32 thread Id and handle.     */
      me -> id = thread_id;
#     ifndef MSWINCE
        if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
                        GetCurrentProcess(), (HANDLE *)&me->handle,
                        0 /* dwDesiredAccess */, FALSE /* bInheritHandle */,
                        DUPLICATE_SAME_ACCESS))
          ABORT("DuplicateHandle failed");
#     endif

#     if defined(THREAD_LOCAL_ALLOC) && !defined(USE_CUSTOM_SPECIFIC)
        /* For Cygwin, we need to re-assign thread-local pointer to     */
        /* 'tlfs' (it is OK to call GC_destroy_thread_local and         */
        /* GC_free_internal before this action).                        */
        if (GC_setspecific(GC_thread_key, &me->tlfs) != 0)
          ABORT("GC_setspecific failed (in child)");
#     endif
    }

    static void fork_prepare_proc(void)
    {
      LOCK();
#     ifdef PARALLEL_MARK
        if (GC_parallel)
          GC_wait_for_reclaim();
#     endif
      GC_wait_for_gc_completion(TRUE);
#     ifdef PARALLEL_MARK
        if (GC_parallel)
          GC_acquire_mark_lock();
#     endif
    }

    static void fork_parent_proc(void)
    {
#     ifdef PARALLEL_MARK
        if (GC_parallel)
          GC_release_mark_lock();
#     endif
      UNLOCK();
    }

    static void fork_child_proc(void)
    {
#     ifdef PARALLEL_MARK
        if (GC_parallel) {
          GC_release_mark_lock();
          GC_parallel = FALSE; /* or GC_markers_m1 = 0 */
                /* Turn off parallel marking in the child, since we are */
                /* probably just going to exec, and we would have to    */
                /* restart mark threads.                                */
        }
#     endif
      GC_remove_all_threads_but_me();
      UNLOCK();
    }

  /* Routines for fork handling by client (no-op if pthread_atfork works). */
  GC_API void GC_CALL GC_atfork_prepare(void)
  {
    if (!EXPECT(GC_is_initialized, TRUE)) GC_init();
    if (GC_handle_fork <= 0)
      fork_prepare_proc();
  }

  GC_API void GC_CALL GC_atfork_parent(void)
  {
    if (GC_handle_fork <= 0)
      fork_parent_proc();
  }

  GC_API void GC_CALL GC_atfork_child(void)
  {
    if (GC_handle_fork <= 0)
      fork_child_proc();
  }
#endif /* CAN_HANDLE_FORK */

void GC_push_thread_structures(void)
{
  GC_ASSERT(I_HOLD_LOCK());
# ifndef GC_NO_THREADS_DISCOVERY
    if (GC_win32_dll_threads) {
      /* Unlike the other threads implementations, the thread table     */
      /* here contains no pointers to the collectible heap (note also   */
      /* that GC_PTHREADS is incompatible with DllMain-based thread     */
      /* registration).  Thus we have no private structures we need     */
      /* to preserve.                                                   */
    } else
# endif
  /* else */ {
    GC_PUSH_ALL_SYM(GC_threads);
  }
# if defined(THREAD_LOCAL_ALLOC)
    GC_PUSH_ALL_SYM(GC_thread_key);
    /* Just in case we ever use our own TLS implementation.     */
# endif
}

/* Suspend the given thread, if it's still active.      */
STATIC void GC_suspend(GC_thread t)
{
# ifndef MSWINCE
    /* Apparently the Windows 95 GetOpenFileName call creates           */
    /* a thread that does not properly get cleaned up, and              */
    /* SuspendThread on its descriptor may provoke a crash.             */
    /* This reduces the probability of that event, though it still      */
    /* appears there's a race here.                                     */
    DWORD exitCode;
# endif
  UNPROTECT_THREAD(t);
# ifndef MSWINCE
eg's avatar
eg committed
1165 1166
    if (GetExitCodeThread(t -> handle, &exitCode) &&
        exitCode != STILL_ACTIVE) {
1167
#     ifdef GC_PTHREADS
1168
        t -> stack_base = 0; /* prevent stack from being pushed */
1169
#     else
eg's avatar
eg committed
1170
        /* this breaks pthread_join on Cygwin, which is guaranteed to  */
1171 1172 1173
        /* only see user pthreads                                      */
        GC_ASSERT(GC_win32_dll_threads);
        GC_delete_gc_thread_no_free(t);
eg's avatar
eg committed
1174
#     endif
eg's avatar
eg committed
1175
      return;
eg's avatar
eg committed
1176
    }
1177 1178 1179 1180 1181 1182 1183 1184 1185
# endif
# if defined(MPROTECT_VDB)
    /* Acquire the spin lock we use to update dirty bits.       */
    /* Threads shouldn't get stopped holding it.  But we may    */
    /* acquire and release it in the UNPROTECT_THREAD call.     */
    while (AO_test_and_set_acquire(&GC_fault_handler_lock) == AO_TS_SET) {
      /* empty */
    }
# endif
1186

1187 1188 1189 1190 1191
# ifdef MSWINCE
    /* SuspendThread() will fail if thread is running kernel code.      */
    while (SuspendThread(THREAD_HANDLE(t)) == (DWORD)-1)
      Sleep(10); /* in millis */
# else
eg's avatar
eg committed
1192 1193
    if (SuspendThread(t -> handle) == (DWORD)-1)
      ABORT("SuspendThread failed");
1194 1195 1196 1197
# endif /* !MSWINCE */
  t -> suspended = (unsigned char)TRUE;
# if defined(MPROTECT_VDB)
    AO_CLEAR(&GC_fault_handler_lock);
eg's avatar
eg committed
1198
# endif
1199 1200
  if (GC_on_thread_event)
    GC_on_thread_event(GC_EVENT_THREAD_SUSPENDED, THREAD_HANDLE(t));
eg's avatar
eg committed
1201 1202
}

1203 1204 1205
#if defined(GC_ASSERTIONS) && !defined(CYGWIN32)
  GC_INNER GC_bool GC_write_disabled = FALSE;
                /* TRUE only if GC_stop_world() acquired GC_write_cs.   */
eg's avatar
eg committed
1206 1207
#endif

1208
GC_INNER void GC_stop_world(void)
eg's avatar
eg committed
1209 1210
{
  DWORD thread_id = GetCurrentThreadId();
eg's avatar
eg committed
1211

1212 1213
  if (!GC_thr_initialized)
    ABORT("GC_stop_world() called before GC_thr_init()");
eg's avatar
eg committed
1214 1215
  GC_ASSERT(I_HOLD_LOCK());

1216 1217 1218 1219 1220 1221 1222 1223 1224
  /* This code is the same as in pthread_stop_world.c */
# ifdef PARALLEL_MARK
    if (GC_parallel) {
      GC_acquire_mark_lock();
      GC_ASSERT(GC_fl_builder_count == 0);
      /* We should have previously waited for it to become zero. */
    }
# endif /* PARALLEL_MARK */

1225 1226 1227
# if !defined(GC_NO_THREADS_DISCOVERY) || defined(GC_ASSERTIONS)
    GC_please_stop = TRUE;
# endif
eg's avatar
eg committed
1228
# ifndef CYGWIN32
1229
    GC_ASSERT(!GC_write_disabled);
eg's avatar
eg committed
1230
    EnterCriticalSection(&GC_write_cs);
1231 1232 1233 1234 1235 1236 1237
    /* It's not allowed to call GC_printf() (and friends) here down to  */
    /* LeaveCriticalSection (same applies recursively to GC_suspend,    */
    /* GC_delete_gc_thread_no_free, GC_get_max_thread_index, GC_size    */
    /* and GC_remove_protection).                                       */
#   ifdef GC_ASSERTIONS
      GC_write_disabled = TRUE;
#   endif
eg's avatar
eg committed
1238
# endif
1239 1240
# ifndef GC_NO_THREADS_DISCOVERY
    if (GC_win32_dll_threads) {
1241
      int i;
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
      int my_max;
      /* Any threads being created during this loop will end up setting */
      /* GC_attached_thread when they start.  This will force marking   */
      /* to restart.  This is not ideal, but hopefully correct.         */
      AO_store(&GC_attached_thread, FALSE);
      my_max = (int)GC_get_max_thread_index();
      for (i = 0; i <= my_max; i++) {
        GC_vthread t = dll_thread_table + i;
        if (t -> stack_base != 0 && t -> thread_blocked_sp == NULL
            && t -> id != thread_id) {
          GC_suspend((GC_thread)t);
        }
      }
    } else
# endif
  /* else */ {
    GC_thread t;
    int i;
eg's avatar
eg committed
1260

1261 1262 1263 1264 1265 1266
    for (i = 0; i < THREAD_TABLE_SZ; i++) {
      for (t = GC_threads[i]; t != 0; t = t -> tm.next) {
        if (t -> stack_base != 0 && t -> thread_blocked_sp == NULL
            && !KNOWN_FINISHED(t) && t -> id != thread_id) {
          GC_suspend(t);
        }
eg's avatar
eg committed
1267
      }
1268
    }
eg's avatar
eg committed
1269 1270
  }
# ifndef CYGWIN32
1271 1272 1273
#   ifdef GC_ASSERTIONS
      GC_write_disabled = FALSE;
#   endif
eg's avatar
eg committed
1274
    LeaveCriticalSection(&GC_write_cs);
1275
# endif
1276 1277 1278 1279
# ifdef PARALLEL_MARK
    if (GC_parallel)
      GC_release_mark_lock();
# endif
eg's avatar
eg committed
1280 1281
}

1282
GC_INNER void GC_start_world(void)
eg's avatar
eg committed
1283
{
1284 1285 1286
# ifdef GC_ASSERTIONS
    DWORD thread_id = GetCurrentThreadId();
# endif
eg's avatar
eg committed
1287 1288 1289

  GC_ASSERT(I_HOLD_LOCK());
  if (GC_win32_dll_threads) {
1290
    LONG my_max = GC_get_max_thread_index();
1291 1292
    int i;

eg's avatar
eg committed
1293 1294
    for (i = 0; i <= my_max; i++) {
      GC_thread t = (GC_thread)(dll_thread_table + i);
1295 1296 1297 1298
      if (t -> suspended) {
        GC_ASSERT(t -> stack_base != 0 && t -> id != thread_id);
        if (ResumeThread(THREAD_HANDLE(t)) == (DWORD)-1)
          ABORT("ResumeThread failed");
eg's avatar
eg committed
1299
        t -> suspended = FALSE;
1300 1301
        if (GC_on_thread_event)
          GC_on_thread_event(GC_EVENT_THREAD_UNSUSPENDED, THREAD_HANDLE(t));
eg's avatar
eg committed
1302 1303 1304 1305 1306 1307 1308
      }
    }
  } else {
    GC_thread t;
    int i;

    for (i = 0; i < THREAD_TABLE_SZ; i++) {
1309 1310 1311 1312 1313 1314
      for (t = GC_threads[i]; t != 0; t = t -> tm.next) {
        if (t -> suspended) {
          GC_ASSERT(t -> stack_base != 0 && t -> id != thread_id);
          if (ResumeThread(THREAD_HANDLE(t)) == (DWORD)-1)
            ABORT("ResumeThread failed");
          UNPROTECT_THREAD(t);
eg's avatar
eg committed
1315
          t -> suspended = FALSE;
1316 1317
          if (GC_on_thread_event)
            GC_on_thread_event(GC_EVENT_THREAD_UNSUSPENDED, THREAD_HANDLE(t));
eg's avatar
eg committed
1318 1319 1320 1321
        }
      }
    }
  }
1322 1323 1324
# if !defined(GC_NO_THREADS_DISCOVERY) || defined(GC_ASSERTIONS)
    GC_please_stop = FALSE;
# endif
eg's avatar
eg committed
1325 1326
}

1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
#ifdef MSWINCE
  /* The VirtualQuery calls below won't work properly on some old WinCE */
  /* versions, but since each stack is restricted to an aligned 64 KiB  */
  /* region of virtual memory we can just take the next lowest multiple */
  /* of 64 KiB.  The result of this macro must not be used as its       */
  /* argument later and must not be used as the lower bound for sp      */
  /* check (since the stack may be bigger than 64 KiB).                 */
# define GC_wince_evaluate_stack_min(s) \
                        (ptr_t)(((word)(s) - 1) & ~(word)0xFFFF)
#elif defined(GC_ASSERTIONS)
# define GC_dont_query_stack_min FALSE
#endif
1339

1340 1341 1342 1343
/* A cache holding the results of the recent VirtualQuery call. */
/* Protected by the allocation lock.                            */
static ptr_t last_address = 0;
static MEMORY_BASIC_INFORMATION last_info;
1344

1345 1346 1347 1348 1349 1350 1351
/* Probe stack memory region (starting at "s") to find out its  */
/* lowest address (i.e. stack top).                             */
/* S must be a mapped address inside the region, NOT the first  */
/* unmapped address.                                            */
STATIC ptr_t GC_get_stack_min(ptr_t s)
{
  ptr_t bottom;
1352

1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
  GC_ASSERT(I_HOLD_LOCK());
  if (s != last_address) {
    VirtualQuery(s, &last_info, sizeof(last_info));
    last_address = s;
  }
  do {
    bottom = last_info.BaseAddress;
    VirtualQuery(bottom - 1, &last_info, sizeof(last_info));
    last_address = bottom - 1;
  } while ((last_info.Protect & PAGE_READWRITE)
           && !(last_info.Protect & PAGE_GUARD));
  return(bottom);
}
eg's avatar
eg committed
1366

1367 1368 1369
/* Return true if the page at s has protections appropriate     */
/* for a stack page.                                            */
static GC_bool may_be_in_stack(ptr_t s)
eg's avatar
eg committed
1370
{
1371 1372 1373 1374 1375 1376 1377 1378
  GC_ASSERT(I_HOLD_LOCK());
  if (s != last_address) {
    VirtualQuery(s, &last_info, sizeof(last_info));
    last_address = s;
  }
  return (last_info.Protect & PAGE_READWRITE)
          && !(last_info.Protect & PAGE_GUARD);
}
eg's avatar
eg committed
1379

1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
STATIC word GC_push_stack_for(GC_thread thread, DWORD me)
{
  ptr_t sp, stack_min;

  struct GC_traced_stack_sect_s *traced_stack_sect =
                                      thread -> traced_stack_sect;
  if (thread -> id == me) {
    GC_ASSERT(thread -> thread_blocked_sp == NULL);
    sp = GC_approx_sp();
  } else if ((sp = thread -> thread_blocked_sp) == NULL) {
              /* Use saved sp value for blocked threads. */
    /* For unblocked threads call GetThreadContext().   */
    CONTEXT context;
    context.ContextFlags = CONTEXT_INTEGER|CONTEXT_CONTROL;
    if (!GetThreadContext(THREAD_HANDLE(thread), &context))
      ABORT("GetThreadContext failed");

    /* Push all registers that might point into the heap.  Frame        */
    /* pointer registers are included in case client code was           */
    /* compiled with the 'omit frame pointer' optimization.             */
#   define PUSH1(reg) GC_push_one((word)context.reg)
#   define PUSH2(r1,r2) (PUSH1(r1), PUSH1(r2))
#   define PUSH4(r1,r2,r3,r4) (PUSH2(r1,r2), PUSH2(r3,r4))
#   if defined(I386)
      PUSH4(Edi,Esi,Ebx,Edx), PUSH2(Ecx,Eax), PUSH1(Ebp);
      sp = (ptr_t)context.Esp;
#   elif defined(X86_64)
      PUSH4(Rax,Rcx,Rdx,Rbx); PUSH2(Rbp, Rsi); PUSH1(Rdi);
      PUSH4(R8, R9, R10, R11); PUSH4(R12, R13, R14, R15);
      sp = (ptr_t)context.Rsp;
#   elif defined(ARM32)
      PUSH4(R0,R1,R2,R3),PUSH4(R4,R5,R6,R7),PUSH4(R8,R9,R10,R11);
      PUSH1(R12);
      sp = (ptr_t)context.Sp;
#   elif defined(SHx)
      PUSH4(R0,R1,R2,R3), PUSH4(R4,R5,R6,R7), PUSH4(R8,R9,R10,R11);
      PUSH2(R12,R13), PUSH1(R14);
      sp = (ptr_t)context.R15;
#   elif defined(MIPS)
      PUSH4(IntAt,IntV0,IntV1,IntA0), PUSH4(IntA1,IntA2,IntA3,IntT0);
      PUSH4(IntT1,IntT2,IntT3,IntT4), PUSH4(IntT5,IntT6,IntT7,IntS0);
      PUSH4(IntS1,IntS2,IntS3,IntS4), PUSH4(IntS5,IntS6,IntS7,IntT8);
      PUSH4(IntT9,IntK0,IntK1,IntS8);
      sp = (ptr_t)context.IntSp;
#   elif defined(PPC)
      PUSH4(Gpr0, Gpr3, Gpr4, Gpr5),  PUSH4(Gpr6, Gpr7, Gpr8, Gpr9);
      PUSH4(Gpr10,Gpr11,Gpr12,Gpr14), PUSH4(Gpr15,Gpr16,Gpr17,Gpr18);
      PUSH4(Gpr19,Gpr20,Gpr21,Gpr22), PUSH4(Gpr23,Gpr24,Gpr25,Gpr26);
      PUSH4(Gpr27,Gpr28,Gpr29,Gpr30), PUSH1(Gpr31);
      sp = (ptr_t)context.Gpr1;
#   elif defined(ALPHA)
      PUSH4(IntV0,IntT0,IntT1,IntT2), PUSH4(IntT3,IntT4,IntT5,IntT6);
      PUSH4(IntT7,IntS0,IntS1,IntS2), PUSH4(IntS3,IntS4,IntS5,IntFp);
      PUSH4(IntA0,IntA1,IntA2,IntA3), PUSH4(IntA4,IntA5,IntT8,IntT9);
      PUSH4(IntT10,IntT11,IntT12,IntAt);
      sp = (ptr_t)context.IntSp;
#   elif !defined(CPPCHECK)
#     error "architecture is not supported"
#   endif
  } /* ! current thread */

  /* Set stack_min to the lowest address in the thread stack,   */
  /* or to an address in the thread stack no larger than sp,    */
  /* taking advantage of the old value to avoid slow traversals */
  /* of large stacks.                                           */
  if (thread -> last_stack_min == ADDR_LIMIT) {
#   ifdef MSWINCE
      if (GC_dont_query_stack_min) {
        stack_min = GC_wince_evaluate_stack_min(traced_stack_sect != NULL ?
                      (ptr_t)traced_stack_sect : thread -> stack_base);
        /* Keep last_stack_min value unmodified. */
      } else
#   endif
    /* else */ {
      stack_min = GC_get_stack_min(traced_stack_sect != NULL ?
                      (ptr_t)traced_stack_sect : thread -> stack_base);
      UNPROTECT_THREAD(thread);
      thread -> last_stack_min = stack_min;
    }
  } else {
    /* First, adjust the latest known minimum stack address if we       */
    /* are inside GC_call_with_gc_active().                             */
    if (traced_stack_sect != NULL &&
        (word)thread->last_stack_min > (word)traced_stack_sect) {
      UNPROTECT_THREAD(thread);
      thread -> last_stack_min = (ptr_t)traced_stack_sect;
    }

    if ((word)sp < (word)thread->stack_base
        && (word)sp >= (word)thread->last_stack_min) {
      stack_min = sp;
    } else {
      /* In the current thread it is always safe to use sp value.       */
      if (may_be_in_stack(thread -> id == me &&
                          (word)sp < (word)thread->last_stack_min ?
                          sp : thread -> last_stack_min)) {
        stack_min = last_info.BaseAddress;
        /* Do not probe rest of the stack if sp is correct. */
        if ((word)sp < (word)stack_min
            || (word)sp >= (word)thread->stack_base)
          stack_min = GC_get_stack_min(thread -> last_stack_min);
1481
      } else {
1482 1483
        /* Stack shrunk?  Is this possible? */
        stack_min = GC_get_stack_min(thread -> stack_base);
1484
      }
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
      UNPROTECT_THREAD(thread);
      thread -> last_stack_min = stack_min;
    }
  }

  GC_ASSERT(GC_dont_query_stack_min
            || stack_min == GC_get_stack_min(thread -> stack_base)
            || ((word)sp >= (word)stack_min
                && (word)stack_min < (word)thread->stack_base
                && (word)stack_min
                        > (word)GC_get_stack_min(thread -> stack_base)));

  if ((word)sp >= (word)stack_min && (word)sp < (word)thread->stack_base) {
#   ifdef DEBUG_THREADS
      GC_log_printf("Pushing stack for 0x%x from sp %p to %p from 0x%x\n",
                    (int)thread->id, (void *)sp, (void *)thread->stack_base,
                    (int)me);
#   endif
    GC_push_all_stack_sections(sp, thread->stack_base, traced_stack_sect);
  } else {
    /* If not current thread then it is possible for sp to point to     */
    /* the guarded (untouched yet) page just below the current          */
    /* stack_min of the thread.                                         */
    if (thread -> id == me || (word)sp >= (word)thread->stack_base
        || (word)(sp + GC_page_size) < (word)stack_min)
      WARN("Thread stack pointer %p out of range, pushing everything\n",
           sp);
#   ifdef DEBUG_THREADS
      GC_log_printf("Pushing stack for 0x%x from (min) %p to %p from 0x%x\n",
                    (int)thread->id, (void *)stack_min,
                    (void *)thread->stack_base, (int)me);
#   endif
    /* Push everything - ignore "traced stack section" data.            */
    GC_push_all_stack(stack_min, thread->stack_base);
  }
  return thread->stack_base - sp; /* stack grows down */
eg's avatar
eg committed
1521 1522
}

1523
GC_INNER void GC_push_all_stacks(void)
eg's avatar
eg committed
1524
{
1525
  DWORD thread_id = GetCurrentThreadId();
eg's avatar
eg committed
1526
  GC_bool found_me = FALSE;
1527 1528 1529
# ifndef SMALL_CONFIG
    unsigned nthreads = 0;
# endif
1530 1531 1532 1533 1534
  word total_size = 0;
# ifndef GC_NO_THREADS_DISCOVERY
    if (GC_win32_dll_threads) {
      int i;
      LONG my_max = GC_get_max_thread_index();
eg's avatar
eg committed
1535

1536 1537 1538 1539 1540 1541 1542 1543 1544
      for (i = 0; i <= my_max; i++) {
        GC_thread t = (GC_thread)(dll_thread_table + i);
        if (t -> tm.in_use && t -> stack_base) {
#         ifndef SMALL_CONFIG
            ++nthreads;
#         endif
          total_size += GC_push_stack_for(t, thread_id);
          if (t -> id == thread_id) found_me = TRUE;
        }
eg's avatar
eg committed
1545
      }
1546 1547 1548
    } else
# endif
  /* else */ {
eg's avatar
eg committed
1549 1550
    int i;
    for (i = 0; i < THREAD_TABLE_SZ; i++) {
1551 1552 1553 1554 1555 1556 1557 1558 1559
      GC_thread t;
      for (t = GC_threads[i]; t != 0; t = t -> tm.next) {
        if (!KNOWN_FINISHED(t) && t -> stack_base) {
#         ifndef SMALL_CONFIG
            ++nthreads;
#         endif
          total_size += GC_push_stack_for(t, thread_id);
          if (t -> id == thread_id) found_me = TRUE;
        }
eg's avatar
eg committed
1560 1561
      }
    }
eg's avatar
eg committed
1562
  }
1563
# ifndef SMALL_CONFIG
1564 1565 1566
    GC_VERBOSE_LOG_PRINTF("Pushed %d thread stacks%s\n", nthreads,
                          GC_win32_dll_threads ?
                                " based on DllMain thread tracking" : "");
1567
# endif
1568
  if (!found_me && !GC_in_thread_creation)
1569 1570
    ABORT("Collecting from unknown thread");
  GC_total_stacksize = total_size;
eg's avatar
eg committed
1571 1572
}

1573 1574 1575 1576 1577 1578
#ifdef PARALLEL_MARK

# ifndef MAX_MARKERS
#   define MAX_MARKERS 16
# endif

1579 1580
  static ptr_t marker_sp[MAX_MARKERS - 1]; /* The cold end of the stack */
                                           /* for markers.              */
1581
# ifdef IA64
1582
    static ptr_t marker_bsp[MAX_MARKERS - 1];
1583 1584
# endif

1585 1586 1587 1588
  static ptr_t marker_last_stack_min[MAX_MARKERS - 1];
                                /* Last known minimum (hottest) address */
                                /* in stack (or ADDR_LIMIT if unset)    */
                                /* for markers.                         */
1589

1590
#endif /* PARALLEL_MARK */
1591

1592 1593 1594 1595 1596 1597 1598
/* Find stack with the lowest address which overlaps the        */
/* interval [start, limit).                                     */
/* Return stack bounds in *lo and *hi.  If no such stack        */
/* is found, both *hi and *lo will be set to an address         */
/* higher than limit.                                           */
GC_INNER void GC_get_next_stack(char *start, char *limit,
                                char **lo, char **hi)
eg's avatar
eg committed
1599
{
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
  int i;
  char * current_min = ADDR_LIMIT;  /* Least in-range stack base      */
  ptr_t *plast_stack_min = NULL;    /* Address of last_stack_min      */
                                    /* field for thread corresponding */
                                    /* to current_min.                */
  GC_thread thread = NULL;          /* Either NULL or points to the   */
                                    /* thread's hash table entry      */
                                    /* containing *plast_stack_min.   */

  /* First set current_min, ignoring limit. */
  if (GC_win32_dll_threads) {
    LONG my_max = GC_get_max_thread_index();

    for (i = 0; i <= my_max; i++) {
      ptr_t s = (ptr_t)(dll_thread_table[i].stack_base);

      if ((word)s > (word)start && (word)s < (word)current_min) {
        /* Update address of last_stack_min. */
        plast_stack_min = (ptr_t * /* no volatile */)
                            &dll_thread_table[i].last_stack_min;
        current_min = s;
#       if defined(CPPCHECK)
          /* To avoid a warning that thread is always null.     */
          thread = (GC_thread)&dll_thread_table[i];
#       endif
      }
    }
  } else {
    for (i = 0; i < THREAD_TABLE_SZ; i++) {
      GC_thread t;

      for (t = GC_threads[i]; t != 0; t = t -> tm.next) {
        ptr_t s = t -> stack_base;

        if ((word)s > (word)start && (word)s < (word)current_min) {
          /* Update address of last_stack_min. */
          plast_stack_min = &t -> last_stack_min;
          thread = t; /* Remember current thread to unprotect. */
          current_min = s;
eg's avatar
eg committed
1639
        }
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
      }
    }
#   ifdef PARALLEL_MARK
      for (i = 0; i < GC_markers_m1; ++i) {
        ptr_t s = marker_sp[i];
#       ifdef IA64
          /* FIXME: not implemented */
#       endif
        if ((word)s > (word)start && (word)s < (word)current_min) {
          GC_ASSERT(marker_last_stack_min[i] != NULL);
          plast_stack_min = &marker_last_stack_min[i];
          current_min = s;
          thread = NULL; /* Not a thread's hash table entry. */
1653 1654
        }
      }
1655 1656
#   endif
  }
1657

1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
  *hi = current_min;
  if (current_min == ADDR_LIMIT) {
      *lo = ADDR_LIMIT;
      return;
  }

  GC_ASSERT((word)current_min > (word)start && plast_stack_min != NULL);
# ifdef MSWINCE
    if (GC_dont_query_stack_min) {
      *lo = GC_wince_evaluate_stack_min(current_min);
      /* Keep last_stack_min value unmodified. */
      return;
1670
    }
1671
# endif
1672

1673 1674 1675 1676 1677 1678 1679
  if ((word)current_min > (word)limit && !may_be_in_stack(limit)) {
    /* Skip the rest since the memory region at limit address is        */
    /* not a stack (so the lowest address of the found stack would      */
    /* be above the limit value anyway).                                */
    *lo = ADDR_LIMIT;
    return;
  }
1680

1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
  /* Get the minimum address of the found stack by probing its memory   */
  /* region starting from the recent known minimum (if set).            */
  if (*plast_stack_min == ADDR_LIMIT
      || !may_be_in_stack(*plast_stack_min)) {
    /* Unsafe to start from last_stack_min value. */
    *lo = GC_get_stack_min(current_min);
  } else {
    /* Use the recent value to optimize search for min address. */
    *lo = GC_get_stack_min(*plast_stack_min);
  }
1691

1692 1693 1694 1695 1696
  /* Remember current stack_min value. */
  if (thread != NULL) {
    UNPROTECT_THREAD(thread);
  }
  *plast_stack_min = *lo;
eg's avatar
eg committed
1697 1698
}

1699 1700
#ifdef PARALLEL_MARK

1701 1702
# if defined(GC_PTHREADS) && !defined(GC_PTHREADS_PARAMARK)
    /* Use pthread-based parallel mark implementation.    */
1703

1704 1705 1706 1707 1708
    /* Workaround a deadlock in winpthreads-3.0b internals (observed    */
    /* with MinGW 32/64).                                               */
#   if !defined(__MINGW32__)
#     define GC_PTHREADS_PARAMARK
#   endif
1709 1710
# endif

1711 1712 1713 1714
# if !defined(GC_PTHREADS_PARAMARK)
    STATIC HANDLE GC_marker_cv[MAX_MARKERS - 1] = {0};
                        /* Events with manual reset (one for each       */
                        /* mark helper).                                */
1715

1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
    STATIC DWORD GC_marker_Id[MAX_MARKERS - 1] = {0};
                        /* This table is used for mapping helper        */
                        /* threads ID to mark helper index (linear      */
                        /* search is used since the mapping contains    */
                        /* only a few entries).                         */
# endif

  /* GC_mark_thread() is the same as in pthread_support.c */
# ifdef GC_PTHREADS_PARAMARK
    STATIC void * GC_mark_thread(void * id)
# elif defined(MSWINCE)
    STATIC DWORD WINAPI GC_mark_thread(LPVOID id)
# else
    STATIC unsigned __stdcall GC_mark_thread(void * id)
# endif
  {
    word my_mark_no = 0;

    if ((word)id == (word)-1) return 0; /* to make compiler happy */
    marker_sp[(word)id] = GC_approx_sp();
#   ifdef IA64
      marker_bsp[(word)id] = GC_save_regs_in_stack();
1738
#   endif
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
#   if !defined(GC_PTHREADS_PARAMARK)
      GC_marker_Id[(word)id] = GetCurrentThreadId();
#   endif

    /* Inform GC_start_mark_threads about completion of marker data init. */
    GC_acquire_mark_lock();
    if (0 == --GC_fl_builder_count) /* count may have a negative value */
      GC_notify_all_builder();

    for (;; ++my_mark_no) {
      if (my_mark_no - GC_mark_no > (word)2) {
        /* resynchronize if we get far off, e.g. because GC_mark_no     */
        /* wrapped.                                                     */
        my_mark_no = GC_mark_no;
      }
#     ifdef DEBUG_THREADS
        GC_log_printf("Starting mark helper for mark number %lu\n",
                      (unsigned long)my_mark_no);
#     endif
      GC_help_marker(my_mark_no);
    }
1760
  }
1761

1762 1763 1764 1765
# ifndef GC_ASSERTIONS
#   define SET_MARK_LOCK_HOLDER (void)0
#   define UNSET_MARK_LOCK_HOLDER (void)0
# endif
1766

1767
  /* GC_mark_threads[] is unused here unlike that in pthread_support.c  */
1768

1769 1770 1771 1772 1773
# ifdef CAN_HANDLE_FORK
    static int available_markers_m1 = 0;
# else
#   define available_markers_m1 GC_markers_m1
# endif
1774

1775 1776
# ifdef GC_PTHREADS_PARAMARK
#   include <pthread.h>
1777

1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
#   if defined(GC_ASSERTIONS) && !defined(NUMERIC_THREAD_ID)
#     define NUMERIC_THREAD_ID(id) (unsigned long)(word)GC_PTHREAD_PTRVAL(id)
      /* Id not guaranteed to be unique. */
#   endif

#   ifdef CAN_HANDLE_FORK
      static pthread_cond_t mark_cv;
                        /* initialized by GC_start_mark_threads_inner   */
#   else
      static pthread_cond_t mark_cv = PTHREAD_COND_INITIALIZER;
#   endif

    /* GC_start_mark_threads is the same as in pthread_support.c except */
    /* for thread stack that is assumed to be large enough.             */

    GC_INNER void GC_start_mark_threads_inner(void)
    {
      int i;
      pthread_attr_t attr;
      pthread_t new_thread;
#     ifndef NO_MARKER_SPECIAL_SIGMASK
        sigset_t set, oldset;
#     endif

      GC_ASSERT(I_DONT_HOLD_LOCK());
      if (available_markers_m1 <= 0) return;
                /* Skip if parallel markers disabled or already started. */
#     ifdef CAN_HANDLE_FORK
        if (GC_parallel) return;

        /* Reset mark_cv state after forking (as in pthread_support.c). */
        {
          pthread_cond_t mark_cv_local = PTHREAD_COND_INITIALIZER;
          BCOPY(&mark_cv_local, &mark_cv, sizeof(mark_cv));
        }
#     endif

      GC_ASSERT(GC_fl_builder_count == 0);
      if (0 != pthread_attr_init(&attr)) ABORT("pthread_attr_init failed");
      if (0 != pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED))
        ABORT("pthread_attr_setdetachstate failed");

#     ifndef NO_MARKER_SPECIAL_SIGMASK
        /* Apply special signal mask to GC marker threads, and don't drop */
        /* user defined signals by GC marker threads.                     */
        if (sigfillset(&set) != 0)
          ABORT("sigfillset failed");
        if (pthread_sigmask(SIG_BLOCK, &set, &oldset) < 0) {
          WARN("pthread_sigmask set failed, no markers started,"
               " errno = %" WARN_PRIdPTR "\n", errno);
          GC_markers_m1 = 0;
          (void)pthread_attr_destroy(&attr);
          return;
        }
#     endif /* !NO_MARKER_SPECIAL_SIGMASK */

#     ifdef CAN_HANDLE_FORK
        /* To have proper GC_parallel value in GC_help_marker.  */
        GC_markers_m1 = available_markers_m1;
#     endif
      for (i = 0; i < available_markers_m1; ++i) {
        marker_last_stack_min[i] = ADDR_LIMIT;
        if (0 != pthread_create(&new_thread, &attr,
                                GC_mark_thread, (void *)(word)i)) {
          WARN("Marker thread creation failed\n", 0);
          /* Don't try to create other marker threads.    */
          GC_markers_m1 = i;
          break;
        }
1847
      }
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859

#     ifndef NO_MARKER_SPECIAL_SIGMASK
        /* Restore previous signal mask.        */
        if (pthread_sigmask(SIG_SETMASK, &oldset, NULL) < 0) {
          WARN("pthread_sigmask restore failed, errno = %" WARN_PRIdPTR "\n",
               errno);
        }
#     endif

      (void)pthread_attr_destroy(&attr);
      GC_wait_for_markers_init();
      GC_COND_LOG_PRINTF("Started %d mark helper threads\n", GC_markers_m1);
1860 1861
    }

1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
#   ifdef GC_ASSERTIONS
      STATIC unsigned long GC_mark_lock_holder = NO_THREAD;
#     define SET_MARK_LOCK_HOLDER \
                (void)(GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self()))
#     define UNSET_MARK_LOCK_HOLDER \
                do { \
                  GC_ASSERT(GC_mark_lock_holder \
                                == NUMERIC_THREAD_ID(pthread_self())); \
                  GC_mark_lock_holder = NO_THREAD; \
                } while (0)
#   endif /* GC_ASSERTIONS */
1873

1874
    static pthread_mutex_t mark_mutex = PTHREAD_MUTEX_INITIALIZER;
1875

1876
    static pthread_cond_t builder_cv = PTHREAD_COND_INITIALIZER;
1877

1878 1879 1880
    /* GC_acquire/release_mark_lock(), GC_wait_builder/marker(),          */
    /* GC_wait_for_reclaim(), GC_notify_all_builder/marker() are the same */
    /* as in pthread_support.c except that GC_generic_lock() is not used. */
1881

1882
#   ifdef LOCK_STATS
1883
      volatile AO_t GC_block_count = 0;
1884
#   endif
1885

1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
    GC_INNER void GC_acquire_mark_lock(void)
    {
#     ifdef NUMERIC_THREAD_ID_UNIQUE
        GC_ASSERT(GC_mark_lock_holder != NUMERIC_THREAD_ID(pthread_self()));
#     endif
      if (pthread_mutex_lock(&mark_mutex) != 0) {
        ABORT("pthread_mutex_lock failed");
      }
#     ifdef LOCK_STATS
        (void)AO_fetch_and_add1(&GC_block_count);
#     endif
      /* GC_generic_lock(&mark_mutex); */
      SET_MARK_LOCK_HOLDER;
1899 1900
    }

1901 1902 1903 1904 1905 1906
    GC_INNER void GC_release_mark_lock(void)
    {
      UNSET_MARK_LOCK_HOLDER;