1 #define PERL_NO_GET_CONTEXT
2 /* Workaround for mingw 32-bit compiler by mingw-w64.sf.net - has to come before any #include.
3  * It also defines USE_NO_MINGW_SETJMP_TWO_ARGS for the mingw.org 32-bit compilers ... but
4  * that's ok as that compiler makes no use of that symbol anyway */
5 #if defined(WIN32) && defined(__MINGW32__) && !defined(__MINGW64__)
6 #  define USE_NO_MINGW_SETJMP_TWO_ARGS 1
7 #endif
8 #include "EXTERN.h"
9 #include "perl.h"
10 #include "XSUB.h"
11 /* Workaround for XSUB.h bug under WIN32 */
12 #ifdef WIN32
13 #  undef setjmp
14 #  if defined(USE_NO_MINGW_SETJMP_TWO_ARGS) || (!defined(__BORLANDC__) && !defined(__MINGW64__))
15 #    define setjmp(x) _setjmp(x)
16 #  endif
17 #  if defined(__MINGW64__)
18 #    define setjmp(x) _setjmpex((x), mingw_getsp())
19 #  endif
20 #endif
21 #ifdef HAS_PPPORT_H
22 #  define NEED_PL_signals
23 #  define NEED_sv_2pv_flags
24 #  include "ppport.h"
25 #  include "threads.h"
26 #endif
27 #ifndef sv_dup_inc
28 #  define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
29 #endif
30 #ifndef PERL_UNUSED_RESULT
31 #  if defined(__GNUC__) && defined(HASATTRIBUTE_WARN_UNUSED_RESULT)
32 #    define PERL_UNUSED_RESULT(v) STMT_START { __typeof__(v) z = (v); (void)sizeof(z); } STMT_END
33 #  else
34 #    define PERL_UNUSED_RESULT(v) ((void)(v))
35 #  endif
36 #endif
37 
38 #ifndef CLANG_DIAG_IGNORE
39 # define CLANG_DIAG_IGNORE(x)
40 # define CLANG_DIAG_RESTORE
41 #endif
42 #ifndef CLANG_DIAG_IGNORE_STMT
43 # define CLANG_DIAG_IGNORE_STMT(x) CLANG_DIAG_IGNORE(x) NOOP
44 # define CLANG_DIAG_RESTORE_STMT CLANG_DIAG_RESTORE NOOP
45 # define CLANG_DIAG_IGNORE_DECL(x) CLANG_DIAG_IGNORE(x) dNOOP
46 # define CLANG_DIAG_RESTORE_DECL CLANG_DIAG_RESTORE dNOOP
47 #endif
48 
49 #ifdef USE_ITHREADS
50 
51 #ifdef __amigaos4__
52 #  undef YIELD
53 #  define YIELD sleep(0)
54 #endif
55 #ifdef WIN32
56 #  include <windows.h>
57    /* Supposed to be in Winbase.h */
58 #  ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
59 #    define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
60 #  endif
61 #  include <win32thread.h>
62 #else
63 #  ifdef OS2
64 typedef perl_os_thread pthread_t;
65 #  else
66 #    include <pthread.h>
67 #  endif
68 #  include <thread.h>
69 #  define PERL_THREAD_SETSPECIFIC(k,v) pthread_setspecific(k,v)
70 #  ifdef OLD_PTHREADS_API
71 #    define PERL_THREAD_DETACH(t) pthread_detach(&(t))
72 #  else
73 #    define PERL_THREAD_DETACH(t) pthread_detach((t))
74 #  endif
75 #endif
76 #if !defined(HAS_GETPAGESIZE) && defined(I_SYS_PARAM)
77 #  include <sys/param.h>
78 #endif
79 
80 /* Values for 'state' member */
81 #define PERL_ITHR_DETACHED           1 /* Thread has been detached */
82 #define PERL_ITHR_JOINED             2 /* Thread is being / has been joined */
83 #define PERL_ITHR_FINISHED           4 /* Thread has finished execution */
84 #define PERL_ITHR_THREAD_EXIT_ONLY   8 /* exit() only exits current thread */
85 #define PERL_ITHR_NONVIABLE         16 /* Thread creation failed */
86 #define PERL_ITHR_DIED              32 /* Thread finished by dying */
87 
88 #define PERL_ITHR_UNCALLABLE  (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)
89 
90 
91 typedef struct _ithread {
92     struct _ithread *next;      /* Next thread in the list */
93     struct _ithread *prev;      /* Prev thread in the list */
94     PerlInterpreter *interp;    /* The threads interpreter */
95     UV tid;                     /* Threads module's thread id */
96     perl_mutex mutex;           /* Mutex for updating things in this struct */
97     int count;                  /* Reference count. See S_ithread_create. */
98     int state;                  /* Detached, joined, finished, etc. */
99     int gimme;                  /* Context of create */
100     SV *init_function;          /* Code to run */
101     AV *params;                 /* Args to pass function */
102 #ifdef WIN32
103     DWORD  thr;                 /* OS's idea if thread id */
104     HANDLE handle;              /* OS's waitable handle */
105 #else
106     pthread_t thr;              /* OS's handle for the thread */
107 #endif
108     IV stack_size;
109     SV *err;                    /* Error from abnormally terminated thread */
110     char *err_class;            /* Error object's classname if applicable */
111 #ifndef WIN32
112     sigset_t initial_sigmask;   /* Thread wakes up with signals blocked */
113 #endif
114 } ithread;
115 
116 
117 #define MY_CXT_KEY "threads::_cxt" XS_VERSION
118 
119 typedef struct {
120     /* Used by Perl interpreter for thread context switching */
121     ithread *context;
122 } my_cxt_t;
123 
124 START_MY_CXT
125 
126 
127 #define MY_POOL_KEY "threads::_pool" XS_VERSION
128 
129 typedef struct {
130     /* Structure for 'main' thread
131      * Also forms the 'base' for the doubly-linked list of threads */
132     ithread main_thread;
133 
134     /* Protects the creation and destruction of threads*/
135     perl_mutex create_destruct_mutex;
136 
137     UV tid_counter;
138     IV joinable_threads;
139     IV running_threads;
140     IV detached_threads;
141     IV total_threads;
142     IV default_stack_size;
143     IV page_size;
144 } my_pool_t;
145 
146 #define dMY_POOL \
147     SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,               \
148                                sizeof(MY_POOL_KEY)-1, TRUE);            \
149     my_pool_t *my_poolp = INT2PTR(my_pool_t*, SvUV(my_pool_sv))
150 
151 #define MY_POOL (*my_poolp)
152 
153 #if defined(WIN32) || (defined(__amigaos4__) && defined(__NEWLIB__))
154 #  undef THREAD_SIGNAL_BLOCKING
155 #else
156 #  define THREAD_SIGNAL_BLOCKING
157 #endif
158 
159 #ifdef THREAD_SIGNAL_BLOCKING
160 
161 /* Block most signals for calling thread, setting the old signal mask to
162  * oldmask, if it is not NULL */
163 STATIC int
S_block_most_signals(sigset_t * oldmask)164 S_block_most_signals(sigset_t *oldmask)
165 {
166     sigset_t newmask;
167 
168     sigfillset(&newmask);
169     /* Don't block certain "important" signals (stolen from mg.c) */
170 #ifdef SIGILL
171     sigdelset(&newmask, SIGILL);
172 #endif
173 #ifdef SIGBUS
174     sigdelset(&newmask, SIGBUS);
175 #endif
176 #ifdef SIGSEGV
177     sigdelset(&newmask, SIGSEGV);
178 #endif
179 
180 #if defined(VMS)
181     /* no per-thread blocking available */
182     return sigprocmask(SIG_BLOCK, &newmask, oldmask);
183 #else
184     return pthread_sigmask(SIG_BLOCK, &newmask, oldmask);
185 #endif /* VMS */
186 }
187 
188 /* Set the signal mask for this thread to newmask */
189 STATIC int
S_set_sigmask(sigset_t * newmask)190 S_set_sigmask(sigset_t *newmask)
191 {
192 #if defined(VMS)
193     return sigprocmask(SIG_SETMASK, newmask, NULL);
194 #else
195     return pthread_sigmask(SIG_SETMASK, newmask, NULL);
196 #endif /* VMS */
197 }
198 #endif /* WIN32 */
199 
200 /* Used by Perl interpreter for thread context switching */
201 STATIC void
S_ithread_set(pTHX_ ithread * thread)202 S_ithread_set(pTHX_ ithread *thread)
203 {
204     dMY_CXT;
205     MY_CXT.context = thread;
206 }
207 
208 STATIC ithread *
S_ithread_get(pTHX)209 S_ithread_get(pTHX)
210 {
211     dMY_CXT;
212     return (MY_CXT.context);
213 }
214 
215 
216 /* Free any data (such as the Perl interpreter) attached to an ithread
217  * structure.  This is a bit like undef on SVs, where the SV isn't freed,
218  * but the PVX is.  Must be called with thread->mutex already locked.  Also,
219  * must be called with MY_POOL.create_destruct_mutex unlocked as destruction
220  * of the interpreter can lead to recursive destruction calls that could
221  * lead to a deadlock on that mutex.
222  */
223 STATIC void
S_ithread_clear(pTHX_ ithread * thread)224 S_ithread_clear(pTHX_ ithread *thread)
225 {
226     PerlInterpreter *interp;
227 #ifndef WIN32
228     sigset_t origmask;
229 #endif
230 
231     assert(((thread->state & PERL_ITHR_FINISHED) &&
232             (thread->state & PERL_ITHR_UNCALLABLE))
233                 ||
234            (thread->state & PERL_ITHR_NONVIABLE));
235 
236 #ifdef THREAD_SIGNAL_BLOCKING
237     /* We temporarily set the interpreter context to the interpreter being
238      * destroyed.  It's in no condition to handle signals while it's being
239      * taken apart.
240      */
241     S_block_most_signals(&origmask);
242 #endif
243 
244     interp = thread->interp;
245     if (interp) {
246         dTHXa(interp);
247 
248         PERL_SET_CONTEXT(interp);
249         S_ithread_set(aTHX_ thread);
250 
251         SvREFCNT_dec(thread->params);
252         thread->params = NULL;
253 
254         if (thread->err) {
255             SvREFCNT_dec(thread->err);
256             thread->err = Nullsv;
257         }
258 
259         perl_destruct(interp);
260         perl_free(interp);
261         thread->interp = NULL;
262     }
263 
264     PERL_SET_CONTEXT(aTHX);
265 #ifdef THREAD_SIGNAL_BLOCKING
266     S_set_sigmask(&origmask);
267 #endif
268 }
269 
270 
271 /* Decrement the refcount of an ithread, and if it reaches zero, free it.
272  * Must be called with the mutex held.
273  * On return, mutex is released (or destroyed).
274  */
275 STATIC void
S_ithread_free(pTHX_ ithread * thread)276 S_ithread_free(pTHX_ ithread *thread)
277   PERL_TSA_RELEASE(thread->mutex)
278 {
279 #ifdef WIN32
280     HANDLE handle;
281 #endif
282     dMY_POOL;
283 
284     if (! (thread->state & PERL_ITHR_NONVIABLE)) {
285         assert(thread->count > 0);
286         if (--thread->count > 0) {
287             MUTEX_UNLOCK(&thread->mutex);
288             return;
289         }
290         assert((thread->state & PERL_ITHR_FINISHED) &&
291                (thread->state & PERL_ITHR_UNCALLABLE));
292     }
293     MUTEX_UNLOCK(&thread->mutex);
294 
295     /* Main thread (0) is immortal and should never get here */
296     assert(thread->tid != 0);
297 
298     /* Remove from circular list of threads */
299     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
300     assert(thread->prev && thread->next);
301     thread->next->prev = thread->prev;
302     thread->prev->next = thread->next;
303     thread->next = NULL;
304     thread->prev = NULL;
305     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
306 
307     /* Thread is now disowned */
308     MUTEX_LOCK(&thread->mutex);
309     S_ithread_clear(aTHX_ thread);
310 
311 #ifdef WIN32
312     handle = thread->handle;
313     thread->handle = NULL;
314 #endif
315     MUTEX_UNLOCK(&thread->mutex);
316     MUTEX_DESTROY(&thread->mutex);
317 
318 #ifdef WIN32
319     if (handle) {
320         CloseHandle(handle);
321     }
322 #endif
323 
324     PerlMemShared_free(thread);
325 
326     /* total_threads >= 1 is used to veto cleanup by the main thread,
327      * should it happen to exit while other threads still exist.
328      * Decrement this as the very last thing in the thread's existence.
329      * Otherwise, MY_POOL and global state such as PL_op_mutex may get
330      * freed while we're still using it.
331      */
332     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
333     MY_POOL.total_threads--;
334     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
335 }
336 
337 
338 static void
S_ithread_count_inc(pTHX_ ithread * thread)339 S_ithread_count_inc(pTHX_ ithread *thread)
340   PERL_TSA_EXCLUDES(thread->mutex)
341 {
342     MUTEX_LOCK(&thread->mutex);
343     thread->count++;
344     MUTEX_UNLOCK(&thread->mutex);
345 }
346 
347 
348 /* Warn if exiting with any unjoined threads */
349 STATIC int
S_exit_warning(pTHX)350 S_exit_warning(pTHX)
351 {
352     int veto_cleanup, warn;
353     dMY_POOL;
354 
355     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
356     veto_cleanup = (MY_POOL.total_threads > 0);
357     warn         = (MY_POOL.running_threads || MY_POOL.joinable_threads);
358     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
359 
360     if (warn) {
361         if (ckWARN_d(WARN_THREADS)) {
362             Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
363                             IVdf " running and unjoined\n\t%"
364                             IVdf " finished and unjoined\n\t%"
365                             IVdf " running and detached\n",
366                             MY_POOL.running_threads,
367                             MY_POOL.joinable_threads,
368                             MY_POOL.detached_threads);
369         }
370     }
371 
372     return (veto_cleanup);
373 }
374 
375 
376 /* Called from perl_destruct() in each thread.  If it's the main thread,
377  * stop it from freeing everything if there are other threads still running.
378  */
379 STATIC int
Perl_ithread_hook(pTHX)380 Perl_ithread_hook(pTHX)
381 {
382     dMY_POOL;
383     return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
384 }
385 
386 
387 /* MAGIC (in mg.h sense) hooks */
388 
389 STATIC int
ithread_mg_get(pTHX_ SV * sv,MAGIC * mg)390 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
391 {
392     ithread *thread = (ithread *)mg->mg_ptr;
393     SvIV_set(sv, PTR2IV(thread));
394     SvIOK_on(sv);
395     return (0);
396 }
397 
398 STATIC int
ithread_mg_free(pTHX_ SV * sv,MAGIC * mg)399 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
400 {
401     ithread *thread = (ithread *)mg->mg_ptr;
402     PERL_UNUSED_ARG(sv);
403     MUTEX_LOCK(&thread->mutex);
404     S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
405     return (0);
406 }
407 
408 STATIC int
ithread_mg_dup(pTHX_ MAGIC * mg,CLONE_PARAMS * param)409 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
410 {
411     PERL_UNUSED_ARG(param);
412     S_ithread_count_inc(aTHX_ (ithread *)mg->mg_ptr);
413     return (0);
414 }
415 
416 STATIC const MGVTBL ithread_vtbl = {
417     ithread_mg_get,     /* get */
418     0,                  /* set */
419     0,                  /* len */
420     0,                  /* clear */
421     ithread_mg_free,    /* free */
422     0,                  /* copy */
423     ithread_mg_dup,     /* dup */
424 #if (PERL_VERSION > 8) || (PERL_VERSION == 8 && PERL_SUBVERSION > 8)
425     0                   /* local */
426 #endif
427 };
428 
429 
430 /* Provided default, minimum and rational stack sizes */
431 STATIC IV
S_good_stack_size(pTHX_ IV stack_size)432 S_good_stack_size(pTHX_ IV stack_size)
433 {
434     dMY_POOL;
435 
436     /* Use default stack size if no stack size specified */
437     if (! stack_size) {
438         return (MY_POOL.default_stack_size);
439     }
440 
441 #ifdef PTHREAD_STACK_MIN
442     /* Can't use less than minimum */
443     if (stack_size < PTHREAD_STACK_MIN) {
444         if (ckWARN(WARN_THREADS)) {
445             Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
446         }
447         return (PTHREAD_STACK_MIN);
448     }
449 #endif
450 
451     /* Round up to page size boundary */
452     if (MY_POOL.page_size <= 0) {
453 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
454         SETERRNO(0, SS_NORMAL);
455 #  ifdef _SC_PAGESIZE
456         MY_POOL.page_size = sysconf(_SC_PAGESIZE);
457 #  else
458         MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
459 #  endif
460         if ((long)MY_POOL.page_size < 0) {
461             if (errno) {
462                 SV * const error = get_sv("@", 0);
463                 (void)SvUPGRADE(error, SVt_PV);
464                 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
465             } else {
466                 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
467             }
468         }
469 #else
470 #  ifdef HAS_GETPAGESIZE
471         MY_POOL.page_size = getpagesize();
472 #  else
473 #    if defined(I_SYS_PARAM) && defined(PAGESIZE)
474         MY_POOL.page_size = PAGESIZE;
475 #    else
476         MY_POOL.page_size = 8192;   /* A conservative default */
477 #    endif
478 #  endif
479         if (MY_POOL.page_size <= 0) {
480             Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
481         }
482 #endif
483     }
484     stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
485 
486     return (stack_size);
487 }
488 
489 
490 /* Run code within a JMPENV environment.
491  * Using a separate function avoids
492  *   "variable 'foo' might be clobbered by 'longjmp'"
493  * warnings.
494  * The three _p vars return values to the caller
495  */
496 static int
S_jmpenv_run(pTHX_ int action,ithread * thread,int * len_p,int * exit_app_p,int * exit_code_p)497 S_jmpenv_run(pTHX_ int action, ithread *thread,
498              int *len_p, int *exit_app_p, int *exit_code_p)
499 {
500     dJMPENV;
501     volatile I32 oldscope = PL_scopestack_ix;
502     int jmp_rc = 0;
503 
504     JMPENV_PUSH(jmp_rc);
505     if (jmp_rc == 0) {
506         if (action == 0) {
507             /* Run the specified function */
508             *len_p = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
509         } else if (action == 1) {
510             /* Warn that thread died */
511             Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
512         } else {
513             /* Warn if there are unjoined threads */
514             S_exit_warning(aTHX);
515         }
516     } else if (jmp_rc == 2) {
517         /* Thread exited */
518         *exit_app_p = 1;
519         *exit_code_p = STATUS_CURRENT;
520         while (PL_scopestack_ix > oldscope) {
521             LEAVE;
522         }
523     }
524     JMPENV_POP;
525     return jmp_rc;
526 }
527 
528 
529 /* Starts executing the thread.
530  * Passed as the C level function to run in the new thread.
531  */
532 #ifdef WIN32
533 STATIC THREAD_RET_TYPE
S_ithread_run(LPVOID arg)534 S_ithread_run(LPVOID arg)
535 #else
536 STATIC void *
537 S_ithread_run(void * arg)
538 #endif
539 {
540     ithread *thread = (ithread *)arg;
541     int exit_app = 0;   /* Thread terminated using 'exit' */
542     int exit_code = 0;
543     int died = 0;       /* Thread terminated abnormally */
544 
545 
546     dTHXa(thread->interp);
547 
548     dMY_POOL;
549 
550     /* The following mutex lock + mutex unlock pair explained.
551      *
552      * parent:
553      * - calls ithread_create (and S_ithread_create), which:
554      *   - creates the new thread
555      *   - does MUTEX_LOCK(&thread->mutex)
556      *   - calls pthread_create(..., S_ithread_run,...)
557      * child:
558      * - starts the S_ithread_run (where we are now), which:
559      *   - tries to MUTEX_LOCK(&thread->mutex)
560      *   - blocks
561      * parent:
562      *   - continues doing more createy stuff
563      *   - does MUTEX_UNLOCK(&thread->mutex)
564      *   - continues
565      * child:
566      *   - finishes MUTEX_LOCK(&thread->mutex)
567      *   - does MUTEX_UNLOCK(&thread->mutex)
568      *   - continues
569      */
570     MUTEX_LOCK(&thread->mutex);
571     MUTEX_UNLOCK(&thread->mutex);
572 
573     PERL_SET_CONTEXT(thread->interp);
574     S_ithread_set(aTHX_ thread);
575 
576 #ifdef THREAD_SIGNAL_BLOCKING
577     /* Thread starts with most signals blocked - restore the signal mask from
578      * the ithread struct.
579      */
580     S_set_sigmask(&thread->initial_sigmask);
581 #endif
582 
583     PL_perl_destruct_level = 2;
584 
585     {
586         AV *params = thread->params;
587         int len = (int)av_len(params)+1;
588         int ii;
589         int jmp_rc;
590 
591         dSP;
592         ENTER;
593         SAVETMPS;
594 
595         /* Put args on the stack */
596         PUSHMARK(SP);
597         for (ii=0; ii < len; ii++) {
598             XPUSHs(av_shift(params));
599         }
600         PUTBACK;
601 
602         jmp_rc = S_jmpenv_run(aTHX_ 0, thread, &len, &exit_app, &exit_code);
603 
604 #ifdef THREAD_SIGNAL_BLOCKING
605         /* The interpreter is finished, so this thread can stop receiving
606          * signals.  This way, our signal handler doesn't get called in the
607          * middle of our parent thread calling perl_destruct()...
608          */
609         S_block_most_signals(NULL);
610 #endif
611 
612         /* Remove args from stack and put back in params array */
613         SPAGAIN;
614         for (ii=len-1; ii >= 0; ii--) {
615             SV *sv = POPs;
616             if (jmp_rc == 0 && (thread->gimme & G_WANT) != G_VOID) {
617                 av_store(params, ii, SvREFCNT_inc(sv));
618             }
619         }
620 
621         FREETMPS;
622         LEAVE;
623 
624         /* Check for abnormal termination */
625         if (SvTRUE(ERRSV)) {
626             died = PERL_ITHR_DIED;
627             thread->err = newSVsv(ERRSV);
628             /* If ERRSV is an object, remember the classname and then
629              * rebless into 'main' so it will survive 'cloning'
630              */
631             if (sv_isobject(thread->err)) {
632                 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
633                 sv_bless(thread->err, gv_stashpv("main", 0));
634             }
635 
636             if (ckWARN_d(WARN_THREADS)) {
637                 (void)S_jmpenv_run(aTHX_ 1, thread, NULL,
638                                             &exit_app, &exit_code);
639             }
640         }
641 
642         /* Release function ref */
643         SvREFCNT_dec(thread->init_function);
644         thread->init_function = Nullsv;
645     }
646 
647     PerlIO_flush((PerlIO *)NULL);
648 
649     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
650     MUTEX_LOCK(&thread->mutex);
651     /* Mark as finished */
652     thread->state |= (PERL_ITHR_FINISHED | died);
653     /* Clear exit flag if required */
654     if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
655         exit_app = 0;
656     }
657 
658     /* Adjust thread status counts */
659     if (thread->state & PERL_ITHR_DETACHED) {
660         MY_POOL.detached_threads--;
661     } else {
662         MY_POOL.running_threads--;
663         MY_POOL.joinable_threads++;
664     }
665     MUTEX_UNLOCK(&thread->mutex);
666     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
667 
668     /* Exit application if required */
669     if (exit_app) {
670         (void)S_jmpenv_run(aTHX_ 2, thread, NULL, &exit_app, &exit_code);
671         my_exit(exit_code);
672     }
673 
674     /* At this point, the interpreter may have been freed, so call
675      * free in the the context of of the 'main' interpreter which
676      * can't have been freed due to the veto_cleanup mechanism.
677      */
678     aTHX = MY_POOL.main_thread.interp;
679 
680     MUTEX_LOCK(&thread->mutex);
681     S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
682 
683 #ifdef WIN32
684     return ((DWORD)0);
685 #else
686     return (0);
687 #endif
688 }
689 
690 
691 /* Type conversion helper functions */
692 
693 STATIC SV *
S_ithread_to_SV(pTHX_ SV * obj,ithread * thread,char * classname,bool inc)694 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
695 {
696     SV *sv;
697     MAGIC *mg;
698 
699     if (inc)
700         S_ithread_count_inc(aTHX_ thread);
701 
702     if (! obj) {
703         obj = newSV(0);
704     }
705 
706     sv = newSVrv(obj, classname);
707     sv_setiv(sv, PTR2IV(thread));
708     mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
709     mg->mg_flags |= MGf_DUP;
710     SvREADONLY_on(sv);
711 
712     return (obj);
713 }
714 
715 STATIC ithread *
S_SV_to_ithread(pTHX_ SV * sv)716 S_SV_to_ithread(pTHX_ SV *sv)
717 {
718     /* Argument is a thread */
719     if (SvROK(sv)) {
720       return (INT2PTR(ithread *, SvIV(SvRV(sv))));
721     }
722     /* Argument is classname, therefore return current thread */
723     return (S_ithread_get(aTHX));
724 }
725 
726 
727 /* threads->create()
728  * Called in context of parent thread.
729  * Called with my_pool->create_destruct_mutex locked.
730  * (Unlocked both on error and on success.)
731  */
732 STATIC ithread *
S_ithread_create(PerlInterpreter * parent_perl,my_pool_t * my_pool,SV * init_function,IV stack_size,int gimme,int exit_opt,int params_start,int num_params)733 S_ithread_create(
734         PerlInterpreter *parent_perl,
735         my_pool_t *my_pool,
736         SV       *init_function,
737         IV        stack_size,
738         int       gimme,
739         int       exit_opt,
740         int       params_start,
741         int       num_params)
742   PERL_TSA_RELEASE(my_pool->create_destruct_mutex)
743 {
744     dTHXa(parent_perl);
745     ithread     *thread;
746     ithread     *current_thread = S_ithread_get(aTHX);
747     AV          *params;
748     SV          **array;
749 
750 #if PERL_VERSION <= 8 && PERL_SUBVERSION <= 7
751     SV         **tmps_tmp = PL_tmps_stack;
752     IV           tmps_ix  = PL_tmps_ix;
753 #endif
754 #ifndef WIN32
755     int          rc_stack_size = 0;
756     int          rc_thread_create = 0;
757 #endif
758 
759     /* Allocate thread structure in context of the main thread's interpreter */
760     {
761         PERL_SET_CONTEXT(my_pool->main_thread.interp);
762         thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
763     }
764     PERL_SET_CONTEXT(aTHX);
765     if (!thread) {
766         /* This lock was acquired in ithread_create()
767          * prior to calling S_ithread_create(). */
768         MUTEX_UNLOCK(&my_pool->create_destruct_mutex);
769         {
770           int fd = PerlIO_fileno(Perl_error_log);
771           if (fd >= 0) {
772             /* If there's no error_log, we cannot scream about it missing. */
773             PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, strlen(PL_no_mem)));
774           }
775         }
776         my_exit(1);
777     }
778     Zero(thread, 1, ithread);
779 
780     /* Add to threads list */
781     thread->next = &my_pool->main_thread;
782     thread->prev = my_pool->main_thread.prev;
783     my_pool->main_thread.prev = thread;
784     thread->prev->next = thread;
785     my_pool->total_threads++;
786 
787     /* 1 ref to be held by the local var 'thread' in S_ithread_run().
788      * 1 ref to be held by the threads object that we assume we will
789      *      be embedded in upon our return.
790      * 1 ref to be the responsibility of join/detach, so we don't get
791      *      freed until join/detach, even if no thread objects remain.
792      *      This allows the following to work:
793      *          { threads->create(sub{...}); } threads->object(1)->join;
794      */
795     thread->count = 3;
796 
797     /* Block new thread until ->create() call finishes */
798     MUTEX_INIT(&thread->mutex);
799     MUTEX_LOCK(&thread->mutex); /* See S_ithread_run() for more detail. */
800 
801     thread->tid = my_pool->tid_counter++;
802     thread->stack_size = S_good_stack_size(aTHX_ stack_size);
803     thread->gimme = gimme;
804     thread->state = exit_opt;
805 
806     /* "Clone" our interpreter into the thread's interpreter.
807      * This gives thread access to "static data" and code.
808      */
809     PerlIO_flush((PerlIO *)NULL);
810     S_ithread_set(aTHX_ thread);
811 
812     SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
813     PL_srand_called = FALSE;   /* Set it to false so we can detect if it gets
814                                   set during the clone */
815 
816 #ifdef THREAD_SIGNAL_BLOCKING
817     /* perl_clone() will leave us the new interpreter's context.  This poses
818      * two problems for our signal handler.  First, it sets the new context
819      * before the new interpreter struct is fully initialized, so our signal
820      * handler might find bogus data in the interpreter struct it gets.
821      * Second, even if the interpreter is initialized before a signal comes in,
822      * we would like to avoid that interpreter receiving notifications for
823      * signals (especially when they ought to be for the one running in this
824      * thread), until it is running in its own thread.  Another problem is that
825      * the new thread will not have set the context until some time after it
826      * has started, so it won't be safe for our signal handler to run until
827      * that time.
828      *
829      * So we block most signals here, so the new thread will inherit the signal
830      * mask, and unblock them right after the thread creation.  The original
831      * mask is saved in the thread struct so that the new thread can restore
832      * the original mask.
833      */
834     S_block_most_signals(&thread->initial_sigmask);
835 #endif
836 
837 #ifdef WIN32
838     thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
839 #else
840     thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
841 #endif
842 
843     /* perl_clone() leaves us in new interpreter's context.  As it is tricky
844      * to spot an implicit aTHX, create a new scope with aTHX matching the
845      * context for the duration of our work for new interpreter.
846      */
847     {
848 #if (PERL_VERSION > 13) || (PERL_VERSION == 13 && PERL_SUBVERSION > 1)
849         CLONE_PARAMS *clone_param = Perl_clone_params_new(aTHX, thread->interp);
850 #else
851         CLONE_PARAMS clone_param_s;
852         CLONE_PARAMS *clone_param = &clone_param_s;
853 #endif
854         dTHXa(thread->interp);
855 
856         MY_CXT_CLONE;
857 
858 #if (PERL_VERSION < 13) || (PERL_VERSION == 13 && PERL_SUBVERSION <= 1)
859         clone_param->flags = 0;
860 #endif
861 
862         /* Here we remove END blocks since they should only run in the thread
863          * they are created
864          */
865         SvREFCNT_dec(PL_endav);
866         PL_endav = NULL;
867 
868         if (SvPOK(init_function)) {
869             thread->init_function = newSV(0);
870             sv_copypv(thread->init_function, init_function);
871         } else {
872             thread->init_function = sv_dup_inc(init_function, clone_param);
873         }
874 
875         thread->params = params = newAV();
876         av_extend(params, num_params - 1);
877         AvFILLp(params) = num_params - 1;
878         array = AvARRAY(params);
879 
880         /* params_start is an offset onto the Perl stack. This can be
881            reallocated (and hence move) as a side effect of calls to
882            perl_clone() and sv_dup_inc(). Hence copy the parameters
883            somewhere under our control first, before duplicating.  */
884         if (num_params) {
885 #if (PERL_VERSION > 8)
886             Copy(parent_perl->Istack_base + params_start, array, num_params, SV *);
887 #else
888             Copy(parent_perl->Tstack_base + params_start, array, num_params, SV *);
889 #endif
890             while (num_params--) {
891                 *array = sv_dup_inc(*array, clone_param);
892                 ++array;
893             }
894         }
895 
896 #if (PERL_VERSION > 13) || (PERL_VERSION == 13 && PERL_SUBVERSION > 1)
897         Perl_clone_params_del(clone_param);
898 #endif
899 
900 #if PERL_VERSION <= 8 && PERL_SUBVERSION <= 7
901         /* The code below checks that anything living on the tmps stack and
902          * has been cloned (so it lives in the ptr_table) has a refcount
903          * higher than 0.
904          *
905          * If the refcount is 0 it means that a something on the stack/context
906          * was holding a reference to it and since we init_stacks() in
907          * perl_clone that won't get cleaned and we will get a leaked scalar.
908          * The reason it was cloned was that it lived on the @_ stack.
909          *
910          * Example of this can be found in bugreport 15837 where calls in the
911          * parameter list end up as a temp.
912          *
913          * As of 5.8.8 this is done in perl_clone.
914          */
915         while (tmps_ix > 0) {
916             SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
917             tmps_ix--;
918             if (sv && SvREFCNT(sv) == 0) {
919                 SvREFCNT_inc_void(sv);
920                 SvREFCNT_dec(sv);
921             }
922         }
923 #endif
924 
925         SvTEMP_off(thread->init_function);
926         ptr_table_free(PL_ptr_table);
927         PL_ptr_table = NULL;
928         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
929     }
930     S_ithread_set(aTHX_ current_thread);
931     PERL_SET_CONTEXT(aTHX);
932 
933     /* Create/start the thread */
934 #ifdef WIN32
935     thread->handle = CreateThread(NULL,
936                                   (DWORD)thread->stack_size,
937                                   S_ithread_run,
938                                   (LPVOID)thread,
939                                   STACK_SIZE_PARAM_IS_A_RESERVATION,
940                                   &thread->thr);
941 #else
942     {
943         STATIC pthread_attr_t attr;
944         STATIC int attr_inited = 0;
945         STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
946         if (! attr_inited) {
947             pthread_attr_init(&attr);
948             attr_inited = 1;
949         }
950 
951 #  ifdef PTHREAD_ATTR_SETDETACHSTATE
952         /* Threads start out joinable */
953         PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
954 #  endif
955 
956 #  ifdef _POSIX_THREAD_ATTR_STACKSIZE
957         /* Set thread's stack size */
958         if (thread->stack_size > 0) {
959             rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
960         }
961 #  endif
962 
963         /* Create the thread */
964         if (! rc_stack_size) {
965 #  ifdef OLD_PTHREADS_API
966             rc_thread_create = pthread_create(&thread->thr,
967                                               attr,
968                                               S_ithread_run,
969                                               (void *)thread);
970 #  else
971 #    if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
972             pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
973 #    endif
974             rc_thread_create = pthread_create(&thread->thr,
975                                               &attr,
976                                               S_ithread_run,
977                                               (void *)thread);
978 #  endif
979         }
980 
981 #ifdef THREAD_SIGNAL_BLOCKING
982     /* Now it's safe to accept signals, since we're in our own interpreter's
983      * context and we have created the thread.
984      */
985     S_set_sigmask(&thread->initial_sigmask);
986 #endif
987 
988 #  ifdef _POSIX_THREAD_ATTR_STACKSIZE
989         /* Try to get thread's actual stack size */
990         {
991             size_t stacksize;
992 #ifdef HPUX1020
993             stacksize = pthread_attr_getstacksize(attr);
994 #else
995             if (! pthread_attr_getstacksize(&attr, &stacksize))
996 #endif
997                 if (stacksize > 0) {
998                     thread->stack_size = (IV)stacksize;
999                 }
1000         }
1001 #  endif
1002     }
1003 #endif
1004 
1005     /* Check for errors */
1006 #ifdef WIN32
1007     if (thread->handle == NULL) {
1008 #else
1009     if (rc_stack_size || rc_thread_create) {
1010 #endif
1011         /* Must unlock mutex for destruct call */
1012         /* This lock was acquired in ithread_create()
1013          * prior to calling S_ithread_create(). */
1014         MUTEX_UNLOCK(&my_pool->create_destruct_mutex);
1015         thread->state |= PERL_ITHR_NONVIABLE;
1016         S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
1017 #ifndef WIN32
1018         if (ckWARN_d(WARN_THREADS)) {
1019             if (rc_stack_size) {
1020                 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
1021             } else {
1022                 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
1023             }
1024         }
1025 #endif
1026         return (NULL);
1027     }
1028 
1029     my_pool->running_threads++;
1030     MUTEX_UNLOCK(&my_pool->create_destruct_mutex);
1031     return (thread);
1032 
1033     CLANG_DIAG_IGNORE_STMT(-Wthread-safety);
1034     /* warning: mutex 'thread->mutex' is not held on every path through here [-Wthread-safety-analysis] */
1035 }
1036 CLANG_DIAG_RESTORE_DECL;
1037 
1038 #endif /* USE_ITHREADS */
1039 
1040 
1041 MODULE = threads    PACKAGE = threads    PREFIX = ithread_
1042 PROTOTYPES: DISABLE
1043 
1044 #ifdef USE_ITHREADS
1045 
1046 void
1047 ithread_create(...)
1048     PREINIT:
1049         char *classname;
1050         ithread *thread;
1051         SV *function_to_call;
1052         HV *specs;
1053         IV stack_size;
1054         int context;
1055         int exit_opt;
1056         SV *thread_exit_only;
1057         char *str;
1058         int idx;
1059         dMY_POOL;
1060     CODE:
1061         if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
1062             if (--items < 2) {
1063                 Perl_croak(aTHX_ "Usage: threads->create(\\%%specs, function, ...)");
1064             }
1065             specs = (HV*)SvRV(ST(1));
1066             idx = 1;
1067         } else {
1068             if (items < 2) {
1069                 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
1070             }
1071             specs = NULL;
1072             idx = 0;
1073         }
1074 
1075         if (sv_isobject(ST(0))) {
1076             /* $thr->create() */
1077             classname = HvNAME(SvSTASH(SvRV(ST(0))));
1078             thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1079             MUTEX_LOCK(&thread->mutex);
1080             stack_size = thread->stack_size;
1081             exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
1082             MUTEX_UNLOCK(&thread->mutex);
1083         } else {
1084             /* threads->create() */
1085             classname = (char *)SvPV_nolen(ST(0));
1086             stack_size = MY_POOL.default_stack_size;
1087             thread_exit_only = get_sv("threads::thread_exit_only", GV_ADD);
1088             exit_opt = (SvTRUE(thread_exit_only))
1089                                     ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
1090         }
1091 
1092         function_to_call = ST(idx+1);
1093 
1094         context = -1;
1095         if (specs) {
1096             SV **svp;
1097             /* stack_size */
1098             if ((svp = hv_fetchs(specs, "stack", 0))) {
1099                 stack_size = SvIV(*svp);
1100             } else if ((svp = hv_fetchs(specs, "stacksize", 0))) {
1101                 stack_size = SvIV(*svp);
1102             } else if ((svp = hv_fetchs(specs, "stack_size", 0))) {
1103                 stack_size = SvIV(*svp);
1104             }
1105 
1106             /* context */
1107             if ((svp = hv_fetchs(specs, "context", 0))) {
1108                 str = (char *)SvPV_nolen(*svp);
1109                 switch (*str) {
1110                     case 'a':
1111                     case 'A':
1112                     case 'l':
1113                     case 'L':
1114                         context = G_ARRAY;
1115                         break;
1116                     case 's':
1117                     case 'S':
1118                         context = G_SCALAR;
1119                         break;
1120                     case 'v':
1121                     case 'V':
1122                         context = G_VOID;
1123                         break;
1124                     default:
1125                         Perl_croak(aTHX_ "Invalid context: %s", str);
1126                 }
1127             } else if ((svp = hv_fetchs(specs, "array", 0))) {
1128                 if (SvTRUE(*svp)) {
1129                     context = G_ARRAY;
1130                 }
1131             } else if ((svp = hv_fetchs(specs, "list", 0))) {
1132                 if (SvTRUE(*svp)) {
1133                     context = G_ARRAY;
1134                 }
1135             } else if ((svp = hv_fetchs(specs, "scalar", 0))) {
1136                 if (SvTRUE(*svp)) {
1137                     context = G_SCALAR;
1138                 }
1139             } else if ((svp = hv_fetchs(specs, "void", 0))) {
1140                 if (SvTRUE(*svp)) {
1141                     context = G_VOID;
1142                 }
1143             }
1144 
1145             /* exit => thread_only */
1146             if ((svp = hv_fetchs(specs, "exit", 0))) {
1147                 str = (char *)SvPV_nolen(*svp);
1148                 exit_opt = (*str == 't' || *str == 'T')
1149                                     ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
1150             }
1151         }
1152         if (context == -1) {
1153             context = GIMME_V;  /* Implicit context */
1154         } else {
1155             context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
1156         }
1157 
1158         /* Create thread */
1159         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1160         thread = S_ithread_create(aTHX_ &MY_POOL,
1161                                         function_to_call,
1162                                         stack_size,
1163                                         context,
1164                                         exit_opt,
1165                                         ax + idx + 2,
1166                                         items > 2 ? items - 2 : 0);
1167         if (! thread) {
1168             XSRETURN_UNDEF;     /* Mutex already unlocked */
1169         }
1170         ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
1171 
1172         /* Let thread run. */
1173         /* See S_ithread_run() for more detail. */
1174         CLANG_DIAG_IGNORE_STMT(-Wthread-safety);
1175         /* warning: releasing mutex 'thread->mutex' that was not held [-Wthread-safety-analysis] */
1176         MUTEX_UNLOCK(&thread->mutex);
1177         CLANG_DIAG_RESTORE_STMT;
1178 
1179         /* XSRETURN(1); - implied */
1180 
1181 
1182 void
1183 ithread_list(...)
1184     PREINIT:
1185         char *classname;
1186         ithread *thread;
1187         int list_context;
1188         IV count = 0;
1189         int want_running = 0;
1190         int state;
1191         dMY_POOL;
1192     PPCODE:
1193         /* Class method only */
1194         if (SvROK(ST(0))) {
1195             Perl_croak(aTHX_ "Usage: threads->list(...)");
1196         }
1197         classname = (char *)SvPV_nolen(ST(0));
1198 
1199         /* Calling context */
1200         list_context = (GIMME_V == G_ARRAY);
1201 
1202         /* Running or joinable parameter */
1203         if (items > 1) {
1204             want_running = SvTRUE(ST(1));
1205         }
1206 
1207         /* Walk through threads list */
1208         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1209         for (thread = MY_POOL.main_thread.next;
1210              thread != &MY_POOL.main_thread;
1211              thread = thread->next)
1212         {
1213             MUTEX_LOCK(&thread->mutex);
1214             state = thread->state;
1215             MUTEX_UNLOCK(&thread->mutex);
1216 
1217             /* Ignore detached or joined threads */
1218             if (state & PERL_ITHR_UNCALLABLE) {
1219                 continue;
1220             }
1221 
1222             /* Filter per parameter */
1223             if (items > 1) {
1224                 if (want_running) {
1225                     if (state & PERL_ITHR_FINISHED) {
1226                         continue;   /* Not running */
1227                     }
1228                 } else {
1229                     if (! (state & PERL_ITHR_FINISHED)) {
1230                         continue;   /* Still running - not joinable yet */
1231                     }
1232                 }
1233             }
1234 
1235             /* Push object on stack if list context */
1236             if (list_context) {
1237                 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
1238             }
1239             count++;
1240         }
1241         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1242         /* If scalar context, send back count */
1243         if (! list_context) {
1244             XSRETURN_IV(count);
1245         }
1246 
1247 
1248 void
1249 ithread_self(...)
1250     PREINIT:
1251         char *classname;
1252         ithread *thread;
1253     CODE:
1254         /* Class method only */
1255         if ((items != 1) || SvROK(ST(0))) {
1256             Perl_croak(aTHX_ "Usage: threads->self()");
1257         }
1258         classname = (char *)SvPV_nolen(ST(0));
1259 
1260         thread = S_ithread_get(aTHX);
1261 
1262         ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1263         /* XSRETURN(1); - implied */
1264 
1265 
1266 void
1267 ithread_tid(...)
1268     PREINIT:
1269         ithread *thread;
1270     CODE:
1271         PERL_UNUSED_VAR(items);
1272         thread = S_SV_to_ithread(aTHX_ ST(0));
1273         XST_mUV(0, thread->tid);
1274         /* XSRETURN(1); - implied */
1275 
1276 
1277 void
1278 ithread_join(...)
1279     PREINIT:
1280         ithread *thread;
1281         ithread *current_thread;
1282         int join_err;
1283         AV *params = NULL;
1284         int len;
1285         int ii;
1286 #ifndef WIN32
1287         int rc_join;
1288         void *retval;
1289 #endif
1290         dMY_POOL;
1291     PPCODE:
1292         /* Object method only */
1293         if ((items != 1) || ! sv_isobject(ST(0))) {
1294             Perl_croak(aTHX_ "Usage: $thr->join()");
1295         }
1296 
1297         /* Check if the thread is joinable and not ourselves */
1298         thread = S_SV_to_ithread(aTHX_ ST(0));
1299         current_thread = S_ithread_get(aTHX);
1300 
1301         MUTEX_LOCK(&thread->mutex);
1302         if ((join_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1303             MUTEX_UNLOCK(&thread->mutex);
1304             Perl_croak(aTHX_ (join_err & PERL_ITHR_DETACHED)
1305                                 ? "Cannot join a detached thread"
1306                                 : "Thread already joined");
1307         } else if (thread->tid == current_thread->tid) {
1308             MUTEX_UNLOCK(&thread->mutex);
1309             Perl_croak(aTHX_ "Cannot join self");
1310         }
1311 
1312         /* Mark as joined */
1313         thread->state |= PERL_ITHR_JOINED;
1314         MUTEX_UNLOCK(&thread->mutex);
1315 
1316         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1317         MY_POOL.joinable_threads--;
1318         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1319 
1320         /* Join the thread */
1321 #ifdef WIN32
1322         if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1323             /* Timeout/abandonment unexpected here; check $^E */
1324             Perl_croak(aTHX_ "PANIC: underlying join failed");
1325         };
1326 #else
1327         if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1328             /* In progress/deadlock/unknown unexpected here; check $! */
1329             errno = rc_join;
1330             Perl_croak(aTHX_ "PANIC: underlying join failed");
1331         };
1332 #endif
1333 
1334         MUTEX_LOCK(&thread->mutex);
1335         /* Get the return value from the call_sv */
1336         /* Objects do not survive this process - FIXME */
1337         if ((thread->gimme & G_WANT) != G_VOID) {
1338 #if (PERL_VERSION < 13) || (PERL_VERSION == 13 && PERL_SUBVERSION <= 1)
1339             AV *params_copy;
1340             PerlInterpreter *other_perl;
1341             CLONE_PARAMS clone_params;
1342 
1343             params_copy = thread->params;
1344             other_perl = thread->interp;
1345             clone_params.stashes = newAV();
1346             clone_params.flags = CLONEf_JOIN_IN;
1347             PL_ptr_table = ptr_table_new();
1348             S_ithread_set(aTHX_ thread);
1349             /* Ensure 'meaningful' addresses retain their meaning */
1350             ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1351             ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1352             ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1353             params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1354             S_ithread_set(aTHX_ current_thread);
1355             SvREFCNT_dec(clone_params.stashes);
1356             SvREFCNT_inc_void(params);
1357             ptr_table_free(PL_ptr_table);
1358             PL_ptr_table = NULL;
1359 #else
1360             AV *params_copy;
1361             PerlInterpreter *other_perl = thread->interp;
1362             CLONE_PARAMS *clone_params = Perl_clone_params_new(other_perl, aTHX);
1363 
1364             params_copy = thread->params;
1365             clone_params->flags |= CLONEf_JOIN_IN;
1366             PL_ptr_table = ptr_table_new();
1367             S_ithread_set(aTHX_ thread);
1368             /* Ensure 'meaningful' addresses retain their meaning */
1369             ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1370             ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1371             ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1372 #  ifdef PL_sv_zero
1373             ptr_table_store(PL_ptr_table, &other_perl->Isv_zero, &PL_sv_zero);
1374 #  endif
1375             params = (AV *)sv_dup((SV*)params_copy, clone_params);
1376             S_ithread_set(aTHX_ current_thread);
1377             Perl_clone_params_del(clone_params);
1378             SvREFCNT_inc_void(params);
1379             ptr_table_free(PL_ptr_table);
1380             PL_ptr_table = NULL;
1381 #endif
1382         }
1383 
1384         /* If thread didn't die, then we can free its interpreter */
1385         if (! (thread->state & PERL_ITHR_DIED)) {
1386             S_ithread_clear(aTHX_ thread);
1387         }
1388         S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
1389 
1390         /* If no return values, then just return */
1391         if (! params) {
1392             XSRETURN_UNDEF;
1393         }
1394 
1395         /* Put return values on stack */
1396         len = (int)AvFILL(params);
1397         for (ii=0; ii <= len; ii++) {
1398             SV* param = av_shift(params);
1399             XPUSHs(sv_2mortal(param));
1400         }
1401 
1402         /* Free return value array */
1403         SvREFCNT_dec(params);
1404 
1405 
1406 void
1407 ithread_yield(...)
1408     CODE:
1409         PERL_UNUSED_VAR(items);
1410         YIELD;
1411 
1412 
1413 void
1414 ithread_detach(...)
1415     PREINIT:
1416         ithread *thread;
1417         int detach_err;
1418         dMY_POOL;
1419     CODE:
1420         PERL_UNUSED_VAR(items);
1421 
1422         /* Detach the thread */
1423         thread = S_SV_to_ithread(aTHX_ ST(0));
1424         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1425         MUTEX_LOCK(&thread->mutex);
1426         if (! (detach_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1427             /* Thread is detachable */
1428             thread->state |= PERL_ITHR_DETACHED;
1429 #ifdef WIN32
1430             /* Windows has no 'detach thread' function */
1431 #else
1432             PERL_THREAD_DETACH(thread->thr);
1433 #endif
1434             if (thread->state & PERL_ITHR_FINISHED) {
1435                 MY_POOL.joinable_threads--;
1436             } else {
1437                 MY_POOL.running_threads--;
1438                 MY_POOL.detached_threads++;
1439             }
1440         }
1441         MUTEX_UNLOCK(&thread->mutex);
1442         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1443 
1444         if (detach_err) {
1445             Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1446                                 ? "Thread already detached"
1447                                 : "Cannot detach a joined thread");
1448         }
1449 
1450         /* If thread is finished and didn't die,
1451          * then we can free its interpreter */
1452         MUTEX_LOCK(&thread->mutex);
1453         if ((thread->state & PERL_ITHR_FINISHED) &&
1454             ! (thread->state & PERL_ITHR_DIED))
1455         {
1456             S_ithread_clear(aTHX_ thread);
1457         }
1458         S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
1459 
1460 
1461 void
1462 ithread_kill(...)
1463     PREINIT:
1464         ithread *thread;
1465         char *sig_name;
1466         IV signal;
1467         int no_handler = 1;
1468     CODE:
1469         /* Must have safe signals */
1470         if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1471             Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1472         }
1473 
1474         /* Object method only */
1475         if ((items != 2) || ! sv_isobject(ST(0))) {
1476             Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1477         }
1478 
1479         /* Get signal */
1480         sig_name = SvPV_nolen(ST(1));
1481         if (isALPHA(*sig_name)) {
1482             if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1483                 sig_name += 3;
1484             }
1485             if ((signal = whichsig(sig_name)) < 0) {
1486                 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1487             }
1488         } else {
1489             signal = SvIV(ST(1));
1490         }
1491 
1492         /* Set the signal for the thread */
1493         thread = S_SV_to_ithread(aTHX_ ST(0));
1494         MUTEX_LOCK(&thread->mutex);
1495         if (thread->interp && ! (thread->state & PERL_ITHR_FINISHED)) {
1496             dTHXa(thread->interp);
1497             if (PL_psig_pend && PL_psig_ptr[signal]) {
1498                 PL_psig_pend[signal]++;
1499                 PL_sig_pending = 1;
1500                 no_handler = 0;
1501             }
1502         } else {
1503             /* Ignore signal to terminated/finished thread */
1504             no_handler = 0;
1505         }
1506         MUTEX_UNLOCK(&thread->mutex);
1507 
1508         if (no_handler) {
1509             Perl_croak(aTHX_ "Signal %s received in thread %" UVuf
1510                              ", but no signal handler set.",
1511                              sig_name, thread->tid);
1512         }
1513 
1514         /* Return the thread to allow for method chaining */
1515         ST(0) = ST(0);
1516         /* XSRETURN(1); - implied */
1517 
1518 
1519 void
1520 ithread_DESTROY(...)
1521     CODE:
1522         PERL_UNUSED_VAR(items);
1523         sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1524 
1525 
1526 void
1527 ithread_equal(...)
1528     PREINIT:
1529         int are_equal = 0;
1530     CODE:
1531         PERL_UNUSED_VAR(items);
1532 
1533         /* Compares TIDs to determine thread equality */
1534         if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1535             ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1536             ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1537             are_equal = (thr1->tid == thr2->tid);
1538         }
1539         if (are_equal) {
1540             XST_mYES(0);
1541         } else {
1542             /* Return 0 on false for backward compatibility */
1543             XST_mIV(0, 0);
1544         }
1545         /* XSRETURN(1); - implied */
1546 
1547 
1548 void
1549 ithread_object(...)
1550     PREINIT:
1551         char *classname;
1552         SV *arg;
1553         UV tid;
1554         ithread *thread;
1555         int state;
1556         int have_obj = 0;
1557         dMY_POOL;
1558     CODE:
1559         /* Class method only */
1560         if (SvROK(ST(0))) {
1561             Perl_croak(aTHX_ "Usage: threads->object($tid)");
1562         }
1563         classname = (char *)SvPV_nolen(ST(0));
1564 
1565         /* Turn $tid from PVLV to SV if needed (bug #73330) */
1566         arg = ST(1);
1567         SvGETMAGIC(arg);
1568 
1569         if ((items < 2) || ! SvOK(arg)) {
1570             XSRETURN_UNDEF;
1571         }
1572 
1573         /* threads->object($tid) */
1574         tid = SvUV(arg);
1575 
1576         /* If current thread wants its own object, then behave the same as
1577            ->self() */
1578         thread = S_ithread_get(aTHX);
1579         if (thread->tid == tid) {
1580             ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1581             have_obj = 1;
1582 
1583         } else {
1584             /* Walk through threads list */
1585             MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1586             for (thread = MY_POOL.main_thread.next;
1587                  thread != &MY_POOL.main_thread;
1588                  thread = thread->next)
1589             {
1590                 /* Look for TID */
1591                 if (thread->tid == tid) {
1592                     /* Ignore if detached or joined */
1593                     MUTEX_LOCK(&thread->mutex);
1594                     state = thread->state;
1595                     MUTEX_UNLOCK(&thread->mutex);
1596                     if (! (state & PERL_ITHR_UNCALLABLE)) {
1597                         /* Put object on stack */
1598                         ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1599                         have_obj = 1;
1600                     }
1601                     break;
1602                 }
1603             }
1604             MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1605         }
1606 
1607         if (! have_obj) {
1608             XSRETURN_UNDEF;
1609         }
1610         /* XSRETURN(1); - implied */
1611 
1612 
1613 void
1614 ithread__handle(...);
1615     PREINIT:
1616         ithread *thread;
1617     CODE:
1618         PERL_UNUSED_VAR(items);
1619         thread = S_SV_to_ithread(aTHX_ ST(0));
1620 #ifdef WIN32
1621         XST_mUV(0, PTR2UV(&thread->handle));
1622 #else
1623         XST_mUV(0, PTR2UV(&thread->thr));
1624 #endif
1625         /* XSRETURN(1); - implied */
1626 
1627 
1628 void
1629 ithread_get_stack_size(...)
1630     PREINIT:
1631         IV stack_size;
1632         dMY_POOL;
1633     CODE:
1634         PERL_UNUSED_VAR(items);
1635         if (sv_isobject(ST(0))) {
1636             /* $thr->get_stack_size() */
1637             ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1638             stack_size = thread->stack_size;
1639         } else {
1640             /* threads->get_stack_size() */
1641             stack_size = MY_POOL.default_stack_size;
1642         }
1643         XST_mIV(0, stack_size);
1644         /* XSRETURN(1); - implied */
1645 
1646 
1647 void
1648 ithread_set_stack_size(...)
1649     PREINIT:
1650         IV old_size;
1651         dMY_POOL;
1652     CODE:
1653         if (items != 2) {
1654             Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1655         }
1656         if (sv_isobject(ST(0))) {
1657             Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1658         }
1659         if (! looks_like_number(ST(1))) {
1660             Perl_croak(aTHX_ "Stack size must be numeric");
1661         }
1662 
1663         old_size = MY_POOL.default_stack_size;
1664         MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1665         XST_mIV(0, old_size);
1666         /* XSRETURN(1); - implied */
1667 
1668 
1669 void
1670 ithread_is_running(...)
1671     PREINIT:
1672         ithread *thread;
1673     CODE:
1674         /* Object method only */
1675         if ((items != 1) || ! sv_isobject(ST(0))) {
1676             Perl_croak(aTHX_ "Usage: $thr->is_running()");
1677         }
1678 
1679         thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1680         MUTEX_LOCK(&thread->mutex);
1681         ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1682         MUTEX_UNLOCK(&thread->mutex);
1683         /* XSRETURN(1); - implied */
1684 
1685 
1686 void
1687 ithread_is_detached(...)
1688     PREINIT:
1689         ithread *thread;
1690     CODE:
1691         PERL_UNUSED_VAR(items);
1692         thread = S_SV_to_ithread(aTHX_ ST(0));
1693         MUTEX_LOCK(&thread->mutex);
1694         ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1695         MUTEX_UNLOCK(&thread->mutex);
1696         /* XSRETURN(1); - implied */
1697 
1698 
1699 void
1700 ithread_is_joinable(...)
1701     PREINIT:
1702         ithread *thread;
1703     CODE:
1704         /* Object method only */
1705         if ((items != 1) || ! sv_isobject(ST(0))) {
1706             Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1707         }
1708 
1709         thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1710         MUTEX_LOCK(&thread->mutex);
1711         ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1712                  ! (thread->state & PERL_ITHR_UNCALLABLE))
1713             ? &PL_sv_yes : &PL_sv_no;
1714         MUTEX_UNLOCK(&thread->mutex);
1715         /* XSRETURN(1); - implied */
1716 
1717 
1718 void
1719 ithread_wantarray(...)
1720     PREINIT:
1721         ithread *thread;
1722     CODE:
1723         PERL_UNUSED_VAR(items);
1724         thread = S_SV_to_ithread(aTHX_ ST(0));
1725         ST(0) = ((thread->gimme & G_WANT) == G_ARRAY) ? &PL_sv_yes :
1726                 ((thread->gimme & G_WANT) == G_VOID)  ? &PL_sv_undef
1727                                        /* G_SCALAR */ : &PL_sv_no;
1728         /* XSRETURN(1); - implied */
1729 
1730 
1731 void
1732 ithread_set_thread_exit_only(...)
1733     PREINIT:
1734         ithread *thread;
1735     CODE:
1736         if (items != 2) {
1737             Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1738         }
1739         thread = S_SV_to_ithread(aTHX_ ST(0));
1740         MUTEX_LOCK(&thread->mutex);
1741         if (SvTRUE(ST(1))) {
1742             thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1743         } else {
1744             thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1745         }
1746         MUTEX_UNLOCK(&thread->mutex);
1747 
1748 
1749 void
1750 ithread_error(...)
1751     PREINIT:
1752         ithread *thread;
1753         SV *err = NULL;
1754     CODE:
1755         /* Object method only */
1756         if ((items != 1) || ! sv_isobject(ST(0))) {
1757             Perl_croak(aTHX_ "Usage: $thr->err()");
1758         }
1759 
1760         thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1761         MUTEX_LOCK(&thread->mutex);
1762 
1763         /* If thread died, then clone the error into the calling thread */
1764         if (thread->state & PERL_ITHR_DIED) {
1765 #if (PERL_VERSION < 13) || (PERL_VERSION == 13 && PERL_SUBVERSION <= 1)
1766             PerlInterpreter *other_perl;
1767             CLONE_PARAMS clone_params;
1768             ithread *current_thread;
1769 
1770             other_perl = thread->interp;
1771             clone_params.stashes = newAV();
1772             clone_params.flags = CLONEf_JOIN_IN;
1773             PL_ptr_table = ptr_table_new();
1774             current_thread = S_ithread_get(aTHX);
1775             S_ithread_set(aTHX_ thread);
1776             /* Ensure 'meaningful' addresses retain their meaning */
1777             ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1778             ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1779             ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1780             err = sv_dup(thread->err, &clone_params);
1781             S_ithread_set(aTHX_ current_thread);
1782             SvREFCNT_dec(clone_params.stashes);
1783             SvREFCNT_inc_void(err);
1784             /* If error was an object, bless it into the correct class */
1785             if (thread->err_class) {
1786                 sv_bless(err, gv_stashpv(thread->err_class, 1));
1787             }
1788             ptr_table_free(PL_ptr_table);
1789             PL_ptr_table = NULL;
1790 #else
1791             PerlInterpreter *other_perl = thread->interp;
1792             CLONE_PARAMS *clone_params = Perl_clone_params_new(other_perl, aTHX);
1793             ithread *current_thread;
1794 
1795             clone_params->flags |= CLONEf_JOIN_IN;
1796             PL_ptr_table = ptr_table_new();
1797             current_thread = S_ithread_get(aTHX);
1798             S_ithread_set(aTHX_ thread);
1799             /* Ensure 'meaningful' addresses retain their meaning */
1800             ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1801             ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1802             ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1803 #  ifdef PL_sv_zero
1804             ptr_table_store(PL_ptr_table, &other_perl->Isv_zero, &PL_sv_zero);
1805 #  endif
1806             err = sv_dup(thread->err, clone_params);
1807             S_ithread_set(aTHX_ current_thread);
1808             Perl_clone_params_del(clone_params);
1809             SvREFCNT_inc_void(err);
1810             /* If error was an object, bless it into the correct class */
1811             if (thread->err_class) {
1812                 sv_bless(err, gv_stashpv(thread->err_class, 1));
1813             }
1814             ptr_table_free(PL_ptr_table);
1815             PL_ptr_table = NULL;
1816 #endif
1817         }
1818 
1819         MUTEX_UNLOCK(&thread->mutex);
1820 
1821         if (! err) {
1822             XSRETURN_UNDEF;
1823         }
1824 
1825         ST(0) = sv_2mortal(err);
1826         /* XSRETURN(1); - implied */
1827 
1828 
1829 #endif /* USE_ITHREADS */
1830 
1831 
1832 BOOT:
1833 {
1834 #ifdef USE_ITHREADS
1835     SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1836                                sizeof(MY_POOL_KEY)-1, TRUE);
1837     my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1838 
1839     MY_CXT_INIT;
1840 
1841     Zero(my_poolp, 1, my_pool_t);
1842     sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1843 
1844     PL_perl_destruct_level = 2;
1845     MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1846     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1847 
1848     PL_threadhook = &Perl_ithread_hook;
1849 
1850     MY_POOL.tid_counter = 1;
1851 #  ifdef THREAD_CREATE_NEEDS_STACK
1852     MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1853 #  endif
1854 
1855     /* The 'main' thread is thread 0.
1856      * It is detached (unjoinable) and immortal.
1857      */
1858 
1859     MUTEX_INIT(&MY_POOL.main_thread.mutex);
1860 
1861     /* Head of the threads list */
1862     MY_POOL.main_thread.next = &MY_POOL.main_thread;
1863     MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1864 
1865     MY_POOL.main_thread.count = 1;                  /* Immortal */
1866 
1867     MY_POOL.main_thread.interp = aTHX;
1868     MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1869     MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1870 #  ifdef WIN32
1871     MY_POOL.main_thread.thr = GetCurrentThreadId();
1872 #  else
1873     MY_POOL.main_thread.thr = pthread_self();
1874 #  endif
1875 
1876     S_ithread_set(aTHX_ &MY_POOL.main_thread);
1877     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1878 #endif /* USE_ITHREADS */
1879 }
1880