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