ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/Coro/State.xs
Revision: 1.267
Committed: Fri Nov 14 06:29:52 2008 UTC (15 years, 6 months ago) by root
Branch: MAIN
Changes since 1.266: +48 -43 lines
Log Message:
one special case less, hopefully

File Contents

# User Rev Content
1 root 1.63 #include "libcoro/coro.c"
2    
3 root 1.146 #define PERL_NO_GET_CONTEXT
4 root 1.198 #define PERL_EXT
5 root 1.146
6 root 1.1 #include "EXTERN.h"
7     #include "perl.h"
8     #include "XSUB.h"
9 root 1.246 #include "perliol.h"
10 root 1.1
11 pcg 1.46 #include "patchlevel.h"
12    
13 root 1.127 #include <stdio.h>
14     #include <errno.h>
15     #include <assert.h>
16 root 1.231
17     #ifdef WIN32
18     # undef setjmp
19     # undef longjmp
20     # undef _exit
21 root 1.232 # define setjmp _setjmp // deep magic, don't ask
22 root 1.231 #else
23     # include <inttypes.h> /* most portable stdint.h */
24     #endif
25 root 1.127
26     #ifdef HAVE_MMAP
27     # include <unistd.h>
28     # include <sys/mman.h>
29     # ifndef MAP_ANONYMOUS
30     # ifdef MAP_ANON
31     # define MAP_ANONYMOUS MAP_ANON
32     # else
33     # undef HAVE_MMAP
34     # endif
35     # endif
36     # include <limits.h>
37     # ifndef PAGESIZE
38     # define PAGESIZE pagesize
39     # define BOOT_PAGESIZE pagesize = sysconf (_SC_PAGESIZE)
40     static long pagesize;
41     # else
42     # define BOOT_PAGESIZE (void)0
43     # endif
44     #else
45     # define PAGESIZE 0
46     # define BOOT_PAGESIZE (void)0
47     #endif
48    
49 root 1.143 #if CORO_USE_VALGRIND
50 root 1.104 # include <valgrind/valgrind.h>
51     #endif
52    
53 root 1.115 /* the maximum number of idle cctx that will be pooled */
54 root 1.254 static int cctx_max_idle = 4;
55 root 1.115
56 root 1.100 #define PERL_VERSION_ATLEAST(a,b,c) \
57     (PERL_REVISION > (a) \
58     || (PERL_REVISION == (a) \
59     && (PERL_VERSION > (b) \
60     || (PERL_VERSION == (b) && PERLSUBVERSION >= (c)))))
61    
62 root 1.102 #if !PERL_VERSION_ATLEAST (5,6,0)
63 pcg 1.46 # ifndef PL_ppaddr
64     # define PL_ppaddr ppaddr
65     # endif
66     # ifndef call_sv
67     # define call_sv perl_call_sv
68     # endif
69     # ifndef get_sv
70     # define get_sv perl_get_sv
71     # endif
72     # ifndef get_cv
73     # define get_cv perl_get_cv
74     # endif
75     # ifndef IS_PADGV
76     # define IS_PADGV(v) 0
77     # endif
78     # ifndef IS_PADCONST
79     # define IS_PADCONST(v) 0
80     # endif
81     #endif
82    
83 root 1.251 /* 5.11 */
84     #ifndef CxHASARGS
85     # define CxHASARGS(cx) (cx)->blk_sub.hasargs
86     #endif
87    
88     /* 5.10.0 */
89     #ifndef SvREFCNT_inc_NN
90     # define SvREFCNT_inc_NN(sv) SvREFCNT_inc (sv)
91     #endif
92    
93 root 1.190 /* 5.8.8 */
94     #ifndef GV_NOTQUAL
95     # define GV_NOTQUAL 0
96     #endif
97 root 1.191 #ifndef newSV
98     # define newSV(l) NEWSV(0,l)
99     #endif
100 root 1.223
101     /* 5.8.7 */
102     #ifndef SvRV_set
103     # define SvRV_set(s,v) SvRV(s) = (v)
104     #endif
105    
106 root 1.78 #if !__i386 && !__x86_64 && !__powerpc && !__m68k && !__alpha && !__mips && !__sparc64
107 root 1.143 # undef CORO_STACKGUARD
108 root 1.78 #endif
109    
110 root 1.143 #ifndef CORO_STACKGUARD
111     # define CORO_STACKGUARD 0
112 root 1.78 #endif
113    
114 root 1.127 /* prefer perl internal functions over our own? */
115 root 1.143 #ifndef CORO_PREFER_PERL_FUNCTIONS
116     # define CORO_PREFER_PERL_FUNCTIONS 0
117 root 1.3 #endif
118    
119 root 1.158 /* The next macros try to return the current stack pointer, in an as
120     * portable way as possible. */
121     #define dSTACKLEVEL volatile char stacklevel
122 root 1.92 #define STACKLEVEL ((void *)&stacklevel)
123 root 1.15
124 root 1.34 #define IN_DESTRUCT (PL_main_cv == Nullcv)
125    
126 root 1.100 #if __GNUC__ >= 3
127     # define attribute(x) __attribute__(x)
128 root 1.194 # define expect(expr,value) __builtin_expect ((expr),(value))
129 root 1.263 # define INLINE static inline
130 root 1.100 #else
131     # define attribute(x)
132 root 1.194 # define expect(expr,value) (expr)
133 root 1.263 # define INLINE static
134 root 1.100 #endif
135    
136 root 1.194 #define expect_false(expr) expect ((expr) != 0, 0)
137     #define expect_true(expr) expect ((expr) != 0, 1)
138    
139 root 1.100 #define NOINLINE attribute ((noinline))
140    
141 root 1.23 #include "CoroAPI.h"
142    
143 pcg 1.55 #ifdef USE_ITHREADS
144 root 1.256
145 root 1.253 static perl_mutex coro_lock;
146     # define LOCK do { MUTEX_LOCK (&coro_lock); } while (0)
147     # define UNLOCK do { MUTEX_UNLOCK (&coro_lock); } while (0)
148 root 1.256 # if CORO_PTHREAD
149     static void *coro_thx;
150     # endif
151    
152 pcg 1.55 #else
153 root 1.256
154 root 1.69 # define LOCK (void)0
155     # define UNLOCK (void)0
156 root 1.256
157 pcg 1.55 #endif
158    
159 root 1.256 # undef LOCK
160     # define LOCK (void)0
161     # undef UNLOCK
162     # define UNLOCK (void)0
163    
164 root 1.136 /* helper storage struct for Coro::AIO */
165 root 1.120 struct io_state
166     {
167 root 1.249 AV *res;
168 root 1.120 int errorno;
169 root 1.255 I32 laststype; /* U16 in 5.10.0 */
170 root 1.120 int laststatval;
171     Stat_t statcache;
172     };
173    
174 root 1.246 static double (*nvtime)(); /* so why doesn't it take void? */
175    
176 root 1.254 static U32 cctx_gen;
177     static size_t cctx_stacksize = CORO_STACKSIZE;
178 root 1.23 static struct CoroAPI coroapi;
179 pcg 1.56 static AV *main_mainstack; /* used to differentiate between $main and others */
180 root 1.148 static JMPENV *main_top_env;
181 root 1.88 static HV *coro_state_stash, *coro_stash;
182 root 1.252 static volatile SV *coro_mortal; /* will be freed/thrown after next transfer */
183 root 1.260 static volatile struct coro *transfer_next;
184    
185     struct transfer_args
186     {
187     struct coro *prev, *next;
188     };
189 root 1.23
190 root 1.189 static GV *irsgv; /* $/ */
191     static GV *stdoutgv; /* *STDOUT */
192 root 1.214 static SV *rv_diehook;
193     static SV *rv_warnhook;
194 root 1.200 static HV *hv_sig; /* %SIG */
195 root 1.178
196 root 1.159 /* async_pool helper stuff */
197     static SV *sv_pool_rss;
198     static SV *sv_pool_size;
199     static AV *av_async_pool;
200    
201 root 1.233 /* Coro::AnyEvent */
202     static SV *sv_activity;
203    
204 root 1.211 static struct coro_cctx *cctx_first;
205     static int cctx_count, cctx_idle;
206 root 1.107
207 root 1.165 enum {
208 root 1.167 CC_MAPPED = 0x01,
209     CC_NOREUSE = 0x02, /* throw this away after tracing */
210     CC_TRACE = 0x04,
211     CC_TRACE_SUB = 0x08, /* trace sub calls */
212     CC_TRACE_LINE = 0x10, /* trace each statement */
213     CC_TRACE_ALL = CC_TRACE_SUB | CC_TRACE_LINE,
214 root 1.165 };
215    
216 root 1.92 /* this is a structure representing a c-level coroutine */
217 root 1.106 typedef struct coro_cctx {
218     struct coro_cctx *next;
219 root 1.15
220 root 1.93 /* the stack */
221 root 1.15 void *sptr;
222 root 1.145 size_t ssize;
223 root 1.89
224     /* cpu state */
225 root 1.132 void *idle_sp; /* sp of top-level transfer/schedule/cede call */
226     JMPENV *idle_te; /* same as idle_sp, but for top_env, TODO: remove once stable */
227 root 1.93 JMPENV *top_env;
228 root 1.89 coro_context cctx;
229 root 1.104
230 root 1.254 U32 gen;
231 root 1.143 #if CORO_USE_VALGRIND
232 root 1.104 int valgrind_id;
233     #endif
234 root 1.165 unsigned char flags;
235 root 1.106 } coro_cctx;
236 root 1.15
237 root 1.111 enum {
238 root 1.133 CF_RUNNING = 0x0001, /* coroutine is running */
239     CF_READY = 0x0002, /* coroutine is ready */
240     CF_NEW = 0x0004, /* has never been switched to */
241     CF_DESTROYED = 0x0008, /* coroutine data has been freed */
242 root 1.111 };
243    
244 root 1.198 /* the structure where most of the perl state is stored, overlaid on the cxstack */
245     typedef struct {
246     SV *defsv;
247     AV *defav;
248     SV *errsv;
249     SV *irsgv;
250     #define VAR(name,type) type name;
251     # include "state.h"
252     #undef VAR
253     } perl_slots;
254    
255     #define SLOT_COUNT ((sizeof (perl_slots) + sizeof (PERL_CONTEXT) - 1) / sizeof (PERL_CONTEXT))
256    
257 root 1.92 /* this is a structure representing a perl-level coroutine */
258 root 1.1 struct coro {
259 root 1.92 /* the c coroutine allocated to this perl coroutine, if any */
260 root 1.106 coro_cctx *cctx;
261 root 1.92
262 root 1.198 /* process data */
263     AV *mainstack;
264     perl_slots *slot; /* basically the saved sp */
265    
266 root 1.203 AV *args; /* data associated with this coroutine (initial args) */
267     int refcnt; /* coroutines are refcounted, yes */
268     int flags; /* CF_ flags */
269     HV *hv; /* the perl hash associated with this coro, if any */
270 root 1.92
271 root 1.172 /* statistics */
272 root 1.181 int usecount; /* number of transfers to this coro */
273 root 1.172
274 root 1.87 /* coro process data */
275     int prio;
276 root 1.203 SV *throw; /* exception to be thrown */
277 root 1.181
278     /* async_pool */
279 root 1.184 SV *saved_deffh;
280 root 1.151
281     /* linked list */
282     struct coro *next, *prev;
283 root 1.1 };
284    
285     typedef struct coro *Coro__State;
286     typedef struct coro *Coro__State_or_hashref;
287    
288 root 1.137 /** Coro ********************************************************************/
289    
290     #define PRIO_MAX 3
291     #define PRIO_HIGH 1
292     #define PRIO_NORMAL 0
293     #define PRIO_LOW -1
294     #define PRIO_IDLE -3
295     #define PRIO_MIN -4
296    
297     /* for Coro.pm */
298     static SV *coro_current;
299 root 1.233 static SV *coro_readyhook;
300 root 1.257 static AV *coro_ready [PRIO_MAX - PRIO_MIN + 1];
301 root 1.137 static int coro_nready;
302 root 1.153 static struct coro *coro_first;
303 root 1.137
304     /** lowlevel stuff **********************************************************/
305    
306 root 1.199 static SV *
307 root 1.213 coro_get_sv (pTHX_ const char *name, int create)
308 root 1.199 {
309 root 1.228 #if PERL_VERSION_ATLEAST (5,10,0)
310 root 1.199 /* silence stupid and wrong 5.10 warning that I am unable to switch off */
311     get_sv (name, create);
312     #endif
313     return get_sv (name, create);
314     }
315    
316 root 1.200 static AV *
317 root 1.213 coro_get_av (pTHX_ const char *name, int create)
318 root 1.199 {
319 root 1.228 #if PERL_VERSION_ATLEAST (5,10,0)
320 root 1.199 /* silence stupid and wrong 5.10 warning that I am unable to switch off */
321     get_av (name, create);
322     #endif
323     return get_av (name, create);
324     }
325    
326 root 1.200 static HV *
327 root 1.213 coro_get_hv (pTHX_ const char *name, int create)
328 root 1.200 {
329 root 1.228 #if PERL_VERSION_ATLEAST (5,10,0)
330 root 1.200 /* silence stupid and wrong 5.10 warning that I am unable to switch off */
331     get_hv (name, create);
332     #endif
333     return get_hv (name, create);
334     }
335    
336 root 1.77 static AV *
337 root 1.146 coro_clone_padlist (pTHX_ CV *cv)
338 root 1.77 {
339     AV *padlist = CvPADLIST (cv);
340     AV *newpadlist, *newpad;
341 root 1.3
342     newpadlist = newAV ();
343     AvREAL_off (newpadlist);
344 root 1.228 #if PERL_VERSION_ATLEAST (5,10,0)
345 root 1.100 Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1);
346     #else
347 root 1.77 Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1, 1);
348 root 1.79 #endif
349 root 1.77 newpad = (AV *)AvARRAY (padlist)[AvFILLp (padlist)];
350     --AvFILLp (padlist);
351 root 1.3
352 root 1.249 av_store (newpadlist, 0, SvREFCNT_inc_NN (*av_fetch (padlist, 0, FALSE)));
353 root 1.77 av_store (newpadlist, 1, (SV *)newpad);
354 root 1.3
355     return newpadlist;
356     }
357    
358 root 1.77 static void
359 root 1.146 free_padlist (pTHX_ AV *padlist)
360 root 1.3 {
361     /* may be during global destruction */
362 pcg 1.50 if (SvREFCNT (padlist))
363 root 1.3 {
364 pcg 1.50 I32 i = AvFILLp (padlist);
365 root 1.3 while (i >= 0)
366     {
367 pcg 1.50 SV **svp = av_fetch (padlist, i--, FALSE);
368     if (svp)
369     {
370     SV *sv;
371     while (&PL_sv_undef != (sv = av_pop ((AV *)*svp)))
372     SvREFCNT_dec (sv);
373    
374     SvREFCNT_dec (*svp);
375     }
376 root 1.3 }
377    
378 pcg 1.50 SvREFCNT_dec ((SV*)padlist);
379     }
380     }
381    
382 root 1.77 static int
383 pcg 1.54 coro_cv_free (pTHX_ SV *sv, MAGIC *mg)
384 pcg 1.50 {
385     AV *padlist;
386     AV *av = (AV *)mg->mg_obj;
387    
388     /* casting is fun. */
389     while (&PL_sv_undef != (SV *)(padlist = (AV *)av_pop (av)))
390 root 1.146 free_padlist (aTHX_ padlist);
391 root 1.61
392 root 1.245 SvREFCNT_dec (av); /* sv_magicext increased the refcount */
393 root 1.244
394 root 1.76 return 0;
395 root 1.3 }
396 pcg 1.50
397 root 1.214 #define CORO_MAGIC_type_cv PERL_MAGIC_ext
398     #define CORO_MAGIC_type_state PERL_MAGIC_ext
399 pcg 1.50
400 root 1.214 static MGVTBL coro_cv_vtbl = {
401     0, 0, 0, 0,
402     coro_cv_free
403     };
404 root 1.3
405 root 1.253 #define CORO_MAGIC(sv, type) \
406     SvMAGIC (sv) \
407     ? SvMAGIC (sv)->mg_type == type \
408     ? SvMAGIC (sv) \
409     : mg_find (sv, type) \
410     : 0
411 root 1.109
412 root 1.214 #define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv)
413     #define CORO_MAGIC_state(sv) CORO_MAGIC (((SV *)(sv)), CORO_MAGIC_type_state)
414    
415 root 1.263 INLINE struct coro *
416 root 1.169 SvSTATE_ (pTHX_ SV *coro)
417     {
418     HV *stash;
419     MAGIC *mg;
420    
421     if (SvROK (coro))
422     coro = SvRV (coro);
423    
424 root 1.194 if (expect_false (SvTYPE (coro) != SVt_PVHV))
425 root 1.172 croak ("Coro::State object required");
426    
427 root 1.169 stash = SvSTASH (coro);
428 root 1.194 if (expect_false (stash != coro_stash && stash != coro_state_stash))
429 root 1.169 {
430     /* very slow, but rare, check */
431     if (!sv_derived_from (sv_2mortal (newRV_inc (coro)), "Coro::State"))
432     croak ("Coro::State object required");
433     }
434    
435 root 1.214 mg = CORO_MAGIC_state (coro);
436 root 1.169 return (struct coro *)mg->mg_ptr;
437     }
438    
439     #define SvSTATE(sv) SvSTATE_ (aTHX_ (sv))
440    
441 root 1.7 /* the next two functions merely cache the padlists */
442 root 1.77 static void
443 root 1.146 get_padlist (pTHX_ CV *cv)
444 root 1.3 {
445 root 1.214 MAGIC *mg = CORO_MAGIC_cv (cv);
446 root 1.109 AV *av;
447 root 1.4
448 root 1.194 if (expect_true (mg && AvFILLp ((av = (AV *)mg->mg_obj)) >= 0))
449 root 1.109 CvPADLIST (cv) = (AV *)AvARRAY (av)[AvFILLp (av)--];
450 root 1.4 else
451 root 1.77 {
452 root 1.143 #if CORO_PREFER_PERL_FUNCTIONS
453 root 1.244 /* this is probably cleaner? but also slower! */
454     /* in practise, it seems to be less stable */
455 root 1.98 CV *cp = Perl_cv_clone (cv);
456 root 1.77 CvPADLIST (cv) = CvPADLIST (cp);
457     CvPADLIST (cp) = 0;
458     SvREFCNT_dec (cp);
459     #else
460 root 1.146 CvPADLIST (cv) = coro_clone_padlist (aTHX_ cv);
461 root 1.77 #endif
462     }
463 root 1.4 }
464    
465 root 1.77 static void
466 root 1.146 put_padlist (pTHX_ CV *cv)
467 root 1.4 {
468 root 1.214 MAGIC *mg = CORO_MAGIC_cv (cv);
469 root 1.109 AV *av;
470 root 1.7
471 root 1.194 if (expect_false (!mg))
472 root 1.214 mg = sv_magicext ((SV *)cv, (SV *)newAV (), CORO_MAGIC_type_cv, &coro_cv_vtbl, 0, 0);
473 root 1.7
474 root 1.109 av = (AV *)mg->mg_obj;
475    
476 root 1.194 if (expect_false (AvFILLp (av) >= AvMAX (av)))
477 root 1.109 av_extend (av, AvMAX (av) + 1);
478    
479     AvARRAY (av)[++AvFILLp (av)] = (SV *)CvPADLIST (cv);
480 root 1.7 }
481    
482 root 1.137 /** load & save, init *******************************************************/
483    
484 root 1.7 static void
485 root 1.146 load_perl (pTHX_ Coro__State c)
486 root 1.7 {
487 root 1.198 perl_slots *slot = c->slot;
488     c->slot = 0;
489    
490     PL_mainstack = c->mainstack;
491 root 1.7
492 root 1.198 GvSV (PL_defgv) = slot->defsv;
493     GvAV (PL_defgv) = slot->defav;
494     GvSV (PL_errgv) = slot->errsv;
495     GvSV (irsgv) = slot->irsgv;
496    
497     #define VAR(name,type) PL_ ## name = slot->name;
498     # include "state.h"
499     #undef VAR
500 root 1.7
501     {
502     dSP;
503 root 1.198
504 root 1.7 CV *cv;
505    
506     /* now do the ugly restore mess */
507 root 1.194 while (expect_true (cv = (CV *)POPs))
508 root 1.7 {
509 root 1.146 put_padlist (aTHX_ cv); /* mark this padlist as available */
510 root 1.109 CvDEPTH (cv) = PTR2IV (POPs);
511     CvPADLIST (cv) = (AV *)POPs;
512 root 1.7 }
513    
514     PUTBACK;
515     }
516     }
517    
518 root 1.3 static void
519 root 1.146 save_perl (pTHX_ Coro__State c)
520 root 1.3 {
521     {
522     dSP;
523     I32 cxix = cxstack_ix;
524 root 1.11 PERL_CONTEXT *ccstk = cxstack;
525 root 1.3 PERL_SI *top_si = PL_curstackinfo;
526    
527     /*
528     * the worst thing you can imagine happens first - we have to save
529     * (and reinitialize) all cv's in the whole callchain :(
530     */
531    
532 root 1.157 XPUSHs (Nullsv);
533 root 1.3 /* this loop was inspired by pp_caller */
534     for (;;)
535     {
536 root 1.194 while (expect_true (cxix >= 0))
537 root 1.3 {
538 root 1.4 PERL_CONTEXT *cx = &ccstk[cxix--];
539 root 1.3
540 root 1.194 if (expect_true (CxTYPE (cx) == CXt_SUB || CxTYPE (cx) == CXt_FORMAT))
541 root 1.3 {
542     CV *cv = cx->blk_sub.cv;
543 root 1.109
544 root 1.194 if (expect_true (CvDEPTH (cv)))
545 root 1.3 {
546 root 1.109 EXTEND (SP, 3);
547 root 1.117 PUSHs ((SV *)CvPADLIST (cv));
548 root 1.233 PUSHs (INT2PTR (SV *, (IV)CvDEPTH (cv)));
549 root 1.3 PUSHs ((SV *)cv);
550    
551 root 1.109 CvDEPTH (cv) = 0;
552 root 1.146 get_padlist (aTHX_ cv);
553 root 1.3 }
554     }
555     }
556    
557 root 1.194 if (expect_true (top_si->si_type == PERLSI_MAIN))
558 root 1.3 break;
559    
560     top_si = top_si->si_prev;
561 root 1.158 ccstk = top_si->si_cxstack;
562     cxix = top_si->si_cxix;
563 root 1.3 }
564    
565     PUTBACK;
566     }
567    
568 root 1.198 /* allocate some space on the context stack for our purposes */
569 root 1.202 /* we manually unroll here, as usually 2 slots is enough */
570     if (SLOT_COUNT >= 1) CXINC;
571     if (SLOT_COUNT >= 2) CXINC;
572     if (SLOT_COUNT >= 3) CXINC;
573 root 1.198 {
574     int i;
575     for (i = 3; i < SLOT_COUNT; ++i)
576     CXINC;
577     }
578 root 1.202 cxstack_ix -= SLOT_COUNT; /* undo allocation */
579 root 1.198
580     c->mainstack = PL_mainstack;
581    
582     {
583     perl_slots *slot = c->slot = (perl_slots *)(cxstack + cxstack_ix + 1);
584    
585     slot->defav = GvAV (PL_defgv);
586     slot->defsv = DEFSV;
587     slot->errsv = ERRSV;
588     slot->irsgv = GvSV (irsgv);
589    
590     #define VAR(name,type) slot->name = PL_ ## name;
591     # include "state.h"
592     #undef VAR
593     }
594 root 1.13 }
595    
596     /*
597     * allocate various perl stacks. This is an exact copy
598     * of perl.c:init_stacks, except that it uses less memory
599 pcg 1.52 * on the (sometimes correct) assumption that coroutines do
600     * not usually need a lot of stackspace.
601 root 1.13 */
602 root 1.204 #if CORO_PREFER_PERL_FUNCTIONS
603 root 1.126 # define coro_init_stacks init_stacks
604     #else
605 root 1.77 static void
606 root 1.146 coro_init_stacks (pTHX)
607 root 1.13 {
608 root 1.198 PL_curstackinfo = new_stackinfo(32, 8);
609 root 1.13 PL_curstackinfo->si_type = PERLSI_MAIN;
610     PL_curstack = PL_curstackinfo->si_stack;
611     PL_mainstack = PL_curstack; /* remember in case we switch stacks */
612    
613     PL_stack_base = AvARRAY(PL_curstack);
614     PL_stack_sp = PL_stack_base;
615     PL_stack_max = PL_stack_base + AvMAX(PL_curstack);
616    
617 root 1.198 New(50,PL_tmps_stack,32,SV*);
618 root 1.13 PL_tmps_floor = -1;
619     PL_tmps_ix = -1;
620 root 1.198 PL_tmps_max = 32;
621 root 1.13
622 root 1.154 New(54,PL_markstack,16,I32);
623 root 1.13 PL_markstack_ptr = PL_markstack;
624 root 1.154 PL_markstack_max = PL_markstack + 16;
625 root 1.13
626 pcg 1.46 #ifdef SET_MARK_OFFSET
627 root 1.13 SET_MARK_OFFSET;
628 pcg 1.46 #endif
629 root 1.13
630 root 1.198 New(54,PL_scopestack,8,I32);
631 root 1.13 PL_scopestack_ix = 0;
632 root 1.198 PL_scopestack_max = 8;
633 root 1.13
634 root 1.198 New(54,PL_savestack,24,ANY);
635 root 1.13 PL_savestack_ix = 0;
636 root 1.198 PL_savestack_max = 24;
637 root 1.13
638 root 1.228 #if !PERL_VERSION_ATLEAST (5,10,0)
639 root 1.156 New(54,PL_retstack,4,OP*);
640 root 1.13 PL_retstack_ix = 0;
641 root 1.156 PL_retstack_max = 4;
642 root 1.71 #endif
643 root 1.3 }
644 root 1.127 #endif
645 root 1.1
646 root 1.7 /*
647     * destroy the stacks, the callchain etc...
648     */
649 root 1.77 static void
650 root 1.253 coro_destruct_stacks (pTHX)
651 root 1.1 {
652 root 1.4 while (PL_curstackinfo->si_next)
653     PL_curstackinfo = PL_curstackinfo->si_next;
654    
655     while (PL_curstackinfo)
656     {
657     PERL_SI *p = PL_curstackinfo->si_prev;
658    
659 root 1.34 if (!IN_DESTRUCT)
660 root 1.126 SvREFCNT_dec (PL_curstackinfo->si_stack);
661 root 1.7
662 pcg 1.57 Safefree (PL_curstackinfo->si_cxstack);
663     Safefree (PL_curstackinfo);
664 root 1.4 PL_curstackinfo = p;
665     }
666    
667 pcg 1.57 Safefree (PL_tmps_stack);
668     Safefree (PL_markstack);
669     Safefree (PL_scopestack);
670     Safefree (PL_savestack);
671 root 1.228 #if !PERL_VERSION_ATLEAST (5,10,0)
672 pcg 1.57 Safefree (PL_retstack);
673 root 1.71 #endif
674 root 1.1 }
675    
676 root 1.152 static size_t
677 root 1.171 coro_rss (pTHX_ struct coro *coro)
678 root 1.152 {
679 root 1.183 size_t rss = sizeof (*coro);
680 root 1.152
681     if (coro->mainstack)
682     {
683 root 1.198 perl_slots tmp_slot;
684     perl_slots *slot;
685    
686 root 1.153 if (coro->flags & CF_RUNNING)
687     {
688 root 1.198 slot = &tmp_slot;
689    
690     #define VAR(name,type) slot->name = PL_ ## name;
691 root 1.153 # include "state.h"
692     #undef VAR
693     }
694 root 1.198 else
695     slot = coro->slot;
696 root 1.153
697 root 1.245 if (slot)
698     {
699     rss += sizeof (slot->curstackinfo);
700     rss += (slot->curstackinfo->si_cxmax + 1) * sizeof (PERL_CONTEXT);
701     rss += sizeof (SV) + sizeof (struct xpvav) + (1 + AvMAX (slot->curstack)) * sizeof (SV *);
702     rss += slot->tmps_max * sizeof (SV *);
703     rss += (slot->markstack_max - slot->markstack_ptr) * sizeof (I32);
704     rss += slot->scopestack_max * sizeof (I32);
705     rss += slot->savestack_max * sizeof (ANY);
706 root 1.152
707 root 1.228 #if !PERL_VERSION_ATLEAST (5,10,0)
708 root 1.245 rss += slot->retstack_max * sizeof (OP *);
709 root 1.152 #endif
710 root 1.245 }
711 root 1.152 }
712    
713     return rss;
714     }
715    
716 root 1.265 /** set stacklevel support **************************************************/
717    
718     /* we sometimes need to create the effect of pp_set_stacklevel calling us */
719     #define SSL_HEAD (void)0
720 root 1.267 /* we sometimes need to create the effect of leaving via pp_set_stacklevel */
721 root 1.265 #define SSL_TAIL set_stacklevel_tail (aTHX)
722    
723     INLINE void
724     set_stacklevel_tail (pTHX)
725     {
726     dSP;
727 root 1.266 SV **bot = SP;
728    
729 root 1.265 int gimme = GIMME_V;
730    
731 root 1.266 /* make sure we put something on the stack in scalar context */
732 root 1.265 if (gimme == G_SCALAR)
733 root 1.266 {
734     if (sp == bot)
735     XPUSHs (&PL_sv_undef);
736    
737     SP = bot + 1;
738     }
739 root 1.265
740     PUTBACK;
741     }
742    
743 root 1.137 /** coroutine stack handling ************************************************/
744    
745 root 1.214 static int (*orig_sigelem_get) (pTHX_ SV *sv, MAGIC *mg);
746 root 1.220 static int (*orig_sigelem_set) (pTHX_ SV *sv, MAGIC *mg);
747 root 1.239 static int (*orig_sigelem_clr) (pTHX_ SV *sv, MAGIC *mg);
748 root 1.214
749 root 1.238 /* apparently < 5.8.8 */
750     #ifndef MgPV_nolen_const
751     #define MgPV_nolen_const(mg) (((((int)(mg)->mg_len)) == HEf_SVKEY) ? \
752 root 1.241 SvPV_nolen((SV*)((mg)->mg_ptr)) : \
753 root 1.238 (const char*)(mg)->mg_ptr)
754     #endif
755    
756 root 1.214 /*
757     * This overrides the default magic get method of %SIG elements.
758     * The original one doesn't provide for reading back of PL_diehook/PL_warnhook
759     * and instead of tryign to save and restore the hash elements, we just provide
760     * readback here.
761     * We only do this when the hook is != 0, as they are often set to 0 temporarily,
762     * not expecting this to actually change the hook. This is a potential problem
763     * when a schedule happens then, but we ignore this.
764     */
765     static int
766     coro_sigelem_get (pTHX_ SV *sv, MAGIC *mg)
767     {
768     const char *s = MgPV_nolen_const (mg);
769    
770     if (*s == '_')
771     {
772 root 1.239 SV **svp = 0;
773    
774     if (strEQ (s, "__DIE__" )) svp = &PL_diehook;
775     if (strEQ (s, "__WARN__")) svp = &PL_warnhook;
776    
777     if (svp)
778     {
779     sv_setsv (sv, *svp ? *svp : &PL_sv_undef);
780     return 0;
781     }
782 root 1.214 }
783    
784 root 1.220 return orig_sigelem_get ? orig_sigelem_get (aTHX_ sv, mg) : 0;
785     }
786    
787     static int
788 root 1.239 coro_sigelem_clr (pTHX_ SV *sv, MAGIC *mg)
789     {
790     const char *s = MgPV_nolen_const (mg);
791    
792     if (*s == '_')
793     {
794     SV **svp = 0;
795    
796     if (strEQ (s, "__DIE__" )) svp = &PL_diehook;
797     if (strEQ (s, "__WARN__")) svp = &PL_warnhook;
798    
799     if (svp)
800     {
801     SV *old = *svp;
802     *svp = 0;
803     SvREFCNT_dec (old);
804     return 0;
805     }
806     }
807    
808     return orig_sigelem_clr ? orig_sigelem_clr (aTHX_ sv, mg) : 0;
809     }
810    
811     static int
812 root 1.220 coro_sigelem_set (pTHX_ SV *sv, MAGIC *mg)
813     {
814     const char *s = MgPV_nolen_const (mg);
815    
816     if (*s == '_')
817     {
818     SV **svp = 0;
819    
820     if (strEQ (s, "__DIE__" )) svp = &PL_diehook;
821     if (strEQ (s, "__WARN__")) svp = &PL_warnhook;
822    
823     if (svp)
824     {
825     SV *old = *svp;
826     *svp = newSVsv (sv);
827     SvREFCNT_dec (old);
828 root 1.231 return 0;
829 root 1.220 }
830     }
831    
832     return orig_sigelem_set ? orig_sigelem_set (aTHX_ sv, mg) : 0;
833 root 1.214 }
834    
835 root 1.13 static void
836 root 1.179 coro_setup (pTHX_ struct coro *coro)
837 root 1.13 {
838 root 1.89 /*
839     * emulate part of the perl startup here.
840     */
841 root 1.146 coro_init_stacks (aTHX);
842 root 1.15
843 root 1.169 PL_runops = RUNOPS_DEFAULT;
844 root 1.117 PL_curcop = &PL_compiling;
845     PL_in_eval = EVAL_NULL;
846 root 1.142 PL_comppad = 0;
847 root 1.117 PL_curpm = 0;
848 root 1.196 PL_curpad = 0;
849 root 1.117 PL_localizing = 0;
850     PL_dirty = 0;
851     PL_restartop = 0;
852 root 1.229 #if PERL_VERSION_ATLEAST (5,10,0)
853 root 1.228 PL_parser = 0;
854     #endif
855 root 1.214
856     /* recreate the die/warn hooks */
857 root 1.220 PL_diehook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__DIE__" , sizeof ("__DIE__" ) - 1, 1), rv_diehook );
858     PL_warnhook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__WARN__", sizeof ("__WARN__") - 1, 1), rv_warnhook);
859 root 1.178
860 root 1.191 GvSV (PL_defgv) = newSV (0);
861 root 1.178 GvAV (PL_defgv) = coro->args; coro->args = 0;
862 root 1.191 GvSV (PL_errgv) = newSV (0);
863 root 1.180 GvSV (irsgv) = newSVpvn ("\n", 1); sv_magic (GvSV (irsgv), (SV *)irsgv, PERL_MAGIC_sv, "/", 0);
864 root 1.179 PL_rs = newSVsv (GvSV (irsgv));
865 root 1.249 PL_defoutgv = (GV *)SvREFCNT_inc_NN (stdoutgv);
866 root 1.103
867 root 1.102 {
868     dSP;
869 root 1.260 UNOP myop;
870 root 1.102
871 root 1.260 Zero (&myop, 1, UNOP);
872 root 1.102 myop.op_next = Nullop;
873     myop.op_flags = OPf_WANT_VOID;
874 root 1.89
875 root 1.102 PUSHMARK (SP);
876 root 1.192 XPUSHs (sv_2mortal (av_shift (GvAV (PL_defgv))));
877 root 1.102 PUTBACK;
878 root 1.120 PL_op = (OP *)&myop;
879 root 1.102 PL_op = PL_ppaddr[OP_ENTERSUB](aTHX);
880     SPAGAIN;
881 root 1.117 }
882 root 1.210
883     /* this newly created coroutine might be run on an existing cctx which most
884 root 1.265 * likely was suspended in set_stacklevel, called from pp_set_stacklevel,
885     * so we have to emulate entering pp_set_stacklevel here.
886 root 1.210 */
887 root 1.264 SSL_HEAD;
888 root 1.13 }
889    
890     static void
891 root 1.253 coro_destruct (pTHX_ struct coro *coro)
892 root 1.178 {
893     if (!IN_DESTRUCT)
894     {
895     /* restore all saved variables and stuff */
896     LEAVE_SCOPE (0);
897     assert (PL_tmps_floor == -1);
898    
899     /* free all temporaries */
900     FREETMPS;
901     assert (PL_tmps_ix == -1);
902    
903     /* unwind all extra stacks */
904     POPSTACK_TO (PL_mainstack);
905    
906     /* unwind main stack */
907     dounwind (-1);
908     }
909    
910     SvREFCNT_dec (GvSV (PL_defgv));
911     SvREFCNT_dec (GvAV (PL_defgv));
912     SvREFCNT_dec (GvSV (PL_errgv));
913 root 1.180 SvREFCNT_dec (PL_defoutgv);
914 root 1.178 SvREFCNT_dec (PL_rs);
915     SvREFCNT_dec (GvSV (irsgv));
916    
917 root 1.198 SvREFCNT_dec (PL_diehook);
918     SvREFCNT_dec (PL_warnhook);
919    
920 root 1.184 SvREFCNT_dec (coro->saved_deffh);
921 root 1.196 SvREFCNT_dec (coro->throw);
922 root 1.181
923 root 1.253 coro_destruct_stacks (aTHX);
924 root 1.178 }
925    
926 root 1.263 INLINE void
927 root 1.146 free_coro_mortal (pTHX)
928 root 1.13 {
929 root 1.194 if (expect_true (coro_mortal))
930 root 1.15 {
931 root 1.89 SvREFCNT_dec (coro_mortal);
932     coro_mortal = 0;
933     }
934 root 1.13 }
935    
936 root 1.165 static int
937 root 1.169 runops_trace (pTHX)
938 root 1.165 {
939     COP *oldcop = 0;
940 root 1.167 int oldcxix = -2;
941 root 1.169 struct coro *coro = SvSTATE (coro_current); /* trace cctx is tied to specific coro */
942     coro_cctx *cctx = coro->cctx;
943 root 1.165
944     while ((PL_op = CALL_FPTR (PL_op->op_ppaddr) (aTHX)))
945     {
946     PERL_ASYNC_CHECK ();
947    
948 root 1.173 if (cctx->flags & CC_TRACE_ALL)
949 root 1.167 {
950 root 1.173 if (PL_op->op_type == OP_LEAVESUB && cctx->flags & CC_TRACE_SUB)
951     {
952     PERL_CONTEXT *cx = &cxstack[cxstack_ix];
953     SV **bot, **top;
954     AV *av = newAV (); /* return values */
955     SV **cb;
956     dSP;
957 root 1.167
958 root 1.173 GV *gv = CvGV (cx->blk_sub.cv);
959     SV *fullname = sv_2mortal (newSV (0));
960     if (isGV (gv))
961     gv_efullname3 (fullname, gv, 0);
962    
963     bot = PL_stack_base + cx->blk_oldsp + 1;
964     top = cx->blk_gimme == G_ARRAY ? SP + 1
965     : cx->blk_gimme == G_SCALAR ? bot + 1
966     : bot;
967 root 1.167
968 root 1.193 av_extend (av, top - bot);
969 root 1.173 while (bot < top)
970 root 1.249 av_push (av, SvREFCNT_inc_NN (*bot++));
971 root 1.167
972 root 1.173 PL_runops = RUNOPS_DEFAULT;
973 root 1.167 ENTER;
974     SAVETMPS;
975     EXTEND (SP, 3);
976 root 1.173 PUSHMARK (SP);
977     PUSHs (&PL_sv_no);
978     PUSHs (fullname);
979     PUSHs (sv_2mortal (newRV_noinc ((SV *)av)));
980     PUTBACK;
981 root 1.212 cb = hv_fetch ((HV *)SvRV (coro_current), "_trace_sub_cb", sizeof ("_trace_sub_cb") - 1, 0);
982 root 1.173 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
983     SPAGAIN;
984     FREETMPS;
985     LEAVE;
986     PL_runops = runops_trace;
987     }
988    
989     if (oldcop != PL_curcop)
990     {
991     oldcop = PL_curcop;
992 root 1.167
993 root 1.173 if (PL_curcop != &PL_compiling)
994 root 1.167 {
995 root 1.173 SV **cb;
996    
997     if (oldcxix != cxstack_ix && cctx->flags & CC_TRACE_SUB)
998     {
999     PERL_CONTEXT *cx = &cxstack[cxstack_ix];
1000    
1001     if (CxTYPE (cx) == CXt_SUB && oldcxix < cxstack_ix)
1002     {
1003     runops_proc_t old_runops = PL_runops;
1004     dSP;
1005     GV *gv = CvGV (cx->blk_sub.cv);
1006     SV *fullname = sv_2mortal (newSV (0));
1007    
1008     if (isGV (gv))
1009     gv_efullname3 (fullname, gv, 0);
1010    
1011     PL_runops = RUNOPS_DEFAULT;
1012     ENTER;
1013     SAVETMPS;
1014     EXTEND (SP, 3);
1015     PUSHMARK (SP);
1016     PUSHs (&PL_sv_yes);
1017     PUSHs (fullname);
1018 root 1.223 PUSHs (CxHASARGS (cx) ? sv_2mortal (newRV_inc ((SV *)cx->blk_sub.argarray)) : &PL_sv_undef);
1019 root 1.173 PUTBACK;
1020 root 1.212 cb = hv_fetch ((HV *)SvRV (coro_current), "_trace_sub_cb", sizeof ("_trace_sub_cb") - 1, 0);
1021 root 1.173 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
1022     SPAGAIN;
1023     FREETMPS;
1024     LEAVE;
1025     PL_runops = runops_trace;
1026     }
1027    
1028     oldcxix = cxstack_ix;
1029     }
1030 root 1.167
1031 root 1.173 if (cctx->flags & CC_TRACE_LINE)
1032 root 1.167 {
1033 root 1.173 dSP;
1034 root 1.167
1035 root 1.173 PL_runops = RUNOPS_DEFAULT;
1036     ENTER;
1037     SAVETMPS;
1038     EXTEND (SP, 3);
1039     PL_runops = RUNOPS_DEFAULT;
1040 root 1.167 PUSHMARK (SP);
1041 root 1.173 PUSHs (sv_2mortal (newSVpv (OutCopFILE (oldcop), 0)));
1042     PUSHs (sv_2mortal (newSViv (CopLINE (oldcop))));
1043 root 1.167 PUTBACK;
1044 root 1.212 cb = hv_fetch ((HV *)SvRV (coro_current), "_trace_line_cb", sizeof ("_trace_line_cb") - 1, 0);
1045 root 1.169 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
1046 root 1.167 SPAGAIN;
1047 root 1.173 FREETMPS;
1048     LEAVE;
1049     PL_runops = runops_trace;
1050 root 1.167 }
1051 root 1.169 }
1052 root 1.167 }
1053 root 1.165 }
1054     }
1055    
1056     TAINT_NOT;
1057     return 0;
1058     }
1059    
1060 root 1.260 static void
1061     prepare_set_stacklevel (struct transfer_args *ta, struct coro_cctx *cctx)
1062     {
1063     ta->prev = (struct coro *)cctx;
1064     ta->next = 0;
1065     }
1066    
1067 root 1.120 /* inject a fake call to Coro::State::_cctx_init into the execution */
1068 root 1.150 /* _cctx_init should be careful, as it could be called at almost any time */
1069     /* during execution of a perl program */
1070 root 1.259 /* also initialises PL_top_env */
1071 root 1.100 static void NOINLINE
1072 root 1.201 cctx_prepare (pTHX_ coro_cctx *cctx)
1073 root 1.99 {
1074     dSP;
1075 root 1.260 UNOP myop;
1076 root 1.99
1077 root 1.165 PL_top_env = &PL_start_env;
1078    
1079     if (cctx->flags & CC_TRACE)
1080 root 1.169 PL_runops = runops_trace;
1081 root 1.165
1082 root 1.260 Zero (&myop, 1, UNOP);
1083     myop.op_next = PL_op;
1084 root 1.120 myop.op_flags = OPf_WANT_VOID | OPf_STACKED;
1085 root 1.102
1086     PUSHMARK (SP);
1087 root 1.120 EXTEND (SP, 2);
1088 root 1.260 PUSHs (sv_2mortal (newSViv ((IV)cctx)));
1089 root 1.120 PUSHs ((SV *)get_cv ("Coro::State::_cctx_init", FALSE));
1090 root 1.99 PUTBACK;
1091 root 1.120 PL_op = (OP *)&myop;
1092     PL_op = PL_ppaddr[OP_ENTERSUB](aTHX);
1093 root 1.99 SPAGAIN;
1094     }
1095    
1096 root 1.262 /* the tail of transfer: execute stuff we can only do after a transfer */
1097 root 1.263 INLINE void
1098 root 1.262 transfer_tail (pTHX)
1099 root 1.259 {
1100 root 1.260 struct coro *next = (struct coro *)transfer_next;
1101 root 1.263 assert (!(transfer_next = 0)); /* just used for the side effect when asserts are enabled */
1102 root 1.264 assert (("FATAL: next coroutine was zero in transfer_tail (please report)", next));
1103 root 1.260
1104     free_coro_mortal (aTHX);
1105 root 1.259 UNLOCK;
1106    
1107 root 1.260 if (expect_false (next->throw))
1108 root 1.259 {
1109 root 1.260 SV *exception = sv_2mortal (next->throw);
1110 root 1.259
1111 root 1.260 next->throw = 0;
1112     sv_setsv (ERRSV, exception);
1113     croak (0);
1114 root 1.259 }
1115     }
1116    
1117 root 1.148 /*
1118     * this is a _very_ stripped down perl interpreter ;)
1119     */
1120 root 1.99 static void
1121 root 1.201 cctx_run (void *arg)
1122 root 1.13 {
1123 root 1.256 #ifdef USE_ITHREADS
1124     # if CORO_PTHREAD
1125     PERL_SET_CONTEXT (coro_thx);
1126     # endif
1127     #endif
1128     {
1129     dTHX;
1130 root 1.146
1131 root 1.265 /* we are the alternative tail to pp_set_stacklevel */
1132     /* so do the same things here */
1133 root 1.264 SSL_TAIL;
1134 root 1.260
1135 root 1.264 /* we now skip the op that did lead to transfer() */
1136 root 1.256 PL_op = PL_op->op_next;
1137 root 1.107
1138 root 1.256 /* inject a fake subroutine call to cctx_init */
1139     cctx_prepare (aTHX_ (coro_cctx *)arg);
1140 root 1.89
1141 root 1.260 /* cctx_run is the alternative tail of transfer() */
1142 root 1.262 transfer_tail (aTHX);
1143 root 1.259
1144 root 1.256 /* somebody or something will hit me for both perl_run and PL_restartop */
1145     PL_restartop = PL_op;
1146     perl_run (PL_curinterp);
1147 root 1.89
1148 root 1.256 /*
1149     * If perl-run returns we assume exit() was being called or the coro
1150     * fell off the end, which seems to be the only valid (non-bug)
1151     * reason for perl_run to return. We try to exit by jumping to the
1152     * bootstrap-time "top" top_env, as we cannot restore the "main"
1153     * coroutine as Coro has no such concept
1154     */
1155     PL_top_env = main_top_env;
1156     JMPENV_JUMP (2); /* I do not feel well about the hardcoded 2 at all */
1157     }
1158 root 1.89 }
1159    
1160 root 1.106 static coro_cctx *
1161     cctx_new ()
1162 root 1.89 {
1163 root 1.106 coro_cctx *cctx;
1164 root 1.89
1165 root 1.107 ++cctx_count;
1166 root 1.258 New (0, cctx, 1, coro_cctx);
1167    
1168 root 1.259 cctx->gen = cctx_gen;
1169     cctx->flags = 0;
1170 root 1.260 cctx->idle_sp = 0; /* can be accessed by transfer between cctx_run and set_stacklevel, on throw */
1171 root 1.258
1172     return cctx;
1173     }
1174    
1175     /* create a new cctx only suitable as source */
1176     static coro_cctx *
1177     cctx_new_empty ()
1178     {
1179     coro_cctx *cctx = cctx_new ();
1180 root 1.89
1181 root 1.259 cctx->sptr = 0;
1182 root 1.258 coro_create (&cctx->cctx, 0, 0, 0, 0);
1183    
1184     return cctx;
1185     }
1186    
1187     /* create a new cctx suitable as destination/running a perl interpreter */
1188     static coro_cctx *
1189     cctx_new_run ()
1190     {
1191     coro_cctx *cctx = cctx_new ();
1192     void *stack_start;
1193     size_t stack_size;
1194 root 1.254
1195 root 1.89 #if HAVE_MMAP
1196 root 1.254 cctx->ssize = ((cctx_stacksize * sizeof (long) + PAGESIZE - 1) / PAGESIZE + CORO_STACKGUARD) * PAGESIZE;
1197 root 1.120 /* mmap supposedly does allocate-on-write for us */
1198 root 1.106 cctx->sptr = mmap (0, cctx->ssize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);
1199 root 1.19
1200 root 1.141 if (cctx->sptr != (void *)-1)
1201 root 1.13 {
1202 root 1.263 #if CORO_STACKGUARD
1203     mprotect (cctx->sptr, CORO_STACKGUARD * PAGESIZE, PROT_NONE);
1204     #endif
1205     stack_start = (char *)cctx->sptr + CORO_STACKGUARD * PAGESIZE;
1206     stack_size = cctx->ssize - CORO_STACKGUARD * PAGESIZE;
1207 root 1.165 cctx->flags |= CC_MAPPED;
1208 root 1.141 }
1209     else
1210     #endif
1211 root 1.89 {
1212 root 1.254 cctx->ssize = cctx_stacksize * (long)sizeof (long);
1213     New (0, cctx->sptr, cctx_stacksize, long);
1214 root 1.13
1215 root 1.141 if (!cctx->sptr)
1216     {
1217 root 1.264 perror ("FATAL: unable to allocate stack for coroutine, exiting.");
1218 root 1.141 _exit (EXIT_FAILURE);
1219     }
1220 root 1.89
1221 root 1.145 stack_start = cctx->sptr;
1222     stack_size = cctx->ssize;
1223     }
1224 root 1.104
1225 root 1.263 #if CORO_USE_VALGRIND
1226     cctx->valgrind_id = VALGRIND_STACK_REGISTER ((char *)stack_start, (char *)stack_start + stack_size);
1227     #endif
1228    
1229 root 1.201 coro_create (&cctx->cctx, cctx_run, (void *)cctx, stack_start, stack_size);
1230 root 1.13
1231 root 1.106 return cctx;
1232 root 1.13 }
1233    
1234 root 1.15 static void
1235 root 1.115 cctx_destroy (coro_cctx *cctx)
1236 root 1.15 {
1237 root 1.106 if (!cctx)
1238 root 1.89 return;
1239    
1240 root 1.107 --cctx_count;
1241 root 1.253 coro_destroy (&cctx->cctx);
1242 root 1.107
1243 root 1.253 /* coro_transfer creates new, empty cctx's */
1244     if (cctx->sptr)
1245     {
1246 root 1.263 #if CORO_USE_VALGRIND
1247     VALGRIND_STACK_DEREGISTER (cctx->valgrind_id);
1248     #endif
1249 root 1.104
1250 root 1.89 #if HAVE_MMAP
1251 root 1.253 if (cctx->flags & CC_MAPPED)
1252     munmap (cctx->sptr, cctx->ssize);
1253     else
1254 root 1.89 #endif
1255 root 1.253 Safefree (cctx->sptr);
1256     }
1257 root 1.89
1258 root 1.106 Safefree (cctx);
1259 root 1.89 }
1260 root 1.32
1261 root 1.193 /* wether this cctx should be destructed */
1262 root 1.254 #define CCTX_EXPIRED(cctx) ((cctx)->gen != cctx_gen || ((cctx)->flags & CC_NOREUSE))
1263 root 1.193
1264 root 1.106 static coro_cctx *
1265 root 1.211 cctx_get (pTHX)
1266 root 1.89 {
1267 root 1.211 while (expect_true (cctx_first))
1268 root 1.89 {
1269 root 1.211 coro_cctx *cctx = cctx_first;
1270     cctx_first = cctx->next;
1271     --cctx_idle;
1272 root 1.145
1273 root 1.194 if (expect_true (!CCTX_EXPIRED (cctx)))
1274 root 1.145 return cctx;
1275    
1276     cctx_destroy (cctx);
1277 root 1.89 }
1278 root 1.91
1279 root 1.258 return cctx_new_run ();
1280 root 1.89 }
1281 root 1.19
1282 root 1.89 static void
1283 root 1.211 cctx_put (coro_cctx *cctx)
1284 root 1.89 {
1285 root 1.263 assert (("FATAL: cctx_put called on non-initialised cctx in Coro (please report)", cctx->sptr));
1286 root 1.253
1287 root 1.115 /* free another cctx if overlimit */
1288 root 1.254 if (expect_false (cctx_idle >= cctx_max_idle))
1289 root 1.115 {
1290 root 1.211 coro_cctx *first = cctx_first;
1291     cctx_first = first->next;
1292     --cctx_idle;
1293 root 1.115
1294     cctx_destroy (first);
1295     }
1296    
1297 root 1.211 ++cctx_idle;
1298     cctx->next = cctx_first;
1299     cctx_first = cctx;
1300 root 1.15 }
1301    
1302 root 1.137 /** coroutine switching *****************************************************/
1303    
1304 root 1.194 static void
1305 root 1.170 transfer_check (pTHX_ struct coro *prev, struct coro *next)
1306     {
1307 root 1.194 if (expect_true (prev != next))
1308 root 1.170 {
1309 root 1.194 if (expect_false (!(prev->flags & (CF_RUNNING | CF_NEW))))
1310 root 1.170 croak ("Coro::State::transfer called with non-running/new prev Coro::State, but can only transfer from running or new states");
1311    
1312 root 1.194 if (expect_false (next->flags & CF_RUNNING))
1313 root 1.170 croak ("Coro::State::transfer called with running next Coro::State, but can only transfer to inactive states");
1314    
1315 root 1.194 if (expect_false (next->flags & CF_DESTROYED))
1316 root 1.170 croak ("Coro::State::transfer called with destroyed next Coro::State, but can only transfer to inactive states");
1317    
1318 root 1.228 #if !PERL_VERSION_ATLEAST (5,10,0)
1319 root 1.230 if (expect_false (PL_lex_state != LEX_NOTPARSING))
1320 root 1.229 croak ("Coro::State::transfer called while parsing, but this is not supported in your perl version");
1321 root 1.198 #endif
1322 root 1.170 }
1323     }
1324    
1325     /* always use the TRANSFER macro */
1326 root 1.100 static void NOINLINE
1327 root 1.227 transfer (pTHX_ struct coro *prev, struct coro *next, int force_cctx)
1328 root 1.8 {
1329 root 1.15 dSTACKLEVEL;
1330 root 1.8
1331 root 1.89 /* sometimes transfer is only called to set idle_sp */
1332 root 1.194 if (expect_false (!next))
1333 root 1.124 {
1334     ((coro_cctx *)prev)->idle_sp = STACKLEVEL;
1335 root 1.132 assert (((coro_cctx *)prev)->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */
1336 root 1.124 }
1337 root 1.194 else if (expect_true (prev != next))
1338 root 1.8 {
1339 root 1.106 coro_cctx *prev__cctx;
1340 root 1.89
1341 root 1.194 if (expect_false (prev->flags & CF_NEW))
1342 root 1.111 {
1343 root 1.253 /* create a new empty/source context */
1344 root 1.258 prev->cctx = cctx_new_empty ();
1345 root 1.117 prev->flags &= ~CF_NEW;
1346     prev->flags |= CF_RUNNING;
1347 root 1.111 }
1348    
1349     prev->flags &= ~CF_RUNNING;
1350     next->flags |= CF_RUNNING;
1351    
1352 root 1.92 LOCK;
1353 root 1.13
1354 root 1.214 /* first get rid of the old state */
1355     save_perl (aTHX_ prev);
1356    
1357 root 1.194 if (expect_false (next->flags & CF_NEW))
1358 root 1.90 {
1359     /* need to start coroutine */
1360 root 1.117 next->flags &= ~CF_NEW;
1361 root 1.89 /* setup coroutine call */
1362 root 1.179 coro_setup (aTHX_ next);
1363 root 1.8 }
1364 root 1.118 else
1365 root 1.214 load_perl (aTHX_ next);
1366 root 1.15
1367 root 1.106 prev__cctx = prev->cctx;
1368 root 1.92
1369 root 1.261 /* possibly untie and reuse the cctx */
1370 root 1.227 if (expect_true (
1371     prev__cctx->idle_sp == STACKLEVEL
1372     && !(prev__cctx->flags & CC_TRACE)
1373     && !force_cctx
1374     ))
1375 root 1.92 {
1376 root 1.114 /* I assume that STACKLEVEL is a stronger indicator than PL_top_env changes */
1377 root 1.263 assert (("FATAL: current top_env must equal previous top_env in Coro (please report)", PL_top_env == prev__cctx->idle_te));
1378 root 1.112
1379 root 1.117 prev->cctx = 0;
1380    
1381 root 1.193 /* if the cctx is about to be destroyed we need to make sure we won't see it in cctx_get */
1382 root 1.194 /* without this the next cctx_get might destroy the prev__cctx while still in use */
1383     if (expect_false (CCTX_EXPIRED (prev__cctx)))
1384 root 1.201 if (!next->cctx)
1385 root 1.211 next->cctx = cctx_get (aTHX);
1386 root 1.193
1387 root 1.211 cctx_put (prev__cctx);
1388 root 1.92 }
1389    
1390 root 1.172 ++next->usecount;
1391    
1392 root 1.194 if (expect_true (!next->cctx))
1393 root 1.211 next->cctx = cctx_get (aTHX);
1394 root 1.111
1395 root 1.263 assert (("FATAL: transfer_next already nonzero in Coro (please report)", !transfer_next));
1396 root 1.260 transfer_next = next;
1397 root 1.216
1398 root 1.194 if (expect_false (prev__cctx != next->cctx))
1399 root 1.117 {
1400 root 1.106 prev__cctx->top_env = PL_top_env;
1401     PL_top_env = next->cctx->top_env;
1402     coro_transfer (&prev__cctx->cctx, &next->cctx->cctx);
1403 root 1.92 }
1404    
1405 root 1.262 transfer_tail (aTHX);
1406 root 1.8 }
1407 root 1.39 }
1408 root 1.23
1409 root 1.227 #define TRANSFER(ta, force_cctx) transfer (aTHX_ (ta).prev, (ta).next, (force_cctx))
1410 root 1.170 #define TRANSFER_CHECK(ta) transfer_check (aTHX_ (ta).prev, (ta).next)
1411 root 1.92
1412 root 1.137 /** high level stuff ********************************************************/
1413    
1414 root 1.133 static int
1415 root 1.146 coro_state_destroy (pTHX_ struct coro *coro)
1416 root 1.87 {
1417 root 1.133 if (coro->flags & CF_DESTROYED)
1418     return 0;
1419    
1420     coro->flags |= CF_DESTROYED;
1421 root 1.137
1422     if (coro->flags & CF_READY)
1423     {
1424     /* reduce nready, as destroying a ready coro effectively unreadies it */
1425 root 1.139 /* alternative: look through all ready queues and remove the coro */
1426 root 1.137 LOCK;
1427     --coro_nready;
1428     UNLOCK;
1429     }
1430     else
1431     coro->flags |= CF_READY; /* make sure it is NOT put into the readyqueue */
1432 root 1.87
1433     if (coro->mainstack && coro->mainstack != main_mainstack)
1434     {
1435 root 1.140 struct coro temp;
1436    
1437 root 1.177 if (coro->flags & CF_RUNNING)
1438     croak ("FATAL: tried to destroy currently running coroutine");
1439 root 1.133
1440 root 1.146 save_perl (aTHX_ &temp);
1441     load_perl (aTHX_ coro);
1442 root 1.87
1443 root 1.253 coro_destruct (aTHX_ coro);
1444 root 1.87
1445 root 1.198 load_perl (aTHX_ &temp);
1446 root 1.87
1447 root 1.198 coro->slot = 0;
1448 root 1.87 }
1449    
1450 root 1.115 cctx_destroy (coro->cctx);
1451 root 1.87 SvREFCNT_dec (coro->args);
1452 root 1.133
1453 root 1.151 if (coro->next) coro->next->prev = coro->prev;
1454     if (coro->prev) coro->prev->next = coro->next;
1455 root 1.153 if (coro == coro_first) coro_first = coro->next;
1456 root 1.151
1457 root 1.133 return 1;
1458 root 1.87 }
1459    
1460     static int
1461 root 1.134 coro_state_free (pTHX_ SV *sv, MAGIC *mg)
1462 root 1.87 {
1463     struct coro *coro = (struct coro *)mg->mg_ptr;
1464     mg->mg_ptr = 0;
1465    
1466 root 1.151 coro->hv = 0;
1467    
1468 root 1.134 if (--coro->refcnt < 0)
1469     {
1470 root 1.146 coro_state_destroy (aTHX_ coro);
1471 root 1.134 Safefree (coro);
1472     }
1473 root 1.133
1474 root 1.87 return 0;
1475     }
1476    
1477     static int
1478 root 1.98 coro_state_dup (pTHX_ MAGIC *mg, CLONE_PARAMS *params)
1479 root 1.87 {
1480     struct coro *coro = (struct coro *)mg->mg_ptr;
1481    
1482     ++coro->refcnt;
1483    
1484     return 0;
1485     }
1486    
1487 root 1.100 static MGVTBL coro_state_vtbl = {
1488     0, 0, 0, 0,
1489 root 1.134 coro_state_free,
1490 root 1.100 0,
1491     #ifdef MGf_DUP
1492     coro_state_dup,
1493 root 1.102 #else
1494     # define MGf_DUP 0
1495 root 1.100 #endif
1496     };
1497 root 1.87
1498 root 1.23 static void
1499 root 1.146 prepare_transfer (pTHX_ struct transfer_args *ta, SV *prev_sv, SV *next_sv)
1500 root 1.23 {
1501 root 1.122 ta->prev = SvSTATE (prev_sv);
1502     ta->next = SvSTATE (next_sv);
1503 root 1.170 TRANSFER_CHECK (*ta);
1504 root 1.92 }
1505    
1506     static void
1507 root 1.122 api_transfer (SV *prev_sv, SV *next_sv)
1508 root 1.92 {
1509 root 1.146 dTHX;
1510 root 1.92 struct transfer_args ta;
1511    
1512 root 1.146 prepare_transfer (aTHX_ &ta, prev_sv, next_sv);
1513 root 1.227 TRANSFER (ta, 1);
1514 root 1.21 }
1515    
1516 root 1.22 /** Coro ********************************************************************/
1517    
1518     static void
1519 root 1.146 coro_enq (pTHX_ SV *coro_sv)
1520 root 1.22 {
1521 root 1.112 av_push (coro_ready [SvSTATE (coro_sv)->prio - PRIO_MIN], coro_sv);
1522 root 1.22 }
1523    
1524     static SV *
1525 root 1.218 coro_deq (pTHX)
1526 root 1.22 {
1527 root 1.218 int prio;
1528 root 1.22
1529 root 1.218 for (prio = PRIO_MAX - PRIO_MIN + 1; --prio >= 0; )
1530 root 1.83 if (AvFILLp (coro_ready [prio]) >= 0)
1531 root 1.137 return av_shift (coro_ready [prio]);
1532 root 1.22
1533     return 0;
1534     }
1535    
1536 root 1.111 static int
1537     api_ready (SV *coro_sv)
1538 root 1.23 {
1539 root 1.146 dTHX;
1540 root 1.111 struct coro *coro;
1541 root 1.237 SV *sv_hook;
1542     void (*xs_hook)(void);
1543 root 1.111
1544     if (SvROK (coro_sv))
1545     coro_sv = SvRV (coro_sv);
1546    
1547     coro = SvSTATE (coro_sv);
1548 root 1.112
1549 root 1.111 if (coro->flags & CF_READY)
1550     return 0;
1551 pcg 1.56
1552 root 1.111 coro->flags |= CF_READY;
1553 root 1.39
1554 pcg 1.55 LOCK;
1555 root 1.233
1556 root 1.237 sv_hook = coro_nready ? 0 : coro_readyhook;
1557     xs_hook = coro_nready ? 0 : coroapi.readyhook;
1558 root 1.233
1559 root 1.249 coro_enq (aTHX_ SvREFCNT_inc_NN (coro_sv));
1560 root 1.137 ++coro_nready;
1561 root 1.233
1562 pcg 1.55 UNLOCK;
1563 root 1.233
1564 root 1.237 if (sv_hook)
1565 root 1.233 {
1566     dSP;
1567    
1568     ENTER;
1569     SAVETMPS;
1570    
1571     PUSHMARK (SP);
1572     PUTBACK;
1573 root 1.237 call_sv (sv_hook, G_DISCARD);
1574 root 1.233 SPAGAIN;
1575    
1576     FREETMPS;
1577     LEAVE;
1578     }
1579 root 1.111
1580 root 1.237 if (xs_hook)
1581     xs_hook ();
1582    
1583 root 1.111 return 1;
1584     }
1585    
1586     static int
1587     api_is_ready (SV *coro_sv)
1588     {
1589 root 1.146 dTHX;
1590 root 1.263
1591 root 1.130 return !!(SvSTATE (coro_sv)->flags & CF_READY);
1592 root 1.23 }
1593    
1594 root 1.263 INLINE void
1595 root 1.146 prepare_schedule (pTHX_ struct transfer_args *ta)
1596 root 1.23 {
1597 root 1.133 SV *prev_sv, *next_sv;
1598 root 1.88
1599     for (;;)
1600     {
1601     LOCK;
1602 root 1.218 next_sv = coro_deq (aTHX);
1603 root 1.88
1604 root 1.133 /* nothing to schedule: call the idle handler */
1605 root 1.194 if (expect_false (!next_sv))
1606 root 1.133 {
1607 root 1.140 dSP;
1608 root 1.138 UNLOCK;
1609 root 1.133
1610     ENTER;
1611     SAVETMPS;
1612 root 1.23
1613 root 1.133 PUSHMARK (SP);
1614     PUTBACK;
1615     call_sv (get_sv ("Coro::idle", FALSE), G_DISCARD);
1616 root 1.219 SPAGAIN;
1617 root 1.133
1618     FREETMPS;
1619     LEAVE;
1620     continue;
1621     }
1622 root 1.88
1623 root 1.133 ta->next = SvSTATE (next_sv);
1624 pcg 1.55
1625 root 1.133 /* cannot transfer to destroyed coros, skip and look for next */
1626 root 1.194 if (expect_false (ta->next->flags & CF_DESTROYED))
1627 root 1.133 {
1628 root 1.138 UNLOCK;
1629 root 1.133 SvREFCNT_dec (next_sv);
1630 root 1.260 /* coro_nready has already been taken care of by destroy */
1631 root 1.133 continue;
1632     }
1633 root 1.23
1634 root 1.137 --coro_nready;
1635     UNLOCK;
1636 root 1.133 break;
1637 root 1.88 }
1638    
1639 root 1.133 /* free this only after the transfer */
1640     prev_sv = SvRV (coro_current);
1641     ta->prev = SvSTATE (prev_sv);
1642 root 1.170 TRANSFER_CHECK (*ta);
1643 root 1.263 assert (("FATAL: next coroutine isn't marked as ready in Coro (please report)", ta->next->flags & CF_READY));
1644 root 1.133 ta->next->flags &= ~CF_READY;
1645 root 1.170 SvRV_set (coro_current, next_sv);
1646 root 1.23
1647 root 1.99 LOCK;
1648 root 1.146 free_coro_mortal (aTHX);
1649 root 1.133 coro_mortal = prev_sv;
1650 root 1.99 UNLOCK;
1651 root 1.92 }
1652    
1653 root 1.263 INLINE void
1654 root 1.146 prepare_cede (pTHX_ struct transfer_args *ta)
1655 root 1.92 {
1656 root 1.117 api_ready (coro_current);
1657 root 1.146 prepare_schedule (aTHX_ ta);
1658 root 1.131 }
1659 pcg 1.55
1660 root 1.267 static void
1661 root 1.146 prepare_cede_notself (pTHX_ struct transfer_args *ta)
1662 root 1.131 {
1663 root 1.267 SV *prev = SvRV (coro_current);
1664    
1665 root 1.131 if (coro_nready)
1666     {
1667 root 1.146 prepare_schedule (aTHX_ ta);
1668 root 1.131 api_ready (prev);
1669     }
1670     else
1671 root 1.267 ta->prev = ta->next = SvSTATE (prev);
1672 root 1.39 }
1673    
1674 root 1.92 static void
1675     api_schedule (void)
1676     {
1677 root 1.146 dTHX;
1678 root 1.92 struct transfer_args ta;
1679    
1680 root 1.146 prepare_schedule (aTHX_ &ta);
1681 root 1.227 TRANSFER (ta, 1);
1682 root 1.92 }
1683 root 1.89
1684 root 1.131 static int
1685 root 1.39 api_cede (void)
1686     {
1687 root 1.146 dTHX;
1688 root 1.92 struct transfer_args ta;
1689 root 1.89
1690 root 1.146 prepare_cede (aTHX_ &ta);
1691 root 1.131
1692 root 1.194 if (expect_true (ta.prev != ta.next))
1693 root 1.131 {
1694 root 1.227 TRANSFER (ta, 1);
1695 root 1.131 return 1;
1696     }
1697     else
1698     return 0;
1699     }
1700    
1701     static int
1702     api_cede_notself (void)
1703     {
1704 root 1.267 if (coro_nready)
1705     {
1706     dTHX;
1707     struct transfer_args ta;
1708 root 1.131
1709 root 1.267 prepare_cede_notself (aTHX_ &ta);
1710 root 1.227 TRANSFER (ta, 1);
1711 root 1.131 return 1;
1712     }
1713     else
1714     return 0;
1715 root 1.23 }
1716    
1717 root 1.173 static void
1718 root 1.174 api_trace (SV *coro_sv, int flags)
1719 root 1.173 {
1720     dTHX;
1721 root 1.174 struct coro *coro = SvSTATE (coro_sv);
1722 root 1.173
1723     if (flags & CC_TRACE)
1724     {
1725     if (!coro->cctx)
1726 root 1.258 coro->cctx = cctx_new_run ();
1727 root 1.173 else if (!(coro->cctx->flags & CC_TRACE))
1728     croak ("cannot enable tracing on coroutine with custom stack");
1729    
1730     coro->cctx->flags |= CC_NOREUSE | (flags & (CC_TRACE | CC_TRACE_ALL));
1731     }
1732     else if (coro->cctx && coro->cctx->flags & CC_TRACE)
1733     {
1734     coro->cctx->flags &= ~(CC_TRACE | CC_TRACE_ALL);
1735    
1736     if (coro->flags & CF_RUNNING)
1737     PL_runops = RUNOPS_DEFAULT;
1738     else
1739 root 1.198 coro->slot->runops = RUNOPS_DEFAULT;
1740 root 1.173 }
1741     }
1742    
1743 root 1.255 #if 0
1744 root 1.243 static int
1745     coro_gensub_free (pTHX_ SV *sv, MAGIC *mg)
1746     {
1747     AV *padlist;
1748     AV *av = (AV *)mg->mg_obj;
1749    
1750     abort ();
1751    
1752     return 0;
1753     }
1754    
1755     static MGVTBL coro_gensub_vtbl = {
1756     0, 0, 0, 0,
1757     coro_gensub_free
1758     };
1759 root 1.255 #endif
1760 root 1.243
1761 root 1.246 /*****************************************************************************/
1762     /* PerlIO::cede */
1763    
1764     typedef struct
1765     {
1766     PerlIOBuf base;
1767     NV next, every;
1768     } PerlIOCede;
1769    
1770     static IV
1771     PerlIOCede_pushed (pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1772     {
1773     PerlIOCede *self = PerlIOSelf (f, PerlIOCede);
1774    
1775 root 1.247 self->every = SvCUR (arg) ? SvNV (arg) : 0.01;
1776 root 1.246 self->next = nvtime () + self->every;
1777    
1778     return PerlIOBuf_pushed (aTHX_ f, mode, Nullsv, tab);
1779     }
1780    
1781     static SV *
1782     PerlIOCede_getarg (pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
1783     {
1784     PerlIOCede *self = PerlIOSelf (f, PerlIOCede);
1785    
1786     return newSVnv (self->every);
1787     }
1788    
1789     static IV
1790     PerlIOCede_flush (pTHX_ PerlIO *f)
1791     {
1792     PerlIOCede *self = PerlIOSelf (f, PerlIOCede);
1793     double now = nvtime ();
1794    
1795     if (now >= self->next)
1796     {
1797     api_cede ();
1798     self->next = now + self->every;
1799     }
1800    
1801 root 1.248 return PerlIOBuf_flush (aTHX_ f);
1802 root 1.246 }
1803    
1804     static PerlIO_funcs PerlIO_cede =
1805     {
1806     sizeof(PerlIO_funcs),
1807     "cede",
1808     sizeof(PerlIOCede),
1809     PERLIO_K_DESTRUCT | PERLIO_K_RAW,
1810     PerlIOCede_pushed,
1811     PerlIOBuf_popped,
1812     PerlIOBuf_open,
1813     PerlIOBase_binmode,
1814     PerlIOCede_getarg,
1815     PerlIOBase_fileno,
1816     PerlIOBuf_dup,
1817     PerlIOBuf_read,
1818     PerlIOBuf_unread,
1819     PerlIOBuf_write,
1820     PerlIOBuf_seek,
1821     PerlIOBuf_tell,
1822     PerlIOBuf_close,
1823     PerlIOCede_flush,
1824     PerlIOBuf_fill,
1825     PerlIOBase_eof,
1826     PerlIOBase_error,
1827     PerlIOBase_clearerr,
1828     PerlIOBase_setlinebuf,
1829     PerlIOBuf_get_base,
1830     PerlIOBuf_bufsiz,
1831     PerlIOBuf_get_ptr,
1832     PerlIOBuf_get_cnt,
1833     PerlIOBuf_set_ptrcnt,
1834     };
1835    
1836 root 1.264 /*****************************************************************************/
1837    
1838     static const CV *ssl_cv; /* for quick consistency check */
1839    
1840     static UNOP ssl_restore; /* restore stack as entersub did, for first-re-run */
1841     static SV *ssl_arg0;
1842     static SV *ssl_arg1;
1843    
1844     /* this restores the stack in the case we patched the entersub, to */
1845     /* recreate the stack frame as perl will on following calls */
1846     /* since entersub cleared the stack */
1847     static OP *
1848     pp_restore (pTHX)
1849     {
1850     dSP;
1851    
1852     PUSHMARK (SP);
1853    
1854     EXTEND (SP, 3);
1855     if (ssl_arg0) PUSHs (sv_2mortal (ssl_arg0)), ssl_arg0 = 0;
1856     if (ssl_arg1) PUSHs (sv_2mortal (ssl_arg1)), ssl_arg1 = 0;
1857     PUSHs ((SV *)CvGV (ssl_cv));
1858    
1859     RETURNOP (ssl_restore.op_first);
1860     }
1861    
1862 root 1.267 #define OPpENTERSUB_SSL 15 /* the part of op_private entersub hopefully doesn't use */
1863    
1864 root 1.264 /* declare prototype */
1865     XS(XS_Coro__State__set_stacklevel);
1866    
1867 root 1.267 /*
1868     * these not obviously related functions are all rolled into one
1869     * function to increase chances that they all will call transfer with the same
1870     * stack offset
1871     */
1872 root 1.264 static OP *
1873     pp_set_stacklevel (pTHX)
1874     {
1875     dSP;
1876     struct transfer_args ta;
1877     SV **arg = PL_stack_base + TOPMARK + 1;
1878     int items = SP - arg; /* args without function object */
1879    
1880     /* do a quick consistency check on the "function" object, and if it isn't */
1881     /* for us, divert to the real entersub */
1882     if (SvTYPE (*sp) != SVt_PVGV || CvXSUB (GvCV (*sp)) != XS_Coro__State__set_stacklevel)
1883     return PL_ppaddr[OP_ENTERSUB](aTHX);
1884    
1885     /* pop args */
1886     SP = PL_stack_base + POPMARK;
1887    
1888     if (!(PL_op->op_flags & OPf_STACKED))
1889     {
1890     /* ampersand-form of call, use @_ instead of stack */
1891     AV *av = GvAV (PL_defgv);
1892     arg = AvARRAY (av);
1893     items = AvFILLp (av) + 1;
1894     }
1895    
1896     PUTBACK;
1897 root 1.266 switch (PL_op->op_private & OPpENTERSUB_SSL)
1898 root 1.264 {
1899     case 0:
1900     prepare_set_stacklevel (&ta, (struct coro_cctx *)SvIV (arg [0]));
1901     break;
1902    
1903     case 1:
1904     if (items != 2)
1905     croak ("Coro::State::transfer (prev, next) expects two arguments, not %d.", items);
1906    
1907     prepare_transfer (aTHX_ &ta, arg [0], arg [1]);
1908     break;
1909    
1910     case 2:
1911     prepare_schedule (aTHX_ &ta);
1912     break;
1913    
1914     case 3:
1915     prepare_cede (aTHX_ &ta);
1916     break;
1917    
1918     case 4:
1919 root 1.267 prepare_cede_notself (aTHX_ &ta);
1920 root 1.264 break;
1921     }
1922    
1923     TRANSFER (ta, 0);
1924     SPAGAIN;
1925    
1926     skip:
1927 root 1.265 PUTBACK;
1928     SSL_TAIL;
1929     SPAGAIN;
1930 root 1.264 RETURN;
1931     }
1932 root 1.246
1933 root 1.267 static void
1934     coro_ssl_patch (pTHX_ CV *cv, int ix, SV **args, int items)
1935     {
1936     assert (("FATAL: ssl call recursion in Coro module (please report)", PL_op->op_ppaddr != pp_set_stacklevel));
1937 root 1.1
1938 root 1.267 assert (("FATAL: ssl call with illegal CV value", CvGV (cv)));
1939     ssl_cv = cv;
1940 root 1.1
1941 root 1.267 /* we patch the op, and then re-run the whole call */
1942     /* we have to put some dummy argument on the stack for this to work */
1943     ssl_restore.op_next = (OP *)&ssl_restore;
1944     ssl_restore.op_type = OP_NULL;
1945     ssl_restore.op_ppaddr = pp_restore;
1946     ssl_restore.op_first = PL_op;
1947 root 1.264
1948 root 1.267 ssl_arg0 = items > 0 ? SvREFCNT_inc (args [0]) : 0;
1949     ssl_arg1 = items > 1 ? SvREFCNT_inc (args [1]) : 0;
1950 root 1.266
1951 root 1.267 PL_op->op_ppaddr = pp_set_stacklevel;
1952     PL_op->op_private = PL_op->op_private & ~OPpENTERSUB_SSL | ix; /* we potentially share our private flags with entersub */
1953 root 1.264
1954 root 1.267 PL_op = (OP *)&ssl_restore;
1955     }
1956 root 1.264
1957 root 1.267 MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_
1958 root 1.264
1959 root 1.267 PROTOTYPES: DISABLE
1960 root 1.264
1961 root 1.3 BOOT:
1962 root 1.88 {
1963 pcg 1.55 #ifdef USE_ITHREADS
1964 root 1.253 MUTEX_INIT (&coro_lock);
1965 root 1.256 # if CORO_PTHREAD
1966     coro_thx = PERL_GET_CONTEXT;
1967     # endif
1968 pcg 1.55 #endif
1969 root 1.78 BOOT_PAGESIZE;
1970 pcg 1.55
1971 root 1.190 irsgv = gv_fetchpv ("/" , GV_ADD|GV_NOTQUAL, SVt_PV);
1972     stdoutgv = gv_fetchpv ("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO);
1973 root 1.220
1974 root 1.239 orig_sigelem_get = PL_vtbl_sigelem.svt_get; PL_vtbl_sigelem.svt_get = coro_sigelem_get;
1975     orig_sigelem_set = PL_vtbl_sigelem.svt_set; PL_vtbl_sigelem.svt_set = coro_sigelem_set;
1976     orig_sigelem_clr = PL_vtbl_sigelem.svt_clear; PL_vtbl_sigelem.svt_clear = coro_sigelem_clr;
1977 root 1.220
1978 root 1.213 hv_sig = coro_get_hv (aTHX_ "SIG", TRUE);
1979 root 1.220 rv_diehook = newRV_inc ((SV *)gv_fetchpv ("Coro::State::diehook" , 0, SVt_PVCV));
1980     rv_warnhook = newRV_inc ((SV *)gv_fetchpv ("Coro::State::warnhook", 0, SVt_PVCV));
1981 root 1.199
1982 root 1.14 coro_state_stash = gv_stashpv ("Coro::State", TRUE);
1983 root 1.7
1984 root 1.167 newCONSTSUB (coro_state_stash, "CC_TRACE" , newSViv (CC_TRACE));
1985     newCONSTSUB (coro_state_stash, "CC_TRACE_SUB" , newSViv (CC_TRACE_SUB));
1986     newCONSTSUB (coro_state_stash, "CC_TRACE_LINE", newSViv (CC_TRACE_LINE));
1987     newCONSTSUB (coro_state_stash, "CC_TRACE_ALL" , newSViv (CC_TRACE_ALL));
1988    
1989 root 1.12 main_mainstack = PL_mainstack;
1990 root 1.148 main_top_env = PL_top_env;
1991    
1992     while (main_top_env->je_prev)
1993     main_top_env = main_top_env->je_prev;
1994 root 1.23
1995 root 1.237 coroapi.ver = CORO_API_VERSION;
1996     coroapi.rev = CORO_API_REVISION;
1997     coroapi.transfer = api_transfer;
1998 root 1.87
1999 root 1.246 {
2000     SV **svp = hv_fetch (PL_modglobal, "Time::NVtime", 12, 0);
2001    
2002     if (!svp) croak ("Time::HiRes is required");
2003     if (!SvIOK (*svp)) croak ("Time::NVtime isn't a function pointer");
2004    
2005     nvtime = INT2PTR (double (*)(), SvIV (*svp));
2006     }
2007    
2008 root 1.87 assert (("PRIO_NORMAL must be 0", !PRIO_NORMAL));
2009 root 1.9 }
2010 root 1.3
2011 root 1.87 SV *
2012 root 1.86 new (char *klass, ...)
2013 root 1.1 CODE:
2014 root 1.86 {
2015 root 1.87 struct coro *coro;
2016 root 1.214 MAGIC *mg;
2017 root 1.87 HV *hv;
2018 root 1.86 int i;
2019    
2020 pcg 1.47 Newz (0, coro, 1, struct coro);
2021 root 1.178 coro->args = newAV ();
2022 root 1.117 coro->flags = CF_NEW;
2023 root 1.86
2024 root 1.153 if (coro_first) coro_first->prev = coro;
2025     coro->next = coro_first;
2026     coro_first = coro;
2027 root 1.151
2028     coro->hv = hv = newHV ();
2029 root 1.214 mg = sv_magicext ((SV *)hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)coro, 0);
2030     mg->mg_flags |= MGf_DUP;
2031 root 1.89 RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1));
2032    
2033 root 1.192 av_extend (coro->args, items - 1);
2034 root 1.86 for (i = 1; i < items; i++)
2035     av_push (coro->args, newSVsv (ST (i)));
2036     }
2037 root 1.1 OUTPUT:
2038     RETVAL
2039    
2040 root 1.267 void
2041     _set_stacklevel (...)
2042     ALIAS:
2043     Coro::State::transfer = 1
2044     Coro::schedule = 2
2045     Coro::cede = 3
2046     Coro::cede_notself = 4
2047     CODE:
2048     coro_ssl_patch (aTHX_ cv, ix, &ST (0), items);
2049    
2050 root 1.133 bool
2051     _destroy (SV *coro_sv)
2052 root 1.87 CODE:
2053 root 1.146 RETVAL = coro_state_destroy (aTHX_ SvSTATE (coro_sv));
2054 root 1.133 OUTPUT:
2055     RETVAL
2056 root 1.12
2057 root 1.7 void
2058 root 1.233 _exit (int code)
2059 root 1.20 PROTOTYPE: $
2060     CODE:
2061     _exit (code);
2062 root 1.1
2063 root 1.106 int
2064 root 1.145 cctx_stacksize (int new_stacksize = 0)
2065     CODE:
2066 root 1.254 RETVAL = cctx_stacksize;
2067 root 1.145 if (new_stacksize)
2068 root 1.254 {
2069     cctx_stacksize = new_stacksize;
2070     ++cctx_gen;
2071     }
2072     OUTPUT:
2073     RETVAL
2074    
2075     int
2076     cctx_max_idle (int max_idle = 0)
2077     CODE:
2078     RETVAL = cctx_max_idle;
2079     if (max_idle > 1)
2080     cctx_max_idle = max_idle;
2081 root 1.145 OUTPUT:
2082     RETVAL
2083    
2084     int
2085 root 1.106 cctx_count ()
2086     CODE:
2087     RETVAL = cctx_count;
2088     OUTPUT:
2089     RETVAL
2090    
2091     int
2092     cctx_idle ()
2093     CODE:
2094 root 1.211 RETVAL = cctx_idle;
2095 root 1.106 OUTPUT:
2096     RETVAL
2097    
2098 root 1.151 void
2099     list ()
2100     PPCODE:
2101     {
2102     struct coro *coro;
2103 root 1.153 for (coro = coro_first; coro; coro = coro->next)
2104 root 1.151 if (coro->hv)
2105     XPUSHs (sv_2mortal (newRV_inc ((SV *)coro->hv)));
2106     }
2107    
2108     void
2109 root 1.164 call (Coro::State coro, SV *coderef)
2110     ALIAS:
2111     eval = 1
2112 root 1.151 CODE:
2113     {
2114 root 1.245 if (coro->mainstack && ((coro->flags & CF_RUNNING) || coro->slot))
2115 root 1.151 {
2116     struct coro temp;
2117    
2118     if (!(coro->flags & CF_RUNNING))
2119     {
2120 root 1.219 PUTBACK;
2121 root 1.151 save_perl (aTHX_ &temp);
2122     load_perl (aTHX_ coro);
2123     }
2124    
2125     {
2126     dSP;
2127     ENTER;
2128     SAVETMPS;
2129 root 1.208 PUTBACK;
2130     PUSHSTACK;
2131 root 1.151 PUSHMARK (SP);
2132 root 1.198
2133 root 1.164 if (ix)
2134     eval_sv (coderef, 0);
2135     else
2136     call_sv (coderef, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
2137 root 1.198
2138 root 1.208 POPSTACK;
2139 root 1.211 SPAGAIN;
2140 root 1.151 FREETMPS;
2141     LEAVE;
2142 root 1.210 PUTBACK;
2143 root 1.151 }
2144    
2145     if (!(coro->flags & CF_RUNNING))
2146     {
2147     save_perl (aTHX_ coro);
2148     load_perl (aTHX_ &temp);
2149 root 1.219 SPAGAIN;
2150 root 1.151 }
2151     }
2152     }
2153 root 1.172
2154 root 1.151 SV *
2155 root 1.152 is_ready (Coro::State coro)
2156 root 1.151 PROTOTYPE: $
2157     ALIAS:
2158     is_ready = CF_READY
2159     is_running = CF_RUNNING
2160     is_new = CF_NEW
2161     is_destroyed = CF_DESTROYED
2162     CODE:
2163     RETVAL = boolSV (coro->flags & ix);
2164     OUTPUT:
2165     RETVAL
2166    
2167 root 1.165 void
2168 root 1.260 throw (Coro::State self, SV *throw = &PL_sv_undef)
2169     PROTOTYPE: $;$
2170     CODE:
2171     SvREFCNT_dec (self->throw);
2172     self->throw = SvOK (throw) ? newSVsv (throw) : 0;
2173    
2174     void
2175 root 1.174 api_trace (SV *coro, int flags = CC_TRACE | CC_TRACE_SUB)
2176 root 1.165
2177 root 1.162 SV *
2178 root 1.234 has_cctx (Coro::State coro)
2179 root 1.162 PROTOTYPE: $
2180     CODE:
2181     RETVAL = boolSV (!!coro->cctx);
2182     OUTPUT:
2183     RETVAL
2184    
2185 root 1.167 int
2186     is_traced (Coro::State coro)
2187     PROTOTYPE: $
2188     CODE:
2189     RETVAL = (coro->cctx ? coro->cctx->flags : 0) & CC_TRACE_ALL;
2190     OUTPUT:
2191     RETVAL
2192    
2193 root 1.255 UV
2194 root 1.152 rss (Coro::State coro)
2195     PROTOTYPE: $
2196 root 1.172 ALIAS:
2197     usecount = 1
2198 root 1.152 CODE:
2199 root 1.172 switch (ix)
2200     {
2201     case 0: RETVAL = coro_rss (aTHX_ coro); break;
2202     case 1: RETVAL = coro->usecount; break;
2203     }
2204 root 1.152 OUTPUT:
2205     RETVAL
2206    
2207 root 1.226 void
2208     force_cctx ()
2209     CODE:
2210     struct coro *coro = SvSTATE (coro_current);
2211     coro->cctx->idle_sp = 0;
2212 root 1.151
2213 root 1.242 void
2214     swap_defsv (Coro::State self)
2215     PROTOTYPE: $
2216     ALIAS:
2217     swap_defav = 1
2218     CODE:
2219     if (!self->slot)
2220     croak ("cannot swap state with coroutine that has no saved state");
2221     else
2222     {
2223     SV **src = ix ? (SV **)&GvAV (PL_defgv) : &GvSV (PL_defgv);
2224     SV **dst = ix ? (SV **)&self->slot->defav : (SV **)&self->slot->defsv;
2225    
2226     SV *tmp = *src; *src = *dst; *dst = tmp;
2227     }
2228    
2229 root 1.21 MODULE = Coro::State PACKAGE = Coro
2230    
2231     BOOT:
2232     {
2233 root 1.22 int i;
2234    
2235 root 1.233 av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE);
2236 root 1.213 sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE);
2237     sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE);
2238 root 1.159
2239 root 1.213 coro_current = coro_get_sv (aTHX_ "Coro::current", FALSE);
2240 root 1.159 SvREADONLY_on (coro_current);
2241    
2242 root 1.198 coro_stash = gv_stashpv ("Coro", TRUE);
2243 root 1.88
2244     newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (PRIO_MAX));
2245     newCONSTSUB (coro_stash, "PRIO_HIGH", newSViv (PRIO_HIGH));
2246     newCONSTSUB (coro_stash, "PRIO_NORMAL", newSViv (PRIO_NORMAL));
2247     newCONSTSUB (coro_stash, "PRIO_LOW", newSViv (PRIO_LOW));
2248     newCONSTSUB (coro_stash, "PRIO_IDLE", newSViv (PRIO_IDLE));
2249     newCONSTSUB (coro_stash, "PRIO_MIN", newSViv (PRIO_MIN));
2250 root 1.22
2251     for (i = PRIO_MAX - PRIO_MIN + 1; i--; )
2252     coro_ready[i] = newAV ();
2253 root 1.26
2254     {
2255 root 1.263 SV *sv = coro_get_sv (aTHX_ "Coro::API", TRUE);
2256 root 1.26
2257 root 1.131 coroapi.schedule = api_schedule;
2258     coroapi.cede = api_cede;
2259     coroapi.cede_notself = api_cede_notself;
2260     coroapi.ready = api_ready;
2261     coroapi.is_ready = api_is_ready;
2262     coroapi.nready = &coro_nready;
2263     coroapi.current = coro_current;
2264 root 1.26
2265     GCoroAPI = &coroapi;
2266 root 1.81 sv_setiv (sv, (IV)&coroapi);
2267     SvREADONLY_on (sv);
2268 root 1.26 }
2269 root 1.21 }
2270    
2271 root 1.122 void
2272     _set_current (SV *current)
2273     PROTOTYPE: $
2274     CODE:
2275     SvREFCNT_dec (SvRV (coro_current));
2276 root 1.249 SvRV_set (coro_current, SvREFCNT_inc_NN (SvRV (current)));
2277 root 1.122
2278 root 1.233 void
2279     _set_readyhook (SV *hook)
2280     PROTOTYPE: $
2281     CODE:
2282     LOCK;
2283 root 1.236 SvREFCNT_dec (coro_readyhook);
2284 root 1.233 coro_readyhook = SvOK (hook) ? newSVsv (hook) : 0;
2285     UNLOCK;
2286    
2287 root 1.92 int
2288     prio (Coro::State coro, int newprio = 0)
2289     ALIAS:
2290     nice = 1
2291     CODE:
2292     {
2293     RETVAL = coro->prio;
2294    
2295     if (items > 1)
2296     {
2297     if (ix)
2298 root 1.129 newprio = coro->prio - newprio;
2299 root 1.92
2300     if (newprio < PRIO_MIN) newprio = PRIO_MIN;
2301     if (newprio > PRIO_MAX) newprio = PRIO_MAX;
2302    
2303     coro->prio = newprio;
2304     }
2305     }
2306 root 1.130 OUTPUT:
2307     RETVAL
2308 root 1.92
2309 root 1.111 SV *
2310 root 1.89 ready (SV *self)
2311 root 1.35 PROTOTYPE: $
2312 root 1.21 CODE:
2313 root 1.111 RETVAL = boolSV (api_ready (self));
2314     OUTPUT:
2315     RETVAL
2316    
2317 root 1.25 int
2318 root 1.87 nready (...)
2319 root 1.25 PROTOTYPE:
2320     CODE:
2321     RETVAL = coro_nready;
2322     OUTPUT:
2323     RETVAL
2324    
2325 root 1.159 # for async_pool speedup
2326 root 1.161 void
2327     _pool_1 (SV *cb)
2328 root 1.159 CODE:
2329     {
2330 root 1.181 struct coro *coro = SvSTATE (coro_current);
2331 root 1.159 HV *hv = (HV *)SvRV (coro_current);
2332     AV *defav = GvAV (PL_defgv);
2333 root 1.212 SV *invoke = hv_delete (hv, "_invoke", sizeof ("_invoke") - 1, 0);
2334 root 1.159 AV *invoke_av;
2335 root 1.181 int i, len;
2336    
2337 root 1.159 if (!invoke)
2338 root 1.221 {
2339 root 1.240 SV *old = PL_diehook;
2340     PL_diehook = 0;
2341     SvREFCNT_dec (old);
2342 root 1.221 croak ("\3async_pool terminate\2\n");
2343     }
2344 root 1.159
2345 root 1.184 SvREFCNT_dec (coro->saved_deffh);
2346 root 1.249 coro->saved_deffh = SvREFCNT_inc_NN ((SV *)PL_defoutgv);
2347 root 1.182
2348 root 1.159 hv_store (hv, "desc", sizeof ("desc") - 1,
2349 root 1.212 newSVpvn ("[async_pool]", sizeof ("[async_pool]") - 1), 0);
2350 root 1.159
2351     invoke_av = (AV *)SvRV (invoke);
2352     len = av_len (invoke_av);
2353    
2354 root 1.161 sv_setsv (cb, AvARRAY (invoke_av)[0]);
2355 root 1.159
2356     if (len > 0)
2357     {
2358 root 1.161 av_fill (defav, len - 1);
2359 root 1.159 for (i = 0; i < len; ++i)
2360 root 1.249 av_store (defav, i, SvREFCNT_inc_NN (AvARRAY (invoke_av)[i + 1]));
2361 root 1.159 }
2362    
2363     SvREFCNT_dec (invoke);
2364     }
2365    
2366     void
2367 root 1.161 _pool_2 (SV *cb)
2368 root 1.159 CODE:
2369     {
2370     struct coro *coro = SvSTATE (coro_current);
2371    
2372 root 1.161 sv_setsv (cb, &PL_sv_undef);
2373    
2374 root 1.184 SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh;
2375     coro->saved_deffh = 0;
2376 root 1.181
2377 root 1.255 if (coro_rss (aTHX_ coro) > SvUV (sv_pool_rss)
2378 root 1.159 || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size))
2379 root 1.221 {
2380 root 1.240 SV *old = PL_diehook;
2381     PL_diehook = 0;
2382     SvREFCNT_dec (old);
2383 root 1.221 croak ("\3async_pool terminate\2\n");
2384     }
2385 root 1.159
2386     av_clear (GvAV (PL_defgv));
2387 root 1.212 hv_store ((HV *)SvRV (coro_current), "desc", sizeof ("desc") - 1,
2388     newSVpvn ("[async_pool idle]", sizeof ("[async_pool idle]") - 1), 0);
2389 root 1.175
2390 root 1.159 coro->prio = 0;
2391 root 1.173
2392     if (coro->cctx && (coro->cctx->flags & CC_TRACE))
2393 root 1.174 api_trace (coro_current, 0);
2394 root 1.173
2395 root 1.159 av_push (av_async_pool, newSVsv (coro_current));
2396     }
2397    
2398 root 1.243 #if 0
2399    
2400     void
2401     _generator_call (...)
2402     PROTOTYPE: @
2403     PPCODE:
2404     fprintf (stderr, "call %p\n", CvXSUBANY(cv).any_ptr);
2405     xxxx
2406     abort ();
2407    
2408     SV *
2409     gensub (SV *sub, ...)
2410     PROTOTYPE: &;@
2411     CODE:
2412     {
2413     struct coro *coro;
2414     MAGIC *mg;
2415     CV *xcv;
2416     CV *ncv = (CV *)newSV_type (SVt_PVCV);
2417     int i;
2418    
2419     CvGV (ncv) = CvGV (cv);
2420     CvFILE (ncv) = CvFILE (cv);
2421    
2422     Newz (0, coro, 1, struct coro);
2423     coro->args = newAV ();
2424     coro->flags = CF_NEW;
2425    
2426     av_extend (coro->args, items - 1);
2427     for (i = 1; i < items; i++)
2428     av_push (coro->args, newSVsv (ST (i)));
2429    
2430     CvISXSUB_on (ncv);
2431     CvXSUBANY (ncv).any_ptr = (void *)coro;
2432    
2433     xcv = GvCV (gv_fetchpv ("Coro::_generator_call", 0, SVt_PVCV));
2434    
2435     CvXSUB (ncv) = CvXSUB (xcv);
2436     CvANON_on (ncv);
2437    
2438     mg = sv_magicext ((SV *)ncv, 0, CORO_MAGIC_type_state, &coro_gensub_vtbl, (char *)coro, 0);
2439     RETVAL = newRV_noinc ((SV *)ncv);
2440     }
2441     OUTPUT:
2442     RETVAL
2443    
2444     #endif
2445    
2446 root 1.159
2447 root 1.89 MODULE = Coro::State PACKAGE = Coro::AIO
2448    
2449 root 1.249 void
2450     _get_state (SV *self)
2451     PPCODE:
2452 root 1.70 {
2453 root 1.249 AV *defav = GvAV (PL_defgv);
2454     AV *av = newAV ();
2455     int i;
2456     SV *data_sv = newSV (sizeof (struct io_state));
2457     struct io_state *data = (struct io_state *)SvPVX (data_sv);
2458     SvCUR_set (data_sv, sizeof (struct io_state));
2459     SvPOK_only (data_sv);
2460 root 1.120
2461     data->errorno = errno;
2462     data->laststype = PL_laststype;
2463     data->laststatval = PL_laststatval;
2464     data->statcache = PL_statcache;
2465 root 1.249
2466     av_extend (av, AvFILLp (defav) + 1 + 1);
2467    
2468     for (i = 0; i <= AvFILLp (defav); ++i)
2469     av_push (av, SvREFCNT_inc_NN (AvARRAY (defav)[i]));
2470    
2471     av_push (av, data_sv);
2472    
2473     XPUSHs (sv_2mortal (newRV_noinc ((SV *)av)));
2474    
2475     api_ready (self);
2476 root 1.70 }
2477    
2478     void
2479 root 1.249 _set_state (SV *state)
2480 root 1.70 PROTOTYPE: $
2481 root 1.249 PPCODE:
2482 root 1.70 {
2483 root 1.249 AV *av = (AV *)SvRV (state);
2484     struct io_state *data = (struct io_state *)SvPVX (AvARRAY (av)[AvFILLp (av)]);
2485     int i;
2486 root 1.70
2487 root 1.120 errno = data->errorno;
2488     PL_laststype = data->laststype;
2489 root 1.70 PL_laststatval = data->laststatval;
2490 root 1.120 PL_statcache = data->statcache;
2491 root 1.249
2492     EXTEND (SP, AvFILLp (av));
2493     for (i = 0; i < AvFILLp (av); ++i)
2494     PUSHs (sv_2mortal (SvREFCNT_inc_NN (AvARRAY (av)[i])));
2495 root 1.70 }
2496 root 1.120
2497 root 1.233
2498     MODULE = Coro::State PACKAGE = Coro::AnyEvent
2499    
2500     BOOT:
2501     sv_activity = coro_get_sv (aTHX_ "Coro::AnyEvent::ACTIVITY", TRUE);
2502    
2503     SV *
2504 root 1.237 _schedule (...)
2505 root 1.233 PROTOTYPE: @
2506     CODE:
2507     {
2508     static int incede;
2509    
2510     api_cede_notself ();
2511    
2512     ++incede;
2513     while (coro_nready >= incede && api_cede ())
2514     ;
2515    
2516     sv_setsv (sv_activity, &PL_sv_undef);
2517     if (coro_nready >= incede)
2518     {
2519     PUSHMARK (SP);
2520     PUTBACK;
2521     call_pv ("Coro::AnyEvent::_activity", G_DISCARD | G_EVAL);
2522     SPAGAIN;
2523     }
2524    
2525     --incede;
2526     }
2527    
2528 root 1.246
2529     MODULE = Coro::State PACKAGE = PerlIO::cede
2530    
2531     BOOT:
2532     PerlIO_define_layer (aTHX_ &PerlIO_cede);
2533 root 1.263