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