prohibit thread join()ing itself (from Dan Sugalski)
[p5sagit/p5-mst-13.2.git] / ext / Thread / Thread.xs
1 #include "EXTERN.h"
2 #include "perl.h"
3 #include "XSUB.h"
4
5 /* Magic signature for Thread's mg_private is "Th" */ 
6 #define Thread_MAGIC_SIGNATURE 0x5468
7
8 #ifdef __cplusplus
9 #ifdef I_UNISTD
10 #include <unistd.h>
11 #endif
12 #endif
13 #include <fcntl.h>
14                         
15 static int sig_pipe[2];
16             
17 #ifndef THREAD_RET_TYPE
18 #define THREAD_RET_TYPE void *
19 #define THREAD_RET_CAST(x) ((THREAD_RET_TYPE) x)
20 #endif
21
22 static void
23 remove_thread(pTHX_ struct perl_thread *t)
24 {
25 #ifdef USE_THREADS
26     DEBUG_S(WITH_THR(PerlIO_printf(PerlIO_stderr(),
27                                    "%p: remove_thread %p\n", thr, t)));
28     MUTEX_LOCK(&PL_threads_mutex);
29     MUTEX_DESTROY(&t->mutex);
30     PL_nthreads--;
31     t->prev->next = t->next;
32     t->next->prev = t->prev;
33     COND_BROADCAST(&PL_nthreads_cond);
34     MUTEX_UNLOCK(&PL_threads_mutex);
35 #endif
36 }
37
38 static THREAD_RET_TYPE
39 threadstart(void *arg)
40 {
41 #ifdef USE_THREADS
42 #ifdef FAKE_THREADS
43     Thread savethread = thr;
44     LOGOP myop;
45     dSP;
46     I32 oldscope = PL_scopestack_ix;
47     I32 retval;
48     AV *av;
49     int i;
50
51     DEBUG_S(PerlIO_printf(PerlIO_stderr(), "new thread %p starting at %s\n",
52                           thr, SvPEEK(TOPs)));
53     thr = (Thread) arg;
54     savemark = TOPMARK;
55     thr->prev = thr->prev_run = savethread;
56     thr->next = savethread->next;
57     thr->next_run = savethread->next_run;
58     savethread->next = savethread->next_run = thr;
59     thr->wait_queue = 0;
60     thr->private = 0;
61
62     /* Now duplicate most of perl_call_sv but with a few twists */
63     PL_op = (OP*)&myop;
64     Zero(PL_op, 1, LOGOP);
65     myop.op_flags = OPf_STACKED;
66     myop.op_next = Nullop;
67     myop.op_flags |= OPf_KNOW;
68     myop.op_flags |= OPf_WANT_LIST;
69     PL_op = pp_entersub(ARGS);
70     DEBUG_S(if (!PL_op)
71             PerlIO_printf(PerlIO_stderr(), "thread starts at Nullop\n"));
72     /*
73      * When this thread is next scheduled, we start in the right
74      * place. When the thread runs off the end of the sub, perl.c
75      * handles things, using savemark to figure out how much of the
76      * stack is the return value for any join.
77      */
78     thr = savethread;           /* back to the old thread */
79     return 0;
80 #else
81     Thread thr = (Thread) arg;
82     LOGOP myop;
83     djSP;
84     I32 oldmark = TOPMARK;
85     I32 oldscope = PL_scopestack_ix;
86     I32 retval;
87     SV *sv;
88     AV *av = newAV();
89     int i, ret;
90     dJMPENV;
91     DEBUG_S(PerlIO_printf(PerlIO_stderr(), "new thread %p waiting to start\n",
92                           thr));
93
94     /* Don't call *anything* requiring dTHR until after SET_THR() */
95     /*
96      * Wait until our creator releases us. If we didn't do this, then
97      * it would be potentially possible for out thread to carry on and
98      * do stuff before our creator fills in our "self" field. For example,
99      * if we went and created another thread which tried to JOIN with us,
100      * then we'd be in a mess.
101      */
102     MUTEX_LOCK(&thr->mutex);
103     MUTEX_UNLOCK(&thr->mutex);
104
105     /*
106      * It's safe to wait until now to set the thread-specific pointer
107      * from our pthread_t structure to our struct perl_thread, since
108      * we're the only thread who can get at it anyway.
109      */
110     SET_THR(thr);
111
112     /* Only now can we use SvPEEK (which calls sv_newmortal which does dTHR) */
113     DEBUG_S(PerlIO_printf(PerlIO_stderr(), "new thread %p starting at %s\n",
114                           thr, SvPEEK(TOPs)));
115
116     sv = POPs;
117     PUTBACK;
118     ENTER;
119     SAVETMPS;
120     perl_call_sv(sv, G_ARRAY|G_EVAL);
121     SPAGAIN;
122     retval = SP - (PL_stack_base + oldmark);
123     SP = PL_stack_base + oldmark + 1;
124     if (SvCUR(thr->errsv)) {
125         MUTEX_LOCK(&thr->mutex);
126         thr->flags |= THRf_DID_DIE;
127         MUTEX_UNLOCK(&thr->mutex);
128         av_store(av, 0, &PL_sv_no);
129         av_store(av, 1, newSVsv(thr->errsv));
130         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p died: %s\n",
131                               thr, SvPV(thr->errsv, PL_na)));
132     } else {
133         DEBUG_S(STMT_START {
134             for (i = 1; i <= retval; i++) {
135                 PerlIO_printf(PerlIO_stderr(), "%p return[%d] = %s\n",
136                                 thr, i, SvPEEK(SP[i - 1]));
137             }
138         } STMT_END);
139         av_store(av, 0, &PL_sv_yes);
140         for (i = 1; i <= retval; i++, SP++)
141             sv_setsv(*av_fetch(av, i, TRUE), SvREFCNT_inc(*SP));
142     }
143     FREETMPS;
144     LEAVE;
145
146   finishoff:
147 #if 0    
148     /* removed for debug */
149     SvREFCNT_dec(PL_curstack);
150 #endif
151     SvREFCNT_dec(thr->cvcache);
152     SvREFCNT_dec(thr->threadsv);
153     SvREFCNT_dec(thr->specific);
154     SvREFCNT_dec(thr->errsv);
155     SvREFCNT_dec(thr->errhv);
156
157     /*Safefree(cxstack);*/
158     while (PL_curstackinfo->si_next)
159         PL_curstackinfo = PL_curstackinfo->si_next;
160     while (PL_curstackinfo) {
161         PERL_SI *p = PL_curstackinfo->si_prev;
162         SvREFCNT_dec(PL_curstackinfo->si_stack);
163         Safefree(PL_curstackinfo->si_cxstack);
164         Safefree(PL_curstackinfo);
165         PL_curstackinfo = p;
166     }    
167     Safefree(PL_markstack);
168     Safefree(PL_scopestack);
169     Safefree(PL_savestack);
170     Safefree(PL_retstack);
171     Safefree(PL_tmps_stack);
172     Safefree(PL_ofs);
173
174     SvREFCNT_dec(PL_rs);
175     SvREFCNT_dec(PL_nrs);
176     SvREFCNT_dec(PL_statname);
177     Safefree(PL_screamfirst);
178     Safefree(PL_screamnext);
179     Safefree(PL_reg_start_tmp);
180     SvREFCNT_dec(PL_lastscream);
181     SvREFCNT_dec(PL_defoutgv);
182
183     MUTEX_LOCK(&thr->mutex);
184     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
185                           "%p: threadstart finishing: state is %u\n",
186                           thr, ThrSTATE(thr)));
187     switch (ThrSTATE(thr)) {
188     case THRf_R_JOINABLE:
189         ThrSETSTATE(thr, THRf_ZOMBIE);
190         MUTEX_UNLOCK(&thr->mutex);
191         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
192                               "%p: R_JOINABLE thread finished\n", thr));
193         break;
194     case THRf_R_JOINED:
195         ThrSETSTATE(thr, THRf_DEAD);
196         MUTEX_UNLOCK(&thr->mutex);
197         remove_thread(aTHX_ thr);
198         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
199                               "%p: R_JOINED thread finished\n", thr));
200         break;
201     case THRf_R_DETACHED:
202         ThrSETSTATE(thr, THRf_DEAD);
203         MUTEX_UNLOCK(&thr->mutex);
204         SvREFCNT_dec(av);
205         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
206                               "%p: DETACHED thread finished\n", thr));
207         remove_thread(aTHX_ thr);       /* This might trigger main thread to finish */
208         break;
209     default:
210         MUTEX_UNLOCK(&thr->mutex);
211         croak("panic: illegal state %u at end of threadstart", ThrSTATE(thr));
212         /* NOTREACHED */
213     }
214     return THREAD_RET_CAST(av); /* Available for anyone to join with */
215                                         /* us unless we're detached, in which */
216                                         /* case noone sees the value anyway. */
217 #endif    
218 #else
219     return THREAD_RET_CAST(NULL);
220 #endif
221 }
222
223 static SV *
224 newthread (pTHX_ SV *startsv, AV *initargs, char *classname)
225 {
226 #ifdef USE_THREADS
227     dSP;
228     Thread savethread;
229     int i;
230     SV *sv;
231     int err;
232 #ifndef THREAD_CREATE
233     static pthread_attr_t attr;
234     static int attr_inited = 0;
235     sigset_t fullmask, oldmask;
236     static int attr_joinable = PTHREAD_CREATE_JOINABLE;
237 #endif
238
239     savethread = thr;
240     thr = new_struct_thread(thr);
241     /* temporarily pretend to be the child thread in case the
242      * XPUSHs() below want to grow the child's stack.  This is
243      * safe, since the other thread is not yet created, and we
244      * are the only ones who know about it */
245     SET_THR(thr);
246     SPAGAIN;
247     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
248                           "%p: newthread (%p), tid is %u, preparing stack\n",
249                           savethread, thr, thr->tid));
250     /* The following pushes the arg list and startsv onto the *new* stack */
251     PUSHMARK(SP);
252     /* Could easily speed up the following greatly */
253     for (i = 0; i <= AvFILL(initargs); i++)
254         XPUSHs(SvREFCNT_inc(*av_fetch(initargs, i, FALSE)));
255     XPUSHs(SvREFCNT_inc(startsv));
256     PUTBACK;
257
258     /* On your marks... */
259     SET_THR(savethread);
260     MUTEX_LOCK(&thr->mutex);
261
262 #ifdef THREAD_CREATE
263     err = THREAD_CREATE(thr, threadstart);
264 #else    
265     /* Get set...  */
266     sigfillset(&fullmask);
267     if (sigprocmask(SIG_SETMASK, &fullmask, &oldmask) == -1)
268         croak("panic: sigprocmask");
269     err = 0;
270     if (!attr_inited) {
271         attr_inited = 1;
272         err = pthread_attr_init(&attr);
273 #  ifdef PTHREAD_ATTR_SETDETACHSTATE
274         if (err == 0)
275             err = PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
276
277 #  else
278         croak("panic: can't pthread_attr_setdetachstate");
279 #  endif
280     }
281     if (err == 0)
282         err = PTHREAD_CREATE(&thr->self, attr, threadstart, (void*) thr);
283 #endif
284
285     if (err) {
286         MUTEX_UNLOCK(&thr->mutex);
287         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
288                               "%p: create of %p failed %d\n",
289                               savethread, thr, err));
290         /* Thread creation failed--clean up */
291         SvREFCNT_dec(thr->cvcache);
292         remove_thread(aTHX_ thr);
293         MUTEX_DESTROY(&thr->mutex);
294         for (i = 0; i <= AvFILL(initargs); i++)
295             SvREFCNT_dec(*av_fetch(initargs, i, FALSE));
296         SvREFCNT_dec(startsv);
297         return NULL;
298     }
299
300 #ifdef THREAD_POST_CREATE
301     THREAD_POST_CREATE(thr);
302 #else
303     if (sigprocmask(SIG_SETMASK, &oldmask, 0))
304         croak("panic: sigprocmask");
305 #endif
306
307     sv = newSViv(thr->tid);
308     sv_magic(sv, thr->oursv, '~', 0, 0);
309     SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
310     sv = sv_bless(newRV_noinc(sv), gv_stashpv(classname, TRUE));
311
312     /* Go */
313     MUTEX_UNLOCK(&thr->mutex);
314
315     return sv;
316 #else
317     croak("No threads in this perl");
318     return &PL_sv_undef;
319 #endif
320 }
321
322 static Signal_t handle_thread_signal (int sig);
323
324 static Signal_t
325 handle_thread_signal(int sig)
326 {
327     unsigned char c = (unsigned char) sig;
328     /*
329      * We're not really allowed to call fprintf in a signal handler
330      * so don't be surprised if this isn't robust while debugging
331      * with -DL.
332      */
333     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
334             "handle_thread_signal: got signal %d\n", sig););
335     write(sig_pipe[1], &c, 1);
336 }
337
338 MODULE = Thread         PACKAGE = Thread
339 PROTOTYPES: DISABLE
340
341 void
342 new(classname, startsv, ...)
343         char *          classname
344         SV *            startsv
345         AV *            av = av_make(items - 2, &ST(2));
346     PPCODE:
347         XPUSHs(sv_2mortal(newthread(aTHX_ startsv, av, classname)));
348
349 void
350 join(t)
351         Thread  t
352         AV *    av = NO_INIT
353         int     i = NO_INIT
354     PPCODE:
355 #ifdef USE_THREADS
356         if (t == thr)
357             croak("Attempt to join self");
358         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: joining %p (state %u)\n",
359                               thr, t, ThrSTATE(t)););
360         MUTEX_LOCK(&t->mutex);
361         switch (ThrSTATE(t)) {
362         case THRf_R_JOINABLE:
363         case THRf_R_JOINED:
364             ThrSETSTATE(t, THRf_R_JOINED);
365             MUTEX_UNLOCK(&t->mutex);
366             break;
367         case THRf_ZOMBIE:
368             ThrSETSTATE(t, THRf_DEAD);
369             MUTEX_UNLOCK(&t->mutex);
370             remove_thread(aTHX_ t);
371             break;
372         default:
373             MUTEX_UNLOCK(&t->mutex);
374             croak("can't join with thread");
375             /* NOTREACHED */
376         }
377         JOIN(t, &av);
378
379         if (SvTRUE(*av_fetch(av, 0, FALSE))) {
380             /* Could easily speed up the following if necessary */
381             for (i = 1; i <= AvFILL(av); i++)
382                 XPUSHs(sv_2mortal(*av_fetch(av, i, FALSE)));
383         } else {
384             STRLEN n_a;
385             char *mess = SvPV(*av_fetch(av, 1, FALSE), n_a);
386             DEBUG_S(PerlIO_printf(PerlIO_stderr(),
387                                   "%p: join propagating die message: %s\n",
388                                   thr, mess));
389             croak(mess);
390         }
391 #endif
392
393 void
394 detach(t)
395         Thread  t
396     CODE:
397 #ifdef USE_THREADS
398         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: detaching %p (state %u)\n",
399                               thr, t, ThrSTATE(t)););
400         MUTEX_LOCK(&t->mutex);
401         switch (ThrSTATE(t)) {
402         case THRf_R_JOINABLE:
403             ThrSETSTATE(t, THRf_R_DETACHED);
404             /* fall through */
405         case THRf_R_DETACHED:
406             DETACH(t);
407             MUTEX_UNLOCK(&t->mutex);
408             break;
409         case THRf_ZOMBIE:
410             ThrSETSTATE(t, THRf_DEAD);
411             DETACH(t);
412             MUTEX_UNLOCK(&t->mutex);
413             remove_thread(aTHX_ t);
414             break;
415         default:
416             MUTEX_UNLOCK(&t->mutex);
417             croak("can't detach thread");
418             /* NOTREACHED */
419         }
420 #endif
421
422 void
423 equal(t1, t2)
424         Thread  t1
425         Thread  t2
426     PPCODE:
427         PUSHs((t1 == t2) ? &PL_sv_yes : &PL_sv_no);
428
429 void
430 flags(t)
431         Thread  t
432     PPCODE:
433 #ifdef USE_THREADS
434         PUSHs(sv_2mortal(newSViv(t->flags)));
435 #endif
436
437 void
438 self(classname)
439         char *  classname
440     PREINIT:
441         SV *sv;
442     PPCODE:        
443 #ifdef USE_THREADS
444         sv = newSViv(thr->tid);
445         sv_magic(sv, thr->oursv, '~', 0, 0);
446         SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
447         PUSHs(sv_2mortal(sv_bless(newRV_noinc(sv),
448                                   gv_stashpv(classname, TRUE))));
449 #endif
450
451 U32
452 tid(t)
453         Thread  t
454     CODE:
455 #ifdef USE_THREADS
456         MUTEX_LOCK(&t->mutex);
457         RETVAL = t->tid;
458         MUTEX_UNLOCK(&t->mutex);
459 #else 
460         RETVAL = 0;
461 #endif
462     OUTPUT:
463         RETVAL
464
465 void
466 DESTROY(t)
467         SV *    t
468     PPCODE:
469         PUSHs(&PL_sv_yes);
470
471 void
472 yield()
473     CODE:
474 {
475 #ifdef USE_THREADS
476         YIELD;
477 #endif
478 }
479
480 void
481 cond_wait(sv)
482         SV *    sv
483         MAGIC * mg = NO_INIT
484 CODE:                       
485 #ifdef USE_THREADS
486         if (SvROK(sv))
487             sv = SvRV(sv);
488
489         mg = condpair_magic(sv);
490         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: cond_wait %p\n", thr, sv));
491         MUTEX_LOCK(MgMUTEXP(mg));
492         if (MgOWNER(mg) != thr) {
493             MUTEX_UNLOCK(MgMUTEXP(mg));
494             croak("cond_wait for lock that we don't own\n");
495         }
496         MgOWNER(mg) = 0;
497         COND_SIGNAL(MgOWNERCONDP(mg));
498         COND_WAIT(MgCONDP(mg), MgMUTEXP(mg));
499         while (MgOWNER(mg))
500             COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
501         MgOWNER(mg) = thr;
502         MUTEX_UNLOCK(MgMUTEXP(mg));
503 #endif
504
505 void
506 cond_signal(sv)
507         SV *    sv
508         MAGIC * mg = NO_INIT
509 CODE:
510 #ifdef USE_THREADS
511         if (SvROK(sv))
512             sv = SvRV(sv);
513
514         mg = condpair_magic(sv);
515         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: cond_signal %p\n",thr,sv));
516         MUTEX_LOCK(MgMUTEXP(mg));
517         if (MgOWNER(mg) != thr) {
518             MUTEX_UNLOCK(MgMUTEXP(mg));
519             croak("cond_signal for lock that we don't own\n");
520         }
521         COND_SIGNAL(MgCONDP(mg));
522         MUTEX_UNLOCK(MgMUTEXP(mg));
523 #endif
524
525 void
526 cond_broadcast(sv)
527         SV *    sv
528         MAGIC * mg = NO_INIT
529 CODE: 
530 #ifdef USE_THREADS
531         if (SvROK(sv))
532             sv = SvRV(sv);
533
534         mg = condpair_magic(sv);
535         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: cond_broadcast %p\n",
536                               thr, sv));
537         MUTEX_LOCK(MgMUTEXP(mg));
538         if (MgOWNER(mg) != thr) {
539             MUTEX_UNLOCK(MgMUTEXP(mg));
540             croak("cond_broadcast for lock that we don't own\n");
541         }
542         COND_BROADCAST(MgCONDP(mg));
543         MUTEX_UNLOCK(MgMUTEXP(mg));
544 #endif
545
546 void
547 list(classname)
548         char *  classname
549     PREINIT:
550         Thread  t;
551         AV *    av;
552         SV **   svp;
553         int     n = 0;
554     PPCODE:
555 #ifdef USE_THREADS
556         av = newAV();
557         /*
558          * Iterate until we have enough dynamic storage for all threads.
559          * We mustn't do any allocation while holding threads_mutex though.
560          */
561         MUTEX_LOCK(&PL_threads_mutex);
562         do {
563             n = PL_nthreads;
564             MUTEX_UNLOCK(&PL_threads_mutex);
565             if (AvFILL(av) < n - 1) {
566                 int i = AvFILL(av);
567                 for (i = AvFILL(av); i < n - 1; i++) {
568                     SV *sv = newSViv(0);        /* fill in tid later */
569                     sv_magic(sv, 0, '~', 0, 0); /* fill in other magic later */
570                     av_push(av, sv_bless(newRV_noinc(sv),
571                                          gv_stashpv(classname, TRUE)));
572         
573                 }
574             }
575             MUTEX_LOCK(&PL_threads_mutex);
576         } while (n < PL_nthreads);
577         n = PL_nthreads;        /* Get the final correct value */
578
579         /*
580          * At this point, there's enough room to fill in av.
581          * Note that we are holding threads_mutex so the list
582          * won't change out from under us but all the remaining
583          * processing is "fast" (no blocking, malloc etc.)
584          */
585         t = thr;
586         svp = AvARRAY(av);
587         do {
588             SV *sv = (SV*)SvRV(*svp);
589             sv_setiv(sv, t->tid);
590             SvMAGIC(sv)->mg_obj = SvREFCNT_inc(t->oursv);
591             SvMAGIC(sv)->mg_flags |= MGf_REFCOUNTED;
592             SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
593             t = t->next;
594             svp++;
595         } while (t != thr);
596         /*  */
597         MUTEX_UNLOCK(&PL_threads_mutex);
598         /* Truncate any unneeded slots in av */
599         av_fill(av, n - 1);
600         /* Finally, push all the new objects onto the stack and drop av */
601         EXTEND(SP, n);
602         for (svp = AvARRAY(av); n > 0; n--, svp++)
603             PUSHs(*svp);
604         (void)sv_2mortal((SV*)av);
605 #endif
606
607
608 MODULE = Thread         PACKAGE = Thread::Signal
609
610 void
611 kill_sighandler_thread()
612     PPCODE:
613         write(sig_pipe[1], "\0", 1);
614         PUSHs(&PL_sv_yes);
615
616 void
617 init_thread_signals()
618     PPCODE:
619         PL_sighandlerp = handle_thread_signal;
620         if (pipe(sig_pipe) == -1)
621             XSRETURN_UNDEF;
622         PUSHs(&PL_sv_yes);
623
624 void
625 await_signal()
626     PREINIT:
627         unsigned char c;
628         SSize_t ret;
629     CODE:
630         do {
631             ret = read(sig_pipe[0], &c, 1);
632         } while (ret == -1 && errno == EINTR);
633         if (ret == -1)
634             croak("panic: await_signal");
635         ST(0) = sv_newmortal();
636         if (ret)
637             sv_setsv(ST(0), c ? PL_psig_ptr[c] : &PL_sv_no);
638         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
639                               "await_signal returning %s\n", SvPEEK(ST(0))););
640
641 MODULE = Thread         PACKAGE = Thread::Specific
642
643 void
644 data(classname = "Thread::Specific")
645         char *  classname
646     PPCODE:
647 #ifdef USE_THREADS
648         if (AvFILL(thr->specific) == -1) {
649             GV *gv = gv_fetchpv("Thread::Specific::FIELDS", TRUE, SVt_PVHV);
650             av_store(thr->specific, 0, newRV((SV*)GvHV(gv)));
651         }
652         XPUSHs(sv_bless(newRV((SV*)thr->specific),gv_stashpv(classname,TRUE)));
653 #endif