Remove a note in README.macros that work in progress
[platform/upstream/libgc.git] / darwin_stop_world.c
1 /*
2  * Copyright (c) 1994 by Xerox Corporation.  All rights reserved.
3  * Copyright (c) 1996 by Silicon Graphics.  All rights reserved.
4  * Copyright (c) 1998 by Fergus Henderson.  All rights reserved.
5  * Copyright (c) 2000-2010 by Hewlett-Packard Development Company.
6  * All rights reserved.
7  *
8  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
9  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
10  *
11  * Permission is hereby granted to use or copy this program
12  * for any purpose,  provided the above notices are retained on all copies.
13  * Permission to modify the code and to distribute modified code is granted,
14  * provided the above notices are retained, and a notice that the code was
15  * modified is included with the above copyright notice.
16  */
17
18 #include "private/pthread_support.h"
19
20 /* This probably needs more porting work to ppc64. */
21
22 #if defined(GC_DARWIN_THREADS)
23
24 #include <sys/sysctl.h>
25 #include <mach/machine.h>
26 #include <CoreFoundation/CoreFoundation.h>
27
28 /* From "Inside Mac OS X - Mach-O Runtime Architecture" published by Apple
29    Page 49:
30    "The space beneath the stack pointer, where a new stack frame would normally
31    be allocated, is called the red zone. This area as shown in Figure 3-2 may
32    be used for any purpose as long as a new stack frame does not need to be
33    added to the stack."
34
35    Page 50: "If a leaf procedure's red zone usage would exceed 224 bytes, then
36    it must set up a stack frame just like routines that call other routines."
37 */
38 #ifdef POWERPC
39 # if CPP_WORDSZ == 32
40 #   define PPC_RED_ZONE_SIZE 224
41 # elif CPP_WORDSZ == 64
42 #   define PPC_RED_ZONE_SIZE 320
43 # endif
44 #endif
45
46 #ifndef DARWIN_DONT_PARSE_STACK
47
48 typedef struct StackFrame {
49   unsigned long savedSP;
50   unsigned long savedCR;
51   unsigned long savedLR;
52   unsigned long reserved[2];
53   unsigned long savedRTOC;
54 } StackFrame;
55
56 GC_INNER ptr_t GC_FindTopOfStack(unsigned long stack_start)
57 {
58   StackFrame *frame = (StackFrame *)stack_start;
59
60   if (stack_start == 0) {
61 #   ifdef POWERPC
62 #     if CPP_WORDSZ == 32
63         __asm__ __volatile__ ("lwz %0,0(r1)" : "=r" (frame));
64 #     else
65         __asm__ __volatile__ ("ld %0,0(r1)" : "=r" (frame));
66 #     endif
67 #   elif defined(ARM32)
68         volatile ptr_t sp_reg;
69         __asm__ __volatile__ ("mov %0, r7\n" : "=r" (sp_reg));
70         frame = (StackFrame *)sp_reg;
71 #   elif defined(AARCH64)
72         volatile ptr_t sp_reg;
73         __asm__ __volatile__ ("mov %0, x29\n" : "=r" (sp_reg));
74         frame = (StackFrame *)sp_reg;
75 #   else
76       ABORT("GC_FindTopOfStack(0) is not implemented");
77 #   endif
78   }
79
80 # ifdef DEBUG_THREADS_EXTRA
81     GC_log_printf("FindTopOfStack start at sp = %p\n", (void *)frame);
82 # endif
83   while (frame->savedSP != 0) {
84     /* if there are no more stack frames, stop */
85
86     frame = (StackFrame*)frame->savedSP;
87
88     /* we do these next two checks after going to the next frame
89        because the LR for the first stack frame in the loop
90        is not set up on purpose, so we shouldn't check it. */
91     if ((frame->savedLR & ~0x3) == 0 || (frame->savedLR & ~0x3) == ~0x3UL)
92       break; /* if the next LR is bogus, stop */
93   }
94 # ifdef DEBUG_THREADS_EXTRA
95     GC_log_printf("FindTopOfStack finish at sp = %p\n", (void *)frame);
96 # endif
97   return (ptr_t)frame;
98 }
99
100 #endif /* !DARWIN_DONT_PARSE_STACK */
101
102 /* GC_query_task_threads controls whether to obtain the list of */
103 /* the threads from the kernel or to use GC_threads table.      */
104 #ifdef GC_NO_THREADS_DISCOVERY
105 # define GC_query_task_threads FALSE
106 #elif defined(GC_DISCOVER_TASK_THREADS)
107 # define GC_query_task_threads TRUE
108 #else
109   STATIC GC_bool GC_query_task_threads = FALSE;
110 #endif /* !GC_NO_THREADS_DISCOVERY */
111
112 /* Use implicit threads registration (all task threads excluding the GC */
113 /* special ones are stopped and scanned).  Should be called before      */
114 /* GC_INIT() (or, at least, before going multi-threaded).  Deprecated.  */
115 GC_API void GC_CALL GC_use_threads_discovery(void)
116 {
117 # if defined(GC_NO_THREADS_DISCOVERY) || defined(DARWIN_DONT_PARSE_STACK)
118     ABORT("Darwin task-threads-based stop and push unsupported");
119 # else
120 #   ifndef GC_ALWAYS_MULTITHREADED
121       GC_ASSERT(!GC_need_to_lock);
122 #   endif
123 #   ifndef GC_DISCOVER_TASK_THREADS
124       GC_query_task_threads = TRUE;
125 #   endif
126     GC_init_parallel(); /* just to be consistent with Win32 one */
127 # endif
128 }
129
130 #ifndef kCFCoreFoundationVersionNumber_iOS_8_0
131 # define kCFCoreFoundationVersionNumber_iOS_8_0 1140.1
132 #endif
133
134 /* Evaluates the stack range for a given thread.  Returns the lower     */
135 /* bound and sets *phi to the upper one.                                */
136 STATIC ptr_t GC_stack_range_for(ptr_t *phi, thread_act_t thread, GC_thread p,
137                                 GC_bool thread_blocked, mach_port_t my_thread,
138                                 ptr_t *paltstack_lo,
139                                 ptr_t *paltstack_hi GC_ATTR_UNUSED)
140 {
141   ptr_t lo;
142   if (thread == my_thread) {
143     GC_ASSERT(!thread_blocked);
144     lo = GC_approx_sp();
145 #   ifndef DARWIN_DONT_PARSE_STACK
146       *phi = GC_FindTopOfStack(0);
147 #   endif
148
149   } else if (thread_blocked) {
150 #   if defined(CPPCHECK)
151       if (NULL == p) ABORT("Invalid GC_thread passed to GC_stack_range_for");
152 #   endif
153     lo = p->stop_info.stack_ptr;
154 #   ifndef DARWIN_DONT_PARSE_STACK
155       *phi = p->topOfStack;
156 #   endif
157
158   } else {
159     /* MACHINE_THREAD_STATE_COUNT does not seem to be defined       */
160     /* everywhere.  Hence we use our own version.  Alternatively,   */
161     /* we could use THREAD_STATE_MAX (but seems to be not optimal). */
162     kern_return_t kern_result;
163     GC_THREAD_STATE_T state;
164
165 #   if defined(ARM32) && defined(ARM_THREAD_STATE32)
166       /* Use ARM_UNIFIED_THREAD_STATE on iOS8+ 32-bit targets and on    */
167       /* 64-bit H/W (iOS7+ 32-bit mode).                                */
168       size_t size;
169       static cpu_type_t cputype = 0;
170
171       if (cputype == 0) {
172         sysctlbyname("hw.cputype", &cputype, &size, NULL, 0);
173       }
174       if (cputype == CPU_TYPE_ARM64
175           || kCFCoreFoundationVersionNumber
176              >= kCFCoreFoundationVersionNumber_iOS_8_0) {
177         arm_unified_thread_state_t unified_state;
178         mach_msg_type_number_t unified_thread_state_count
179                                         = ARM_UNIFIED_THREAD_STATE_COUNT;
180 #       if defined(CPPCHECK)
181 #         define GC_ARM_UNIFIED_THREAD_STATE 1
182 #       else
183 #         define GC_ARM_UNIFIED_THREAD_STATE ARM_UNIFIED_THREAD_STATE
184 #       endif
185         kern_result = thread_get_state(thread, GC_ARM_UNIFIED_THREAD_STATE,
186                                        (natural_t *)&unified_state,
187                                        &unified_thread_state_count);
188 #       if !defined(CPPCHECK)
189           if (unified_state.ash.flavor != ARM_THREAD_STATE32) {
190             ABORT("unified_state flavor should be ARM_THREAD_STATE32");
191           }
192 #       endif
193         state = unified_state;
194       } else
195 #   endif
196     /* else */ {
197       mach_msg_type_number_t thread_state_count = GC_MACH_THREAD_STATE_COUNT;
198
199       /* Get the thread state (registers, etc) */
200       kern_result = thread_get_state(thread, GC_MACH_THREAD_STATE,
201                                      (natural_t *)&state,
202                                      &thread_state_count);
203     }
204 #   ifdef DEBUG_THREADS
205       GC_log_printf("thread_get_state returns value = %d\n", kern_result);
206 #   endif
207     if (kern_result != KERN_SUCCESS)
208       ABORT("thread_get_state failed");
209
210 #   if defined(I386)
211       lo = (ptr_t)state.THREAD_FLD(esp);
212 #     ifndef DARWIN_DONT_PARSE_STACK
213         *phi = GC_FindTopOfStack(state.THREAD_FLD(esp));
214 #     endif
215       GC_push_one(state.THREAD_FLD(eax));
216       GC_push_one(state.THREAD_FLD(ebx));
217       GC_push_one(state.THREAD_FLD(ecx));
218       GC_push_one(state.THREAD_FLD(edx));
219       GC_push_one(state.THREAD_FLD(edi));
220       GC_push_one(state.THREAD_FLD(esi));
221       GC_push_one(state.THREAD_FLD(ebp));
222
223 #   elif defined(X86_64)
224       lo = (ptr_t)state.THREAD_FLD(rsp);
225 #     ifndef DARWIN_DONT_PARSE_STACK
226         *phi = GC_FindTopOfStack(state.THREAD_FLD(rsp));
227 #     endif
228       GC_push_one(state.THREAD_FLD(rax));
229       GC_push_one(state.THREAD_FLD(rbx));
230       GC_push_one(state.THREAD_FLD(rcx));
231       GC_push_one(state.THREAD_FLD(rdx));
232       GC_push_one(state.THREAD_FLD(rdi));
233       GC_push_one(state.THREAD_FLD(rsi));
234       GC_push_one(state.THREAD_FLD(rbp));
235       /* GC_push_one(state.THREAD_FLD(rsp)); */
236       GC_push_one(state.THREAD_FLD(r8));
237       GC_push_one(state.THREAD_FLD(r9));
238       GC_push_one(state.THREAD_FLD(r10));
239       GC_push_one(state.THREAD_FLD(r11));
240       GC_push_one(state.THREAD_FLD(r12));
241       GC_push_one(state.THREAD_FLD(r13));
242       GC_push_one(state.THREAD_FLD(r14));
243       GC_push_one(state.THREAD_FLD(r15));
244
245 #   elif defined(POWERPC)
246       lo = (ptr_t)(state.THREAD_FLD(r1) - PPC_RED_ZONE_SIZE);
247 #     ifndef DARWIN_DONT_PARSE_STACK
248         *phi = GC_FindTopOfStack(state.THREAD_FLD(r1));
249 #     endif
250       GC_push_one(state.THREAD_FLD(r0));
251       GC_push_one(state.THREAD_FLD(r2));
252       GC_push_one(state.THREAD_FLD(r3));
253       GC_push_one(state.THREAD_FLD(r4));
254       GC_push_one(state.THREAD_FLD(r5));
255       GC_push_one(state.THREAD_FLD(r6));
256       GC_push_one(state.THREAD_FLD(r7));
257       GC_push_one(state.THREAD_FLD(r8));
258       GC_push_one(state.THREAD_FLD(r9));
259       GC_push_one(state.THREAD_FLD(r10));
260       GC_push_one(state.THREAD_FLD(r11));
261       GC_push_one(state.THREAD_FLD(r12));
262       GC_push_one(state.THREAD_FLD(r13));
263       GC_push_one(state.THREAD_FLD(r14));
264       GC_push_one(state.THREAD_FLD(r15));
265       GC_push_one(state.THREAD_FLD(r16));
266       GC_push_one(state.THREAD_FLD(r17));
267       GC_push_one(state.THREAD_FLD(r18));
268       GC_push_one(state.THREAD_FLD(r19));
269       GC_push_one(state.THREAD_FLD(r20));
270       GC_push_one(state.THREAD_FLD(r21));
271       GC_push_one(state.THREAD_FLD(r22));
272       GC_push_one(state.THREAD_FLD(r23));
273       GC_push_one(state.THREAD_FLD(r24));
274       GC_push_one(state.THREAD_FLD(r25));
275       GC_push_one(state.THREAD_FLD(r26));
276       GC_push_one(state.THREAD_FLD(r27));
277       GC_push_one(state.THREAD_FLD(r28));
278       GC_push_one(state.THREAD_FLD(r29));
279       GC_push_one(state.THREAD_FLD(r30));
280       GC_push_one(state.THREAD_FLD(r31));
281
282 #   elif defined(ARM32)
283       lo = (ptr_t)state.THREAD_FLD(sp);
284 #     ifndef DARWIN_DONT_PARSE_STACK
285         *phi = GC_FindTopOfStack(state.THREAD_FLD(r[7])); /* fp */
286 #     endif
287       {
288         int j;
289         for (j = 0; j < 7; j++)
290           GC_push_one(state.THREAD_FLD(r[j]));
291         j++; /* "r7" is skipped (iOS uses it as a frame pointer) */
292         for (; j <= 12; j++)
293           GC_push_one(state.THREAD_FLD(r[j]));
294       }
295       /* "cpsr", "pc" and "sp" are skipped */
296       GC_push_one(state.THREAD_FLD(lr));
297
298 #   elif defined(AARCH64)
299       lo = (ptr_t)state.THREAD_FLD(sp);
300 #     ifndef DARWIN_DONT_PARSE_STACK
301         *phi = GC_FindTopOfStack(state.THREAD_FLD(fp));
302 #     endif
303       {
304         int j;
305         for (j = 0; j <= 28; j++) {
306           GC_push_one(state.THREAD_FLD(x[j]));
307         }
308       }
309       /* "cpsr", "fp", "pc" and "sp" are skipped */
310       GC_push_one(state.THREAD_FLD(lr));
311
312 #   elif defined(CPPCHECK)
313       lo = NULL;
314 #   else
315 #     error FIXME for non-arm/ppc/x86 architectures
316 #   endif
317   } /* thread != my_thread */
318
319 # ifdef DARWIN_DONT_PARSE_STACK
320     /* p is guaranteed to be non-NULL regardless of GC_query_task_threads. */
321     *phi = (p->flags & MAIN_THREAD) != 0 ? GC_stackbottom : p->stack_end;
322 # endif
323
324   /* TODO: Determine p and handle altstack if !DARWIN_DONT_PARSE_STACK */
325 # ifdef DARWIN_DONT_PARSE_STACK
326   if (p->altstack != NULL && (word)p->altstack <= (word)lo
327       && (word)lo <= (word)p->altstack + p->altstack_size) {
328     *paltstack_lo = lo;
329     *paltstack_hi = p->altstack + p->altstack_size;
330     lo = p->stack;
331     *phi = p->stack + p->stack_size;
332   } else
333 # endif
334   /* else */ {
335     *paltstack_lo = NULL;
336   }
337 # ifdef DEBUG_THREADS
338     GC_log_printf("Darwin: Stack for thread %p = [%p,%p)\n",
339                   (void *)(word)thread, (void *)lo, (void *)(*phi));
340 # endif
341   return lo;
342 }
343
344 GC_INNER void GC_push_all_stacks(void)
345 {
346   ptr_t hi, altstack_lo, altstack_hi;
347   task_t my_task = current_task();
348   mach_port_t my_thread = mach_thread_self();
349   GC_bool found_me = FALSE;
350   int nthreads = 0;
351   word total_size = 0;
352   mach_msg_type_number_t listcount = (mach_msg_type_number_t)THREAD_TABLE_SZ;
353   if (!EXPECT(GC_thr_initialized, TRUE))
354     GC_thr_init();
355
356 # ifndef DARWIN_DONT_PARSE_STACK
357     if (GC_query_task_threads) {
358       int i;
359       kern_return_t kern_result;
360       thread_act_array_t act_list = 0;
361
362       /* Obtain the list of the threads from the kernel.  */
363       kern_result = task_threads(my_task, &act_list, &listcount);
364       if (kern_result != KERN_SUCCESS)
365         ABORT("task_threads failed");
366
367       for (i = 0; i < (int)listcount; i++) {
368         thread_act_t thread = act_list[i];
369         ptr_t lo = GC_stack_range_for(&hi, thread, NULL, FALSE, my_thread,
370                                       &altstack_lo, &altstack_hi);
371
372         if (lo) {
373           GC_ASSERT((word)lo <= (word)hi);
374           total_size += hi - lo;
375           GC_push_all_stack(lo, hi);
376         }
377         /* TODO: Handle altstack */
378         nthreads++;
379         if (thread == my_thread)
380           found_me = TRUE;
381         mach_port_deallocate(my_task, thread);
382       } /* for (i=0; ...) */
383
384       vm_deallocate(my_task, (vm_address_t)act_list,
385                     sizeof(thread_t) * listcount);
386     } else
387 # endif /* !DARWIN_DONT_PARSE_STACK */
388   /* else */ {
389     int i;
390
391     for (i = 0; i < (int)listcount; i++) {
392       GC_thread p;
393
394       for (p = GC_threads[i]; p != NULL; p = p->next)
395         if ((p->flags & FINISHED) == 0) {
396           thread_act_t thread = (thread_act_t)p->stop_info.mach_thread;
397           ptr_t lo = GC_stack_range_for(&hi, thread, p,
398                                         (GC_bool)p->thread_blocked,
399                                         my_thread, &altstack_lo,
400                                         &altstack_hi);
401
402           if (lo) {
403             GC_ASSERT((word)lo <= (word)hi);
404             total_size += hi - lo;
405             GC_push_all_stack_sections(lo, hi, p->traced_stack_sect);
406           }
407           if (altstack_lo) {
408             total_size += altstack_hi - altstack_lo;
409             GC_push_all_stack(altstack_lo, altstack_hi);
410           }
411           nthreads++;
412           if (thread == my_thread)
413             found_me = TRUE;
414         }
415     } /* for (i=0; ...) */
416   }
417
418   mach_port_deallocate(my_task, my_thread);
419   GC_VERBOSE_LOG_PRINTF("Pushed %d thread stacks\n", nthreads);
420   if (!found_me && !GC_in_thread_creation)
421     ABORT("Collecting from unknown thread");
422   GC_total_stacksize = total_size;
423 }
424
425 #ifndef GC_NO_THREADS_DISCOVERY
426
427 # ifdef MPROTECT_VDB
428     STATIC mach_port_t GC_mach_handler_thread = 0;
429     STATIC GC_bool GC_use_mach_handler_thread = FALSE;
430
431     GC_INNER void GC_darwin_register_mach_handler_thread(mach_port_t thread)
432     {
433       GC_mach_handler_thread = thread;
434       GC_use_mach_handler_thread = TRUE;
435     }
436 # endif /* MPROTECT_VDB */
437
438 # ifndef GC_MAX_MACH_THREADS
439 #   define GC_MAX_MACH_THREADS THREAD_TABLE_SZ
440 # endif
441
442   struct GC_mach_thread {
443     thread_act_t thread;
444     GC_bool suspended;
445   };
446
447   struct GC_mach_thread GC_mach_threads[GC_MAX_MACH_THREADS];
448   STATIC int GC_mach_threads_count = 0;
449   /* FIXME: it is better to implement GC_mach_threads as a hash set.  */
450
451 /* returns true if there's a thread in act_list that wasn't in old_list */
452 STATIC GC_bool GC_suspend_thread_list(thread_act_array_t act_list, int count,
453                                       thread_act_array_t old_list,
454                                       int old_count, task_t my_task,
455                                       mach_port_t my_thread)
456 {
457   int i;
458   int j = -1;
459   GC_bool changed = FALSE;
460
461   for (i = 0; i < count; i++) {
462     thread_act_t thread = act_list[i];
463     GC_bool found;
464     kern_return_t kern_result;
465
466     if (thread == my_thread
467 #       ifdef MPROTECT_VDB
468           || (GC_mach_handler_thread == thread && GC_use_mach_handler_thread)
469 #       endif
470 #       ifdef PARALLEL_MARK
471           || GC_is_mach_marker(thread) /* ignore the parallel markers */
472 #       endif
473         ) {
474       /* Do not add our one, parallel marker and the handler threads;   */
475       /* consider it as found (e.g., it was processed earlier).         */
476       mach_port_deallocate(my_task, thread);
477       continue;
478     }
479
480     /* find the current thread in the old list */
481     found = FALSE;
482     {
483       int last_found = j; /* remember the previous found thread index */
484
485       /* Search for the thread starting from the last found one first.  */
486       while (++j < old_count)
487         if (old_list[j] == thread) {
488           found = TRUE;
489           break;
490         }
491       if (!found) {
492         /* If not found, search in the rest (beginning) of the list.    */
493         for (j = 0; j < last_found; j++)
494           if (old_list[j] == thread) {
495             found = TRUE;
496             break;
497           }
498       }
499     }
500
501     if (found) {
502       /* It is already in the list, skip processing, release mach port. */
503       mach_port_deallocate(my_task, thread);
504       continue;
505     }
506
507     /* add it to the GC_mach_threads list */
508     if (GC_mach_threads_count == GC_MAX_MACH_THREADS)
509       ABORT("Too many threads");
510     GC_mach_threads[GC_mach_threads_count].thread = thread;
511     /* default is not suspended */
512     GC_mach_threads[GC_mach_threads_count].suspended = FALSE;
513     changed = TRUE;
514
515 #   ifdef DEBUG_THREADS
516       GC_log_printf("Suspending %p\n", (void *)(word)thread);
517 #   endif
518     /* Unconditionally suspend the thread.  It will do no     */
519     /* harm if it is already suspended by the client logic.   */
520     GC_acquire_dirty_lock();
521     do {
522       kern_result = thread_suspend(thread);
523     } while (kern_result == KERN_ABORTED);
524     GC_release_dirty_lock();
525     if (kern_result != KERN_SUCCESS) {
526       /* The thread may have quit since the thread_threads() call we  */
527       /* mark already suspended so it's not dealt with anymore later. */
528       GC_mach_threads[GC_mach_threads_count].suspended = FALSE;
529     } else {
530       /* Mark the thread as suspended and require resume.     */
531       GC_mach_threads[GC_mach_threads_count].suspended = TRUE;
532       if (GC_on_thread_event)
533         GC_on_thread_event(GC_EVENT_THREAD_SUSPENDED, (void *)(word)thread);
534     }
535     GC_mach_threads_count++;
536   }
537   return changed;
538 }
539
540 #endif /* !GC_NO_THREADS_DISCOVERY */
541
542 /* Caller holds allocation lock.        */
543 GC_INNER void GC_stop_world(void)
544 {
545   task_t my_task = current_task();
546   mach_port_t my_thread = mach_thread_self();
547   kern_return_t kern_result;
548
549 # ifdef DEBUG_THREADS
550     GC_log_printf("Stopping the world from thread %p\n",
551                   (void *)(word)my_thread);
552 # endif
553 # ifdef PARALLEL_MARK
554     if (GC_parallel) {
555       /* Make sure all free list construction has stopped before we     */
556       /* start.  No new construction can start, since free list         */
557       /* construction is required to acquire and release the GC lock    */
558       /* before it starts, and we have the lock.                        */
559       GC_acquire_mark_lock();
560       GC_ASSERT(GC_fl_builder_count == 0);
561       /* We should have previously waited for it to become zero. */
562     }
563 # endif /* PARALLEL_MARK */
564
565   if (GC_query_task_threads) {
566 #   ifndef GC_NO_THREADS_DISCOVERY
567       GC_bool changed;
568       thread_act_array_t act_list, prev_list;
569       mach_msg_type_number_t listcount, prevcount;
570
571       /* Clear out the mach threads list table.  We do not need to      */
572       /* really clear GC_mach_threads[] as it is used only in the range */
573       /* from 0 to GC_mach_threads_count-1, inclusive.                  */
574       GC_mach_threads_count = 0;
575
576       /* Loop stopping threads until you have gone over the whole list  */
577       /* twice without a new one appearing.  thread_create() won't      */
578       /* return (and thus the thread stop) until the new thread exists, */
579       /* so there is no window whereby you could stop a thread,         */
580       /* recognize it is stopped, but then have a new thread it created */
581       /* before stopping show up later.                                 */
582       changed = TRUE;
583       prev_list = NULL;
584       prevcount = 0;
585       do {
586         kern_result = task_threads(my_task, &act_list, &listcount);
587
588         if (kern_result == KERN_SUCCESS) {
589           changed = GC_suspend_thread_list(act_list, listcount, prev_list,
590                                            prevcount, my_task, my_thread);
591
592           if (prev_list != NULL) {
593             /* Thread ports are not deallocated by list, unused ports   */
594             /* deallocated in GC_suspend_thread_list, used - kept in    */
595             /* GC_mach_threads till GC_start_world as otherwise thread  */
596             /* object change can occur and GC_start_world will not      */
597             /* find the thread to resume which will cause app to hang.  */
598             vm_deallocate(my_task, (vm_address_t)prev_list,
599                           sizeof(thread_t) * prevcount);
600           }
601
602           /* Repeat while having changes. */
603           prev_list = act_list;
604           prevcount = listcount;
605         }
606       } while (changed);
607
608       GC_ASSERT(prev_list != 0);
609       /* The thread ports are not deallocated by list, see above.       */
610       vm_deallocate(my_task, (vm_address_t)act_list,
611                     sizeof(thread_t) * listcount);
612 #   endif /* !GC_NO_THREADS_DISCOVERY */
613
614   } else {
615     unsigned i;
616
617     for (i = 0; i < THREAD_TABLE_SZ; i++) {
618       GC_thread p;
619
620       for (p = GC_threads[i]; p != NULL; p = p->next) {
621         if ((p->flags & FINISHED) == 0 && !p->thread_blocked &&
622              p->stop_info.mach_thread != my_thread) {
623           GC_acquire_dirty_lock();
624           do {
625             kern_result = thread_suspend(p->stop_info.mach_thread);
626           } while (kern_result == KERN_ABORTED);
627           GC_release_dirty_lock();
628           if (kern_result != KERN_SUCCESS)
629             ABORT("thread_suspend failed");
630           if (GC_on_thread_event)
631             GC_on_thread_event(GC_EVENT_THREAD_SUSPENDED,
632                                (void *)(word)p->stop_info.mach_thread);
633         }
634       }
635     }
636   }
637
638 # ifdef MPROTECT_VDB
639     if (GC_auto_incremental) {
640       GC_mprotect_stop();
641     }
642 # endif
643 # ifdef PARALLEL_MARK
644     if (GC_parallel)
645       GC_release_mark_lock();
646 # endif
647
648 # ifdef DEBUG_THREADS
649     GC_log_printf("World stopped from %p\n", (void *)(word)my_thread);
650 # endif
651   mach_port_deallocate(my_task, my_thread);
652 }
653
654 GC_INLINE void GC_thread_resume(thread_act_t thread)
655 {
656   kern_return_t kern_result;
657 # if defined(DEBUG_THREADS) || defined(GC_ASSERTIONS)
658     struct thread_basic_info info;
659     mach_msg_type_number_t outCount = THREAD_BASIC_INFO_COUNT;
660
661 #   if defined(CPPCHECK) && defined(DEBUG_THREADS)
662       info.run_state = 0;
663 #   endif
664     kern_result = thread_info(thread, THREAD_BASIC_INFO,
665                               (thread_info_t)&info, &outCount);
666     if (kern_result != KERN_SUCCESS)
667       ABORT("thread_info failed");
668 # endif
669 # ifdef DEBUG_THREADS
670     GC_log_printf("Resuming thread %p with state %d\n", (void *)(word)thread,
671                   info.run_state);
672 # endif
673   /* Resume the thread */
674   kern_result = thread_resume(thread);
675   if (kern_result != KERN_SUCCESS) {
676     WARN("thread_resume(%p) failed: mach port invalid\n", thread);
677   } else if (GC_on_thread_event) {
678     GC_on_thread_event(GC_EVENT_THREAD_UNSUSPENDED, (void *)(word)thread);
679   }
680 }
681
682 /* Caller holds allocation lock, and has held it continuously since     */
683 /* the world stopped.                                                   */
684 GC_INNER void GC_start_world(void)
685 {
686   task_t my_task = current_task();
687 # ifdef DEBUG_THREADS
688     GC_log_printf("World starting\n");
689 # endif
690 # ifdef MPROTECT_VDB
691     if (GC_auto_incremental) {
692       GC_mprotect_resume();
693     }
694 # endif
695
696   if (GC_query_task_threads) {
697 #   ifndef GC_NO_THREADS_DISCOVERY
698       int i, j;
699       kern_return_t kern_result;
700       thread_act_array_t act_list;
701       mach_msg_type_number_t listcount;
702
703       kern_result = task_threads(my_task, &act_list, &listcount);
704       if (kern_result != KERN_SUCCESS)
705         ABORT("task_threads failed");
706
707       j = (int)listcount;
708       for (i = 0; i < GC_mach_threads_count; i++) {
709         thread_act_t thread = GC_mach_threads[i].thread;
710
711         if (GC_mach_threads[i].suspended) {
712           int last_found = j;   /* The thread index found during the    */
713                                 /* previous iteration (count value      */
714                                 /* means no thread found yet).          */
715
716           /* Search for the thread starting from the last found one first. */
717           while (++j < (int)listcount) {
718             if (act_list[j] == thread)
719               break;
720           }
721           if (j >= (int)listcount) {
722             /* If not found, search in the rest (beginning) of the list. */
723             for (j = 0; j < last_found; j++) {
724               if (act_list[j] == thread)
725                 break;
726             }
727           }
728           if (j != last_found) {
729             /* The thread is alive, resume it.  */
730             GC_thread_resume(thread);
731           }
732         } else {
733           /* This thread was failed to be suspended by GC_stop_world,   */
734           /* no action needed.                                          */
735 #         ifdef DEBUG_THREADS
736             GC_log_printf("Not resuming thread %p as it is not suspended\n",
737                           (void *)(word)thread);
738 #         endif
739         }
740         mach_port_deallocate(my_task, thread);
741       }
742
743       for (i = 0; i < (int)listcount; i++)
744         mach_port_deallocate(my_task, act_list[i]);
745       vm_deallocate(my_task, (vm_address_t)act_list,
746                     sizeof(thread_t) * listcount);
747 #   endif /* !GC_NO_THREADS_DISCOVERY */
748
749   } else {
750     int i;
751     mach_port_t my_thread = mach_thread_self();
752
753     for (i = 0; i < THREAD_TABLE_SZ; i++) {
754       GC_thread p;
755       for (p = GC_threads[i]; p != NULL; p = p->next) {
756         if ((p->flags & FINISHED) == 0 && !p->thread_blocked &&
757              p->stop_info.mach_thread != my_thread)
758           GC_thread_resume(p->stop_info.mach_thread);
759       }
760     }
761
762     mach_port_deallocate(my_task, my_thread);
763   }
764
765 # ifdef DEBUG_THREADS
766     GC_log_printf("World started\n");
767 # endif
768 }
769
770 #endif /* GC_DARWIN_THREADS */