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