ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/Coro/State.xs
(Generate patch)

Comparing Coro/Coro/State.xs (file contents):
Revision 1.309 by root, Wed Nov 19 15:29:57 2008 UTC vs.
Revision 1.384 by root, Thu Feb 17 01:32:18 2011 UTC

1/* this works around a bug in mingw32 providing a non-working setjmp */
2#define USE_NO_MINGW_SETJMP_TWO_ARGS
3
4#define NDEBUG 1
5
1#include "libcoro/coro.c" 6#include "libcoro/coro.c"
2 7
3#define PERL_NO_GET_CONTEXT 8#define PERL_NO_GET_CONTEXT
4#define PERL_EXT 9#define PERL_EXT
5 10
6#include "EXTERN.h" 11#include "EXTERN.h"
7#include "perl.h" 12#include "perl.h"
8#include "XSUB.h" 13#include "XSUB.h"
9#include "perliol.h" 14#include "perliol.h"
10 15
11#include "patchlevel.h" 16#include "schmorp.h"
12 17
13#include <stdio.h> 18#include <stdio.h>
14#include <errno.h> 19#include <errno.h>
15#include <assert.h> 20#include <assert.h>
21
22#ifndef SVs_PADSTALE
23# define SVs_PADSTALE 0
24#endif
16 25
17#ifdef WIN32 26#ifdef WIN32
18# undef setjmp 27# undef setjmp
19# undef longjmp 28# undef longjmp
20# undef _exit 29# undef _exit
51#endif 60#endif
52 61
53/* the maximum number of idle cctx that will be pooled */ 62/* the maximum number of idle cctx that will be pooled */
54static int cctx_max_idle = 4; 63static int cctx_max_idle = 4;
55 64
56#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#if !PERL_VERSION_ATLEAST (5,6,0)
63# 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/* 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/* 5.8.8 */
94#ifndef GV_NOTQUAL
95# define GV_NOTQUAL 0
96#endif
97#ifndef newSV
98# define newSV(l) NEWSV(0,l)
99#endif
100#ifndef CvISXSUB_on
101# define CvISXSUB_on(cv) (void)cv
102#endif
103
104/* 5.8.7 */
105#ifndef SvRV_set
106# define SvRV_set(s,v) SvRV(s) = (v)
107#endif
108
109#if !__i386 && !__x86_64 && !__powerpc && !__m68k && !__alpha && !__mips && !__sparc64 65#if !__i386 && !__x86_64 && !__powerpc && !__m68k && !__alpha && !__mips && !__sparc64
110# undef CORO_STACKGUARD 66# undef CORO_STACKGUARD
111#endif 67#endif
112 68
113#ifndef CORO_STACKGUARD 69#ifndef CORO_STACKGUARD
127#else 83#else
128# define dSTACKLEVEL volatile void *stacklevel 84# define dSTACKLEVEL volatile void *stacklevel
129# define STACKLEVEL ((void *)&stacklevel) 85# define STACKLEVEL ((void *)&stacklevel)
130#endif 86#endif
131 87
132#define IN_DESTRUCT (PL_main_cv == Nullcv) 88#define IN_DESTRUCT PL_dirty
133 89
134#if __GNUC__ >= 3 90#if __GNUC__ >= 3
135# define attribute(x) __attribute__(x) 91# define attribute(x) __attribute__(x)
136# define expect(expr,value) __builtin_expect ((expr),(value)) 92# define expect(expr,value) __builtin_expect ((expr), (value))
137# define INLINE static inline 93# define INLINE static inline
138#else 94#else
139# define attribute(x) 95# define attribute(x)
140# define expect(expr,value) (expr) 96# define expect(expr,value) (expr)
141# define INLINE static 97# define INLINE static
153# if CORO_PTHREAD 109# if CORO_PTHREAD
154static void *coro_thx; 110static void *coro_thx;
155# endif 111# endif
156#endif 112#endif
157 113
114#ifdef __linux
115# include <time.h> /* for timespec */
116# include <syscall.h> /* for SYS_* */
117# ifdef SYS_clock_gettime
118# define coro_clock_gettime(id, ts) syscall (SYS_clock_gettime, (id), (ts))
119# define CORO_CLOCK_MONOTONIC 1
120# define CORO_CLOCK_THREAD_CPUTIME_ID 3
121# endif
122#endif
123
158static double (*nvtime)(); /* so why doesn't it take void? */ 124static double (*nvtime)(); /* so why doesn't it take void? */
125static void (*u2time)(pTHX_ UV ret[2]);
159 126
160/* we hijack an hopefully unused CV flag for our purposes */ 127/* we hijack an hopefully unused CV flag for our purposes */
161#define CVf_SLF 0x4000 128#define CVf_SLF 0x4000
162static OP *pp_slf (pTHX); 129static OP *pp_slf (pTHX);
163 130
165static size_t cctx_stacksize = CORO_STACKSIZE; 132static size_t cctx_stacksize = CORO_STACKSIZE;
166static struct CoroAPI coroapi; 133static struct CoroAPI coroapi;
167static AV *main_mainstack; /* used to differentiate between $main and others */ 134static AV *main_mainstack; /* used to differentiate between $main and others */
168static JMPENV *main_top_env; 135static JMPENV *main_top_env;
169static HV *coro_state_stash, *coro_stash; 136static HV *coro_state_stash, *coro_stash;
170static CV *coro_run_cv;
171static volatile SV *coro_mortal; /* will be freed/thrown after next transfer */ 137static volatile SV *coro_mortal; /* will be freed/thrown after next transfer */
138
139static AV *av_destroy; /* destruction queue */
140static SV *sv_manager; /* the manager coro */
141static SV *sv_idle; /* $Coro::idle */
172 142
173static GV *irsgv; /* $/ */ 143static GV *irsgv; /* $/ */
174static GV *stdoutgv; /* *STDOUT */ 144static GV *stdoutgv; /* *STDOUT */
175static SV *rv_diehook; 145static SV *rv_diehook;
176static SV *rv_warnhook; 146static SV *rv_warnhook;
177static HV *hv_sig; /* %SIG */ 147static HV *hv_sig; /* %SIG */
178 148
179/* async_pool helper stuff */ 149/* async_pool helper stuff */
180static SV *sv_pool_rss; 150static SV *sv_pool_rss;
181static SV *sv_pool_size; 151static SV *sv_pool_size;
152static SV *sv_async_pool_idle; /* description string */
182static AV *av_async_pool; 153static AV *av_async_pool; /* idle pool */
154static SV *sv_Coro; /* class string */
155static CV *cv_pool_handler;
183 156
184/* Coro::AnyEvent */ 157/* Coro::AnyEvent */
185static SV *sv_activity; 158static SV *sv_activity;
159
160/* enable processtime/realtime profiling */
161static char enable_times;
162typedef U32 coro_ts[2];
163static coro_ts time_real, time_cpu;
164static char times_valid;
186 165
187static struct coro_cctx *cctx_first; 166static struct coro_cctx *cctx_first;
188static int cctx_count, cctx_idle; 167static int cctx_count, cctx_idle;
189 168
190enum { 169enum {
216 int valgrind_id; 195 int valgrind_id;
217#endif 196#endif
218 unsigned char flags; 197 unsigned char flags;
219} coro_cctx; 198} coro_cctx;
220 199
200coro_cctx *cctx_current; /* the currently running cctx */
201
202/*****************************************************************************/
203
221enum { 204enum {
222 CF_RUNNING = 0x0001, /* coroutine is running */ 205 CF_RUNNING = 0x0001, /* coroutine is running */
223 CF_READY = 0x0002, /* coroutine is ready */ 206 CF_READY = 0x0002, /* coroutine is ready */
224 CF_NEW = 0x0004, /* has never been switched to */ 207 CF_NEW = 0x0004, /* has never been switched to */
225 CF_DESTROYED = 0x0008, /* coroutine data has been freed */ 208 CF_DESTROYED = 0x0008, /* coroutine data has been freed */
209 CF_SUSPENDED = 0x0010, /* coroutine can't be scheduled */
226}; 210};
227 211
228/* the structure where most of the perl state is stored, overlaid on the cxstack */ 212/* the structure where most of the perl state is stored, overlaid on the cxstack */
229typedef struct 213typedef struct
230{ 214{
231 SV *defsv; 215 SV *defsv;
232 AV *defav; 216 AV *defav;
233 SV *errsv; 217 SV *errsv;
234 SV *irsgv; 218 SV *irsgv;
219 HV *hinthv;
235#define VAR(name,type) type name; 220#define VAR(name,type) type name;
236# include "state.h" 221# include "state.h"
237#undef VAR 222#undef VAR
238} perl_slots; 223} perl_slots;
239 224
241 226
242/* this is a structure representing a perl-level coroutine */ 227/* this is a structure representing a perl-level coroutine */
243struct coro { 228struct coro {
244 /* the C coroutine allocated to this perl coroutine, if any */ 229 /* the C coroutine allocated to this perl coroutine, if any */
245 coro_cctx *cctx; 230 coro_cctx *cctx;
231
232 /* ready queue */
233 struct coro *next_ready;
246 234
247 /* state data */ 235 /* state data */
248 struct CoroSLF slf_frame; /* saved slf frame */ 236 struct CoroSLF slf_frame; /* saved slf frame */
249 AV *mainstack; 237 AV *mainstack;
250 perl_slots *slot; /* basically the saved sp */ 238 perl_slots *slot; /* basically the saved sp */
252 CV *startcv; /* the CV to execute */ 240 CV *startcv; /* the CV to execute */
253 AV *args; /* data associated with this coroutine (initial args) */ 241 AV *args; /* data associated with this coroutine (initial args) */
254 int refcnt; /* coroutines are refcounted, yes */ 242 int refcnt; /* coroutines are refcounted, yes */
255 int flags; /* CF_ flags */ 243 int flags; /* CF_ flags */
256 HV *hv; /* the perl hash associated with this coro, if any */ 244 HV *hv; /* the perl hash associated with this coro, if any */
257 void (*on_destroy)(pTHX_ struct coro *coro); 245 void (*on_destroy)(pTHX_ struct coro *coro); /* for temporary use by xs in critical sections */
258 246
259 /* statistics */ 247 /* statistics */
260 int usecount; /* number of transfers to this coro */ 248 int usecount; /* number of transfers to this coro */
261 249
262 /* coro process data */ 250 /* coro process data */
264 SV *except; /* exception to be thrown */ 252 SV *except; /* exception to be thrown */
265 SV *rouse_cb; 253 SV *rouse_cb;
266 254
267 /* async_pool */ 255 /* async_pool */
268 SV *saved_deffh; 256 SV *saved_deffh;
257 SV *invoke_cb;
258 AV *invoke_av;
259
260 /* on_enter/on_leave */
261 AV *on_enter;
262 AV *on_leave;
263
264 /* swap_sv */
265 AV *swap_sv;
266
267 /* times */
268 coro_ts t_cpu, t_real;
269 269
270 /* linked list */ 270 /* linked list */
271 struct coro *next, *prev; 271 struct coro *next, *prev;
272}; 272};
273 273
279/* the mainr easonw e don't support windows process emulation */ 279/* the mainr easonw e don't support windows process emulation */
280static struct CoroSLF slf_frame; /* the current slf frame */ 280static struct CoroSLF slf_frame; /* the current slf frame */
281 281
282/** Coro ********************************************************************/ 282/** Coro ********************************************************************/
283 283
284#define PRIO_MAX 3 284#define CORO_PRIO_MAX 3
285#define PRIO_HIGH 1 285#define CORO_PRIO_HIGH 1
286#define PRIO_NORMAL 0 286#define CORO_PRIO_NORMAL 0
287#define PRIO_LOW -1 287#define CORO_PRIO_LOW -1
288#define PRIO_IDLE -3 288#define CORO_PRIO_IDLE -3
289#define PRIO_MIN -4 289#define CORO_PRIO_MIN -4
290 290
291/* for Coro.pm */ 291/* for Coro.pm */
292static SV *coro_current; 292static SV *coro_current;
293static SV *coro_readyhook; 293static SV *coro_readyhook;
294static AV *coro_ready [PRIO_MAX - PRIO_MIN + 1]; 294static struct coro *coro_ready [CORO_PRIO_MAX - CORO_PRIO_MIN + 1][2]; /* head|tail */
295static CV *cv_coro_run, *cv_coro_terminate;
295static struct coro *coro_first; 296static struct coro *coro_first;
296#define coro_nready coroapi.nready 297#define coro_nready coroapi.nready
298
299/** Coro::Select ************************************************************/
300
301static OP *(*coro_old_pp_sselect) (pTHX);
302static SV *coro_select_select;
303
304/* horrible hack, but if it works... */
305static OP *
306coro_pp_sselect (pTHX)
307{
308 dSP;
309 PUSHMARK (SP - 4); /* fake argument list */
310 XPUSHs (coro_select_select);
311 PUTBACK;
312
313 /* entersub is an UNOP, select a LISTOP... keep your fingers crossed */
314 PL_op->op_flags |= OPf_STACKED;
315 PL_op->op_private = 0;
316 return PL_ppaddr [OP_ENTERSUB](aTHX);
317}
297 318
298/** lowlevel stuff **********************************************************/ 319/** lowlevel stuff **********************************************************/
299 320
300static SV * 321static SV *
301coro_get_sv (pTHX_ const char *name, int create) 322coro_get_sv (pTHX_ const char *name, int create)
325 get_hv (name, create); 346 get_hv (name, create);
326#endif 347#endif
327 return get_hv (name, create); 348 return get_hv (name, create);
328} 349}
329 350
330/* may croak */ 351INLINE void
331INLINE CV * 352coro_times_update ()
332coro_sv_2cv (SV *sv)
333{ 353{
354#ifdef coro_clock_gettime
355 struct timespec ts;
356
357 ts.tv_sec = ts.tv_nsec = 0;
358 coro_clock_gettime (CORO_CLOCK_THREAD_CPUTIME_ID, &ts);
359 time_cpu [0] = ts.tv_sec; time_cpu [1] = ts.tv_nsec;
360
361 ts.tv_sec = ts.tv_nsec = 0;
362 coro_clock_gettime (CORO_CLOCK_MONOTONIC, &ts);
363 time_real [0] = ts.tv_sec; time_real [1] = ts.tv_nsec;
364#else
365 dTHX;
366 UV tv[2];
367
368 u2time (aTHX_ tv);
369 time_real [0] = tv [0];
370 time_real [1] = tv [1] * 1000;
371#endif
372}
373
374INLINE void
375coro_times_add (struct coro *c)
376{
377 c->t_real [1] += time_real [1];
378 if (c->t_real [1] > 1000000000) { c->t_real [1] -= 1000000000; ++c->t_real [0]; }
379 c->t_real [0] += time_real [0];
380
381 c->t_cpu [1] += time_cpu [1];
382 if (c->t_cpu [1] > 1000000000) { c->t_cpu [1] -= 1000000000; ++c->t_cpu [0]; }
383 c->t_cpu [0] += time_cpu [0];
384}
385
386INLINE void
387coro_times_sub (struct coro *c)
388{
389 if (c->t_real [1] < time_real [1]) { c->t_real [1] += 1000000000; --c->t_real [0]; }
390 c->t_real [1] -= time_real [1];
391 c->t_real [0] -= time_real [0];
392
393 if (c->t_cpu [1] < time_cpu [1]) { c->t_cpu [1] += 1000000000; --c->t_cpu [0]; }
394 c->t_cpu [1] -= time_cpu [1];
395 c->t_cpu [0] -= time_cpu [0];
396}
397
398/*****************************************************************************/
399/* magic glue */
400
401#define CORO_MAGIC_type_cv 26
402#define CORO_MAGIC_type_state PERL_MAGIC_ext
403
404#define CORO_MAGIC_NN(sv, type) \
405 (expect_true (SvMAGIC (sv)->mg_type == type) \
406 ? SvMAGIC (sv) \
407 : mg_find (sv, type))
408
409#define CORO_MAGIC(sv, type) \
410 (expect_true (SvMAGIC (sv)) \
411 ? CORO_MAGIC_NN (sv, type) \
412 : 0)
413
414#define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv)
415#define CORO_MAGIC_state(sv) CORO_MAGIC_NN (((SV *)(sv)), CORO_MAGIC_type_state)
416
417INLINE struct coro *
418SvSTATE_ (pTHX_ SV *coro)
419{
334 HV *st; 420 HV *stash;
335 GV *gvp; 421 MAGIC *mg;
336 return sv_2cv (sv, &st, &gvp, 0); 422
423 if (SvROK (coro))
424 coro = SvRV (coro);
425
426 if (expect_false (SvTYPE (coro) != SVt_PVHV))
427 croak ("Coro::State object required");
428
429 stash = SvSTASH (coro);
430 if (expect_false (stash != coro_stash && stash != coro_state_stash))
431 {
432 /* very slow, but rare, check */
433 if (!sv_derived_from (sv_2mortal (newRV_inc (coro)), "Coro::State"))
434 croak ("Coro::State object required");
435 }
436
437 mg = CORO_MAGIC_state (coro);
438 return (struct coro *)mg->mg_ptr;
337} 439}
440
441#define SvSTATE(sv) SvSTATE_ (aTHX_ (sv))
442
443/* faster than SvSTATE, but expects a coroutine hv */
444#define SvSTATE_hv(hv) ((struct coro *)CORO_MAGIC_NN ((SV *)hv, CORO_MAGIC_type_state)->mg_ptr)
445#define SvSTATE_current SvSTATE_hv (SvRV (coro_current))
446
447/*****************************************************************************/
448/* padlist management and caching */
338 449
339static AV * 450static AV *
340coro_clone_padlist (pTHX_ CV *cv) 451coro_derive_padlist (pTHX_ CV *cv)
341{ 452{
342 AV *padlist = CvPADLIST (cv); 453 AV *padlist = CvPADLIST (cv);
343 AV *newpadlist, *newpad; 454 AV *newpadlist, *newpad;
344 455
345 newpadlist = newAV (); 456 newpadlist = newAV ();
350 Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1, 1); 461 Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1, 1);
351#endif 462#endif
352 newpad = (AV *)AvARRAY (padlist)[AvFILLp (padlist)]; 463 newpad = (AV *)AvARRAY (padlist)[AvFILLp (padlist)];
353 --AvFILLp (padlist); 464 --AvFILLp (padlist);
354 465
355 av_store (newpadlist, 0, SvREFCNT_inc_NN (*av_fetch (padlist, 0, FALSE))); 466 av_store (newpadlist, 0, SvREFCNT_inc_NN (AvARRAY (padlist)[0]));
356 av_store (newpadlist, 1, (SV *)newpad); 467 av_store (newpadlist, 1, (SV *)newpad);
357 468
358 return newpadlist; 469 return newpadlist;
359} 470}
360 471
361static void 472static void
362free_padlist (pTHX_ AV *padlist) 473free_padlist (pTHX_ AV *padlist)
363{ 474{
364 /* may be during global destruction */ 475 /* may be during global destruction */
365 if (SvREFCNT (padlist)) 476 if (!IN_DESTRUCT)
366 { 477 {
367 I32 i = AvFILLp (padlist); 478 I32 i = AvFILLp (padlist);
368 while (i >= 0) 479
480 while (i > 0) /* special-case index 0 */
369 { 481 {
370 SV **svp = av_fetch (padlist, i--, FALSE); 482 /* we try to be extra-careful here */
371 if (svp) 483 AV *av = (AV *)AvARRAY (padlist)[i--];
372 { 484 I32 j = AvFILLp (av);
373 SV *sv; 485
374 while (&PL_sv_undef != (sv = av_pop ((AV *)*svp))) 486 while (j >= 0)
487 SvREFCNT_dec (AvARRAY (av)[j--]);
488
489 AvFILLp (av) = -1;
375 SvREFCNT_dec (sv); 490 SvREFCNT_dec (av);
376
377 SvREFCNT_dec (*svp);
378 }
379 } 491 }
380 492
493 SvREFCNT_dec (AvARRAY (padlist)[0]);
494
495 AvFILLp (padlist) = -1;
381 SvREFCNT_dec ((SV*)padlist); 496 SvREFCNT_dec ((SV*)padlist);
382 } 497 }
383} 498}
384 499
385static int 500static int
386coro_cv_free (pTHX_ SV *sv, MAGIC *mg) 501coro_cv_free (pTHX_ SV *sv, MAGIC *mg)
387{ 502{
388 AV *padlist; 503 AV *padlist;
389 AV *av = (AV *)mg->mg_obj; 504 AV *av = (AV *)mg->mg_obj;
505
506 /* perl manages to free our internal AV and _then_ call us */
507 if (IN_DESTRUCT)
508 return 0;
390 509
391 /* casting is fun. */ 510 /* casting is fun. */
392 while (&PL_sv_undef != (SV *)(padlist = (AV *)av_pop (av))) 511 while (&PL_sv_undef != (SV *)(padlist = (AV *)av_pop (av)))
393 free_padlist (aTHX_ padlist); 512 free_padlist (aTHX_ padlist);
394 513
395 SvREFCNT_dec (av); /* sv_magicext increased the refcount */ 514 SvREFCNT_dec (av); /* sv_magicext increased the refcount */
396 515
397 return 0; 516 return 0;
398} 517}
399
400#define CORO_MAGIC_type_cv 26
401#define CORO_MAGIC_type_state PERL_MAGIC_ext
402 518
403static MGVTBL coro_cv_vtbl = { 519static MGVTBL coro_cv_vtbl = {
404 0, 0, 0, 0, 520 0, 0, 0, 0,
405 coro_cv_free 521 coro_cv_free
406}; 522};
407
408#define CORO_MAGIC_NN(sv, type) \
409 (expect_true (SvMAGIC (sv)->mg_type == type) \
410 ? SvMAGIC (sv) \
411 : mg_find (sv, type))
412
413#define CORO_MAGIC(sv, type) \
414 (expect_true (SvMAGIC (sv)) \
415 ? CORO_MAGIC_NN (sv, type) \
416 : 0)
417
418#define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv)
419#define CORO_MAGIC_state(sv) CORO_MAGIC_NN (((SV *)(sv)), CORO_MAGIC_type_state)
420
421INLINE struct coro *
422SvSTATE_ (pTHX_ SV *coro)
423{
424 HV *stash;
425 MAGIC *mg;
426
427 if (SvROK (coro))
428 coro = SvRV (coro);
429
430 if (expect_false (SvTYPE (coro) != SVt_PVHV))
431 croak ("Coro::State object required");
432
433 stash = SvSTASH (coro);
434 if (expect_false (stash != coro_stash && stash != coro_state_stash))
435 {
436 /* very slow, but rare, check */
437 if (!sv_derived_from (sv_2mortal (newRV_inc (coro)), "Coro::State"))
438 croak ("Coro::State object required");
439 }
440
441 mg = CORO_MAGIC_state (coro);
442 return (struct coro *)mg->mg_ptr;
443}
444
445#define SvSTATE(sv) SvSTATE_ (aTHX_ (sv))
446
447/* faster than SvSTATE, but expects a coroutine hv */
448#define SvSTATE_hv(hv) ((struct coro *)CORO_MAGIC_NN ((SV *)hv, CORO_MAGIC_type_state)->mg_ptr)
449#define SvSTATE_current SvSTATE_hv (SvRV (coro_current))
450 523
451/* the next two functions merely cache the padlists */ 524/* the next two functions merely cache the padlists */
452static void 525static void
453get_padlist (pTHX_ CV *cv) 526get_padlist (pTHX_ CV *cv)
454{ 527{
465 CV *cp = Perl_cv_clone (aTHX_ cv); 538 CV *cp = Perl_cv_clone (aTHX_ cv);
466 CvPADLIST (cv) = CvPADLIST (cp); 539 CvPADLIST (cv) = CvPADLIST (cp);
467 CvPADLIST (cp) = 0; 540 CvPADLIST (cp) = 0;
468 SvREFCNT_dec (cp); 541 SvREFCNT_dec (cp);
469#else 542#else
470 CvPADLIST (cv) = coro_clone_padlist (aTHX_ cv); 543 CvPADLIST (cv) = coro_derive_padlist (aTHX_ cv);
471#endif 544#endif
472 } 545 }
473} 546}
474 547
475static void 548static void
482 mg = sv_magicext ((SV *)cv, (SV *)newAV (), CORO_MAGIC_type_cv, &coro_cv_vtbl, 0, 0); 555 mg = sv_magicext ((SV *)cv, (SV *)newAV (), CORO_MAGIC_type_cv, &coro_cv_vtbl, 0, 0);
483 556
484 av = (AV *)mg->mg_obj; 557 av = (AV *)mg->mg_obj;
485 558
486 if (expect_false (AvFILLp (av) >= AvMAX (av))) 559 if (expect_false (AvFILLp (av) >= AvMAX (av)))
487 av_extend (av, AvMAX (av) + 1); 560 av_extend (av, AvFILLp (av) + 1);
488 561
489 AvARRAY (av)[++AvFILLp (av)] = (SV *)CvPADLIST (cv); 562 AvARRAY (av)[++AvFILLp (av)] = (SV *)CvPADLIST (cv);
490} 563}
491 564
492/** load & save, init *******************************************************/ 565/** load & save, init *******************************************************/
566
567/* swap sv heads, at least logically */
568static void
569swap_svs (pTHX_ Coro__State c)
570{
571 int i;
572
573 for (i = 0; i <= AvFILLp (c->swap_sv); )
574 {
575 SV *a = AvARRAY (c->swap_sv)[i++];
576 SV *b = AvARRAY (c->swap_sv)[i++];
577
578 const U32 keep = SVs_PADSTALE | SVs_PADTMP | SVs_PADMY; /* keep these flags */
579 SV tmp;
580
581 /* swap sv_any */
582 SvANY (&tmp) = SvANY (a); SvANY (a) = SvANY (b); SvANY (b) = SvANY (&tmp);
583
584 /* swap sv_flags */
585 SvFLAGS (&tmp) = SvFLAGS (a);
586 SvFLAGS (a) = (SvFLAGS (a) & keep) | (SvFLAGS (b ) & ~keep);
587 SvFLAGS (b) = (SvFLAGS (b) & keep) | (SvFLAGS (&tmp) & ~keep);
588
589#if PERL_VERSION_ATLEAST (5,10,0)
590 /* perl 5.10 complicates this _quite_ a bit, but it also is
591 * is much faster, so no quarrels here. alternatively, we could
592 * sv_upgrade to avoid this.
593 */
594 {
595 /* swap sv_u */
596 tmp.sv_u = a->sv_u; a->sv_u = b->sv_u; b->sv_u = tmp.sv_u;
597
598 /* if SvANY points to the head, we need to adjust the pointers,
599 * as the pointer for a still points to b, and maybe vice versa.
600 */
601 #define svany_in_head(type) \
602 (((1 << SVt_NULL) | (1 << SVt_BIND) | (1 << SVt_IV) | (1 << SVt_RV)) & (1 << (type)))
603
604 if (svany_in_head (SvTYPE (a)))
605 SvANY (a) = (void *)((PTRV)SvANY (a) - (PTRV)b + (PTRV)a);
606
607 if (svany_in_head (SvTYPE (b)))
608 SvANY (b) = (void *)((PTRV)SvANY (b) - (PTRV)a + (PTRV)b);
609 }
610#endif
611 }
612}
613
614#define SWAP_SVS(coro) \
615 if (expect_false ((coro)->swap_sv)) \
616 swap_svs (aTHX_ (coro))
617
618static void
619on_enterleave_call (pTHX_ SV *cb);
493 620
494static void 621static void
495load_perl (pTHX_ Coro__State c) 622load_perl (pTHX_ Coro__State c)
496{ 623{
497 perl_slots *slot = c->slot; 624 perl_slots *slot = c->slot;
498 c->slot = 0; 625 c->slot = 0;
499 626
500 PL_mainstack = c->mainstack; 627 PL_mainstack = c->mainstack;
501 628
502 GvSV (PL_defgv) = slot->defsv; 629 GvSV (PL_defgv) = slot->defsv;
503 GvAV (PL_defgv) = slot->defav; 630 GvAV (PL_defgv) = slot->defav;
504 GvSV (PL_errgv) = slot->errsv; 631 GvSV (PL_errgv) = slot->errsv;
505 GvSV (irsgv) = slot->irsgv; 632 GvSV (irsgv) = slot->irsgv;
633 GvHV (PL_hintgv) = slot->hinthv;
506 634
507 #define VAR(name,type) PL_ ## name = slot->name; 635 #define VAR(name,type) PL_ ## name = slot->name;
508 # include "state.h" 636 # include "state.h"
509 #undef VAR 637 #undef VAR
510 638
524 PUTBACK; 652 PUTBACK;
525 } 653 }
526 654
527 slf_frame = c->slf_frame; 655 slf_frame = c->slf_frame;
528 CORO_THROW = c->except; 656 CORO_THROW = c->except;
657
658 if (expect_false (enable_times))
659 {
660 if (expect_false (!times_valid))
661 coro_times_update ();
662
663 coro_times_sub (c);
664 }
665
666 if (expect_false (c->on_enter))
667 {
668 int i;
669
670 for (i = 0; i <= AvFILLp (c->on_enter); ++i)
671 on_enterleave_call (aTHX_ AvARRAY (c->on_enter)[i]);
672 }
673
674 SWAP_SVS (c);
529} 675}
530 676
531static void 677static void
532save_perl (pTHX_ Coro__State c) 678save_perl (pTHX_ Coro__State c)
533{ 679{
680 SWAP_SVS (c);
681
682 if (expect_false (c->on_leave))
683 {
684 int i;
685
686 for (i = AvFILLp (c->on_leave); i >= 0; --i)
687 on_enterleave_call (aTHX_ AvARRAY (c->on_leave)[i]);
688 }
689
690 times_valid = 0;
691
692 if (expect_false (enable_times))
693 {
694 coro_times_update (); times_valid = 1;
695 coro_times_add (c);
696 }
697
534 c->except = CORO_THROW; 698 c->except = CORO_THROW;
535 c->slf_frame = slf_frame; 699 c->slf_frame = slf_frame;
536 700
537 { 701 {
538 dSP; 702 dSP;
551 { 715 {
552 while (expect_true (cxix >= 0)) 716 while (expect_true (cxix >= 0))
553 { 717 {
554 PERL_CONTEXT *cx = &ccstk[cxix--]; 718 PERL_CONTEXT *cx = &ccstk[cxix--];
555 719
556 if (expect_true (CxTYPE (cx) == CXt_SUB || CxTYPE (cx) == CXt_FORMAT)) 720 if (expect_true (CxTYPE (cx) == CXt_SUB) || expect_false (CxTYPE (cx) == CXt_FORMAT))
557 { 721 {
558 CV *cv = cx->blk_sub.cv; 722 CV *cv = cx->blk_sub.cv;
559 723
560 if (expect_true (CvDEPTH (cv))) 724 if (expect_true (CvDEPTH (cv)))
561 { 725 {
585 /* we manually unroll here, as usually 2 slots is enough */ 749 /* we manually unroll here, as usually 2 slots is enough */
586 if (SLOT_COUNT >= 1) CXINC; 750 if (SLOT_COUNT >= 1) CXINC;
587 if (SLOT_COUNT >= 2) CXINC; 751 if (SLOT_COUNT >= 2) CXINC;
588 if (SLOT_COUNT >= 3) CXINC; 752 if (SLOT_COUNT >= 3) CXINC;
589 { 753 {
590 int i; 754 unsigned int i;
591 for (i = 3; i < SLOT_COUNT; ++i) 755 for (i = 3; i < SLOT_COUNT; ++i)
592 CXINC; 756 CXINC;
593 } 757 }
594 cxstack_ix -= SLOT_COUNT; /* undo allocation */ 758 cxstack_ix -= SLOT_COUNT; /* undo allocation */
595 759
596 c->mainstack = PL_mainstack; 760 c->mainstack = PL_mainstack;
597 761
598 { 762 {
599 perl_slots *slot = c->slot = (perl_slots *)(cxstack + cxstack_ix + 1); 763 perl_slots *slot = c->slot = (perl_slots *)(cxstack + cxstack_ix + 1);
600 764
601 slot->defav = GvAV (PL_defgv); 765 slot->defav = GvAV (PL_defgv);
602 slot->defsv = DEFSV; 766 slot->defsv = DEFSV;
603 slot->errsv = ERRSV; 767 slot->errsv = ERRSV;
604 slot->irsgv = GvSV (irsgv); 768 slot->irsgv = GvSV (irsgv);
769 slot->hinthv = GvHV (PL_hintgv);
605 770
606 #define VAR(name,type) slot->name = PL_ ## name; 771 #define VAR(name,type) slot->name = PL_ ## name;
607 # include "state.h" 772 # include "state.h"
608 #undef VAR 773 #undef VAR
609 } 774 }
687#if !PERL_VERSION_ATLEAST (5,10,0) 852#if !PERL_VERSION_ATLEAST (5,10,0)
688 Safefree (PL_retstack); 853 Safefree (PL_retstack);
689#endif 854#endif
690} 855}
691 856
857#define CORO_RSS \
858 rss += sizeof (SYM (curstackinfo)); \
859 rss += (SYM (curstackinfo->si_cxmax) + 1) * sizeof (PERL_CONTEXT); \
860 rss += sizeof (SV) + sizeof (struct xpvav) + (1 + AvMAX (SYM (curstack))) * sizeof (SV *); \
861 rss += SYM (tmps_max) * sizeof (SV *); \
862 rss += (SYM (markstack_max) - SYM (markstack_ptr)) * sizeof (I32); \
863 rss += SYM (scopestack_max) * sizeof (I32); \
864 rss += SYM (savestack_max) * sizeof (ANY);
865
692static size_t 866static size_t
693coro_rss (pTHX_ struct coro *coro) 867coro_rss (pTHX_ struct coro *coro)
694{ 868{
695 size_t rss = sizeof (*coro); 869 size_t rss = sizeof (*coro);
696 870
697 if (coro->mainstack) 871 if (coro->mainstack)
698 { 872 {
699 perl_slots tmp_slot;
700 perl_slots *slot;
701
702 if (coro->flags & CF_RUNNING) 873 if (coro->flags & CF_RUNNING)
703 { 874 {
704 slot = &tmp_slot; 875 #define SYM(sym) PL_ ## sym
705 876 CORO_RSS;
706 #define VAR(name,type) slot->name = PL_ ## name;
707 # include "state.h"
708 #undef VAR 877 #undef SYM
709 } 878 }
710 else 879 else
711 slot = coro->slot;
712
713 if (slot)
714 { 880 {
715 rss += sizeof (slot->curstackinfo); 881 #define SYM(sym) coro->slot->sym
716 rss += (slot->curstackinfo->si_cxmax + 1) * sizeof (PERL_CONTEXT); 882 CORO_RSS;
717 rss += sizeof (SV) + sizeof (struct xpvav) + (1 + AvMAX (slot->curstack)) * sizeof (SV *); 883 #undef SYM
718 rss += slot->tmps_max * sizeof (SV *);
719 rss += (slot->markstack_max - slot->markstack_ptr) * sizeof (I32);
720 rss += slot->scopestack_max * sizeof (I32);
721 rss += slot->savestack_max * sizeof (ANY);
722
723#if !PERL_VERSION_ATLEAST (5,10,0)
724 rss += slot->retstack_max * sizeof (OP *);
725#endif
726 } 884 }
727 } 885 }
728 886
729 return rss; 887 return rss;
730} 888}
743#endif 901#endif
744 902
745/* 903/*
746 * This overrides the default magic get method of %SIG elements. 904 * This overrides the default magic get method of %SIG elements.
747 * The original one doesn't provide for reading back of PL_diehook/PL_warnhook 905 * The original one doesn't provide for reading back of PL_diehook/PL_warnhook
748 * and instead of tryign to save and restore the hash elements, we just provide 906 * and instead of trying to save and restore the hash elements, we just provide
749 * readback here. 907 * readback here.
750 * We only do this when the hook is != 0, as they are often set to 0 temporarily,
751 * not expecting this to actually change the hook. This is a potential problem
752 * when a schedule happens then, but we ignore this.
753 */ 908 */
754static int 909static int
755coro_sigelem_get (pTHX_ SV *sv, MAGIC *mg) 910coro_sigelem_get (pTHX_ SV *sv, MAGIC *mg)
756{ 911{
757 const char *s = MgPV_nolen_const (mg); 912 const char *s = MgPV_nolen_const (mg);
810 if (strEQ (s, "__WARN__")) svp = &PL_warnhook; 965 if (strEQ (s, "__WARN__")) svp = &PL_warnhook;
811 966
812 if (svp) 967 if (svp)
813 { 968 {
814 SV *old = *svp; 969 SV *old = *svp;
815 *svp = newSVsv (sv); 970 *svp = SvOK (sv) ? newSVsv (sv) : 0;
816 SvREFCNT_dec (old); 971 SvREFCNT_dec (old);
817 return 0; 972 return 0;
818 } 973 }
819 } 974 }
820 975
832slf_check_nop (pTHX_ struct CoroSLF *frame) 987slf_check_nop (pTHX_ struct CoroSLF *frame)
833{ 988{
834 return 0; 989 return 0;
835} 990}
836 991
837static UNOP coro_setup_op; 992static int
993slf_check_repeat (pTHX_ struct CoroSLF *frame)
994{
995 return 1;
996}
997
998static UNOP init_perl_op;
838 999
839static void NOINLINE /* noinline to keep it out of the transfer fast path */ 1000static void NOINLINE /* noinline to keep it out of the transfer fast path */
840coro_setup (pTHX_ struct coro *coro) 1001init_perl (pTHX_ struct coro *coro)
841{ 1002{
842 /* 1003 /*
843 * emulate part of the perl startup here. 1004 * emulate part of the perl startup here.
844 */ 1005 */
845 coro_init_stacks (aTHX); 1006 coro_init_stacks (aTHX);
846 1007
847 PL_runops = RUNOPS_DEFAULT; 1008 PL_runops = RUNOPS_DEFAULT;
848 PL_curcop = &PL_compiling; 1009 PL_curcop = &PL_compiling;
849 PL_in_eval = EVAL_NULL; 1010 PL_in_eval = EVAL_NULL;
850 PL_comppad = 0; 1011 PL_comppad = 0;
1012 PL_comppad_name = 0;
1013 PL_comppad_name_fill = 0;
1014 PL_comppad_name_floor = 0;
851 PL_curpm = 0; 1015 PL_curpm = 0;
852 PL_curpad = 0; 1016 PL_curpad = 0;
853 PL_localizing = 0; 1017 PL_localizing = 0;
854 PL_dirty = 0;
855 PL_restartop = 0; 1018 PL_restartop = 0;
856#if PERL_VERSION_ATLEAST (5,10,0) 1019#if PERL_VERSION_ATLEAST (5,10,0)
857 PL_parser = 0; 1020 PL_parser = 0;
858#endif 1021#endif
1022 PL_hints = 0;
859 1023
860 /* recreate the die/warn hooks */ 1024 /* recreate the die/warn hooks */
861 PL_diehook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__DIE__" , sizeof ("__DIE__" ) - 1, 1), rv_diehook ); 1025 PL_diehook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__DIE__" , sizeof ("__DIE__" ) - 1, 1), rv_diehook );
862 PL_warnhook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__WARN__", sizeof ("__WARN__") - 1, 1), rv_warnhook); 1026 PL_warnhook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__WARN__", sizeof ("__WARN__") - 1, 1), rv_warnhook);
863 1027
864 GvSV (PL_defgv) = newSV (0); 1028 GvSV (PL_defgv) = newSV (0);
865 GvAV (PL_defgv) = coro->args; coro->args = 0; 1029 GvAV (PL_defgv) = coro->args; coro->args = 0;
866 GvSV (PL_errgv) = newSV (0); 1030 GvSV (PL_errgv) = newSV (0);
867 GvSV (irsgv) = newSVpvn ("\n", 1); sv_magic (GvSV (irsgv), (SV *)irsgv, PERL_MAGIC_sv, "/", 0); 1031 GvSV (irsgv) = newSVpvn ("\n", 1); sv_magic (GvSV (irsgv), (SV *)irsgv, PERL_MAGIC_sv, "/", 0);
1032 GvHV (PL_hintgv) = 0;
868 PL_rs = newSVsv (GvSV (irsgv)); 1033 PL_rs = newSVsv (GvSV (irsgv));
869 PL_defoutgv = (GV *)SvREFCNT_inc_NN (stdoutgv); 1034 PL_defoutgv = (GV *)SvREFCNT_inc_NN (stdoutgv);
870 1035
871 { 1036 {
872 dSP; 1037 dSP;
889 */ 1054 */
890 slf_frame.prepare = prepare_nop; /* provide a nop function for an eventual pp_slf */ 1055 slf_frame.prepare = prepare_nop; /* provide a nop function for an eventual pp_slf */
891 slf_frame.check = slf_check_nop; /* signal pp_slf to not repeat */ 1056 slf_frame.check = slf_check_nop; /* signal pp_slf to not repeat */
892 1057
893 /* and we have to provide the pp_slf op in any case, so pp_slf can skip it */ 1058 /* and we have to provide the pp_slf op in any case, so pp_slf can skip it */
894 coro_setup_op.op_next = PL_op; 1059 init_perl_op.op_next = PL_op;
895 coro_setup_op.op_type = OP_CUSTOM; 1060 init_perl_op.op_type = OP_ENTERSUB;
896 coro_setup_op.op_ppaddr = pp_slf; 1061 init_perl_op.op_ppaddr = pp_slf;
897 /* no flags etc. required, as an init function won't be called */ 1062 /* no flags etc. required, as an init function won't be called */
898 1063
899 PL_op = (OP *)&coro_setup_op; 1064 PL_op = (OP *)&init_perl_op;
900 1065
901 /* copy throw, in case it was set before coro_setup */ 1066 /* copy throw, in case it was set before init_perl */
902 CORO_THROW = coro->except; 1067 CORO_THROW = coro->except;
903}
904 1068
1069 SWAP_SVS (coro);
1070
1071 if (expect_false (enable_times))
1072 {
1073 coro_times_update ();
1074 coro_times_sub (coro);
1075 }
1076}
1077
905static void 1078static void
906coro_destruct (pTHX_ struct coro *coro) 1079coro_unwind_stacks (pTHX)
907{ 1080{
908 if (!IN_DESTRUCT) 1081 if (!IN_DESTRUCT)
909 { 1082 {
910 /* restore all saved variables and stuff */ 1083 /* restore all saved variables and stuff */
911 LEAVE_SCOPE (0); 1084 LEAVE_SCOPE (0);
919 POPSTACK_TO (PL_mainstack); 1092 POPSTACK_TO (PL_mainstack);
920 1093
921 /* unwind main stack */ 1094 /* unwind main stack */
922 dounwind (-1); 1095 dounwind (-1);
923 } 1096 }
1097}
924 1098
925 SvREFCNT_dec (GvSV (PL_defgv)); 1099static void
926 SvREFCNT_dec (GvAV (PL_defgv)); 1100destroy_perl (pTHX_ struct coro *coro)
927 SvREFCNT_dec (GvSV (PL_errgv)); 1101{
928 SvREFCNT_dec (PL_defoutgv); 1102 SV *svf [9];
929 SvREFCNT_dec (PL_rs);
930 SvREFCNT_dec (GvSV (irsgv));
931 1103
932 SvREFCNT_dec (PL_diehook);
933 SvREFCNT_dec (PL_warnhook);
934 1104 {
1105 struct coro *current = SvSTATE_current;
1106
1107 assert (("FATAL: tried to destroy currently running coroutine", coro->mainstack != PL_mainstack));
1108
1109 save_perl (aTHX_ current);
1110 load_perl (aTHX_ coro);
1111
1112 coro_unwind_stacks (aTHX);
1113 coro_destruct_stacks (aTHX);
1114
1115 /* restore swapped sv's */
1116 SWAP_SVS (coro);
1117
1118 // now save some sv's to be free'd later
1119 svf [0] = GvSV (PL_defgv);
1120 svf [1] = (SV *)GvAV (PL_defgv);
1121 svf [2] = GvSV (PL_errgv);
1122 svf [3] = (SV *)PL_defoutgv;
1123 svf [4] = PL_rs;
1124 svf [5] = GvSV (irsgv);
1125 svf [6] = (SV *)GvHV (PL_hintgv);
1126 svf [7] = PL_diehook;
1127 svf [8] = PL_warnhook;
1128 assert (9 == sizeof (svf) / sizeof (*svf));
1129
1130 load_perl (aTHX_ current);
1131 }
1132
1133 {
1134 unsigned int i;
1135
1136 for (i = 0; i < sizeof (svf) / sizeof (*svf); ++i)
1137 SvREFCNT_dec (svf [i]);
1138
935 SvREFCNT_dec (coro->saved_deffh); 1139 SvREFCNT_dec (coro->saved_deffh);
936 SvREFCNT_dec (coro->rouse_cb); 1140 SvREFCNT_dec (coro->rouse_cb);
937 1141 SvREFCNT_dec (coro->invoke_cb);
938 coro_destruct_stacks (aTHX); 1142 SvREFCNT_dec (coro->invoke_av);
1143 }
939} 1144}
940 1145
941INLINE void 1146INLINE void
942free_coro_mortal (pTHX) 1147free_coro_mortal (pTHX)
943{ 1148{
951static int 1156static int
952runops_trace (pTHX) 1157runops_trace (pTHX)
953{ 1158{
954 COP *oldcop = 0; 1159 COP *oldcop = 0;
955 int oldcxix = -2; 1160 int oldcxix = -2;
956 struct coro *coro = SvSTATE_current; /* trace cctx is tied to specific coro */
957 coro_cctx *cctx = coro->cctx;
958 1161
959 while ((PL_op = CALL_FPTR (PL_op->op_ppaddr) (aTHX))) 1162 while ((PL_op = CALL_FPTR (PL_op->op_ppaddr) (aTHX)))
960 { 1163 {
961 PERL_ASYNC_CHECK (); 1164 PERL_ASYNC_CHECK ();
962 1165
963 if (cctx->flags & CC_TRACE_ALL) 1166 if (cctx_current->flags & CC_TRACE_ALL)
964 { 1167 {
965 if (PL_op->op_type == OP_LEAVESUB && cctx->flags & CC_TRACE_SUB) 1168 if (PL_op->op_type == OP_LEAVESUB && cctx_current->flags & CC_TRACE_SUB)
966 { 1169 {
967 PERL_CONTEXT *cx = &cxstack[cxstack_ix]; 1170 PERL_CONTEXT *cx = &cxstack[cxstack_ix];
968 SV **bot, **top; 1171 SV **bot, **top;
969 AV *av = newAV (); /* return values */ 1172 AV *av = newAV (); /* return values */
970 SV **cb; 1173 SV **cb;
1007 1210
1008 if (PL_curcop != &PL_compiling) 1211 if (PL_curcop != &PL_compiling)
1009 { 1212 {
1010 SV **cb; 1213 SV **cb;
1011 1214
1012 if (oldcxix != cxstack_ix && cctx->flags & CC_TRACE_SUB) 1215 if (oldcxix != cxstack_ix && cctx_current->flags & CC_TRACE_SUB)
1013 { 1216 {
1014 PERL_CONTEXT *cx = &cxstack[cxstack_ix]; 1217 PERL_CONTEXT *cx = &cxstack[cxstack_ix];
1015 1218
1016 if (CxTYPE (cx) == CXt_SUB && oldcxix < cxstack_ix) 1219 if (CxTYPE (cx) == CXt_SUB && oldcxix < cxstack_ix)
1017 { 1220 {
1018 runops_proc_t old_runops = PL_runops;
1019 dSP; 1221 dSP;
1020 GV *gv = CvGV (cx->blk_sub.cv); 1222 GV *gv = CvGV (cx->blk_sub.cv);
1021 SV *fullname = sv_2mortal (newSV (0)); 1223 SV *fullname = sv_2mortal (newSV (0));
1022 1224
1023 if (isGV (gv)) 1225 if (isGV (gv))
1041 } 1243 }
1042 1244
1043 oldcxix = cxstack_ix; 1245 oldcxix = cxstack_ix;
1044 } 1246 }
1045 1247
1046 if (cctx->flags & CC_TRACE_LINE) 1248 if (cctx_current->flags & CC_TRACE_LINE)
1047 { 1249 {
1048 dSP; 1250 dSP;
1049 1251
1050 PL_runops = RUNOPS_DEFAULT; 1252 PL_runops = RUNOPS_DEFAULT;
1051 ENTER; 1253 ENTER;
1070 1272
1071 TAINT_NOT; 1273 TAINT_NOT;
1072 return 0; 1274 return 0;
1073} 1275}
1074 1276
1075static struct coro_cctx *cctx_ssl_cctx;
1076static struct CoroSLF cctx_ssl_frame; 1277static struct CoroSLF cctx_ssl_frame;
1077 1278
1078static void 1279static void
1079slf_prepare_set_stacklevel (pTHX_ struct coro_transfer_args *ta) 1280slf_prepare_set_stacklevel (pTHX_ struct coro_transfer_args *ta)
1080{ 1281{
1081 ta->prev = (struct coro *)cctx_ssl_cctx;
1082 ta->next = 0; 1282 ta->prev = 0;
1083} 1283}
1084 1284
1085static int 1285static int
1086slf_check_set_stacklevel (pTHX_ struct CoroSLF *frame) 1286slf_check_set_stacklevel (pTHX_ struct CoroSLF *frame)
1087{ 1287{
1090 return frame->check (aTHX_ frame); /* execute the restored frame - there must be one */ 1290 return frame->check (aTHX_ frame); /* execute the restored frame - there must be one */
1091} 1291}
1092 1292
1093/* initialises PL_top_env and injects a pseudo-slf-call to set the stacklevel */ 1293/* initialises PL_top_env and injects a pseudo-slf-call to set the stacklevel */
1094static void NOINLINE 1294static void NOINLINE
1095cctx_prepare (pTHX_ coro_cctx *cctx) 1295cctx_prepare (pTHX)
1096{ 1296{
1097 PL_top_env = &PL_start_env; 1297 PL_top_env = &PL_start_env;
1098 1298
1099 if (cctx->flags & CC_TRACE) 1299 if (cctx_current->flags & CC_TRACE)
1100 PL_runops = runops_trace; 1300 PL_runops = runops_trace;
1101 1301
1102 /* we already must be executing an SLF op, there is no other valid way 1302 /* we already must be executing an SLF op, there is no other valid way
1103 * that can lead to creation of a new cctx */ 1303 * that can lead to creation of a new cctx */
1104 assert (("FATAL: can't prepare slf-less cctx in Coro module (please report)", 1304 assert (("FATAL: can't prepare slf-less cctx in Coro module (please report)",
1105 slf_frame.prepare && PL_op->op_ppaddr == pp_slf)); 1305 slf_frame.prepare && PL_op->op_ppaddr == pp_slf));
1106 1306
1107 /* we must emulate leaving pp_slf, which is done inside slf_check_set_stacklevel */ 1307 /* we must emulate leaving pp_slf, which is done inside slf_check_set_stacklevel */
1108 cctx_ssl_cctx = cctx;
1109 cctx_ssl_frame = slf_frame; 1308 cctx_ssl_frame = slf_frame;
1110 1309
1111 slf_frame.prepare = slf_prepare_set_stacklevel; 1310 slf_frame.prepare = slf_prepare_set_stacklevel;
1112 slf_frame.check = slf_check_set_stacklevel; 1311 slf_frame.check = slf_check_set_stacklevel;
1113} 1312}
1136 /* normally we would need to skip the entersub here */ 1335 /* normally we would need to skip the entersub here */
1137 /* not doing so will re-execute it, which is exactly what we want */ 1336 /* not doing so will re-execute it, which is exactly what we want */
1138 /* PL_nop = PL_nop->op_next */ 1337 /* PL_nop = PL_nop->op_next */
1139 1338
1140 /* inject a fake subroutine call to cctx_init */ 1339 /* inject a fake subroutine call to cctx_init */
1141 cctx_prepare (aTHX_ (coro_cctx *)arg); 1340 cctx_prepare (aTHX);
1142 1341
1143 /* cctx_run is the alternative tail of transfer() */ 1342 /* cctx_run is the alternative tail of transfer() */
1144 transfer_tail (aTHX); 1343 transfer_tail (aTHX);
1145 1344
1146 /* somebody or something will hit me for both perl_run and PL_restartop */ 1345 /* somebody or something will hit me for both perl_run and PL_restartop */
1147 PL_restartop = PL_op; 1346 PL_restartop = PL_op;
1148 perl_run (PL_curinterp); 1347 perl_run (PL_curinterp);
1149 /* 1348 /*
1150 * Unfortunately, there is no way to get at the return values of the 1349 * Unfortunately, there is no way to get at the return values of the
1151 * coro body here, as perl_run destroys these 1350 * coro body here, as perl_run destroys these. Likewise, we cannot catch
1351 * runtime errors here, as this is just a random interpreter, not a thread.
1152 */ 1352 */
1153 1353
1154 /* 1354 /*
1155 * If perl-run returns we assume exit() was being called or the coro 1355 * If perl-run returns we assume exit() was being called or the coro
1156 * fell off the end, which seems to be the only valid (non-bug) 1356 * fell off the end, which seems to be the only valid (non-bug)
1157 * reason for perl_run to return. We try to exit by jumping to the 1357 * reason for perl_run to return. We try to exit by jumping to the
1158 * bootstrap-time "top" top_env, as we cannot restore the "main" 1358 * bootstrap-time "top" top_env, as we cannot restore the "main"
1159 * coroutine as Coro has no such concept 1359 * coroutine as Coro has no such concept.
1360 * This actually isn't valid with the pthread backend, but OSes requiring
1361 * that backend are too broken to do it in a standards-compliant way.
1160 */ 1362 */
1161 PL_top_env = main_top_env; 1363 PL_top_env = main_top_env;
1162 JMPENV_JUMP (2); /* I do not feel well about the hardcoded 2 at all */ 1364 JMPENV_JUMP (2); /* I do not feel well about the hardcoded 2 at all */
1163 } 1365 }
1164} 1366}
1241cctx_destroy (coro_cctx *cctx) 1443cctx_destroy (coro_cctx *cctx)
1242{ 1444{
1243 if (!cctx) 1445 if (!cctx)
1244 return; 1446 return;
1245 1447
1448 assert (("FATAL: tried to destroy current cctx", cctx != cctx_current));//D temporary?
1449
1246 --cctx_count; 1450 --cctx_count;
1247 coro_destroy (&cctx->cctx); 1451 coro_destroy (&cctx->cctx);
1248 1452
1249 /* coro_transfer creates new, empty cctx's */ 1453 /* coro_transfer creates new, empty cctx's */
1250 if (cctx->sptr) 1454 if (cctx->sptr)
1313 /* TODO: throwing up here is considered harmful */ 1517 /* TODO: throwing up here is considered harmful */
1314 1518
1315 if (expect_true (prev != next)) 1519 if (expect_true (prev != next))
1316 { 1520 {
1317 if (expect_false (!(prev->flags & (CF_RUNNING | CF_NEW)))) 1521 if (expect_false (!(prev->flags & (CF_RUNNING | CF_NEW))))
1318 croak ("Coro::State::transfer called with non-running/new prev Coro::State, but can only transfer from running or new states,"); 1522 croak ("Coro::State::transfer called with a blocked prev Coro::State, but can only transfer from running or new states,");
1319 1523
1320 if (expect_false (next->flags & CF_RUNNING))
1321 croak ("Coro::State::transfer called with running next Coro::State, but can only transfer to inactive states,");
1322
1323 if (expect_false (next->flags & CF_DESTROYED)) 1524 if (expect_false (next->flags & (CF_RUNNING | CF_DESTROYED | CF_SUSPENDED)))
1324 croak ("Coro::State::transfer called with destroyed next Coro::State, but can only transfer to inactive states,"); 1525 croak ("Coro::State::transfer called with running, destroyed or suspended next Coro::State, but can only transfer to inactive states,");
1325 1526
1326#if !PERL_VERSION_ATLEAST (5,10,0) 1527#if !PERL_VERSION_ATLEAST (5,10,0)
1327 if (expect_false (PL_lex_state != LEX_NOTPARSING)) 1528 if (expect_false (PL_lex_state != LEX_NOTPARSING))
1328 croak ("Coro::State::transfer called while parsing, but this is not supported in your perl version,"); 1529 croak ("Coro::State::transfer called while parsing, but this is not supported in your perl version,");
1329#endif 1530#endif
1335transfer (pTHX_ struct coro *prev, struct coro *next, int force_cctx) 1536transfer (pTHX_ struct coro *prev, struct coro *next, int force_cctx)
1336{ 1537{
1337 dSTACKLEVEL; 1538 dSTACKLEVEL;
1338 1539
1339 /* sometimes transfer is only called to set idle_sp */ 1540 /* sometimes transfer is only called to set idle_sp */
1340 if (expect_false (!next)) 1541 if (expect_false (!prev))
1341 { 1542 {
1342 ((coro_cctx *)prev)->idle_sp = STACKLEVEL; 1543 cctx_current->idle_sp = STACKLEVEL;
1343 assert (((coro_cctx *)prev)->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */ 1544 assert (cctx_current->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */
1344 } 1545 }
1345 else if (expect_true (prev != next)) 1546 else if (expect_true (prev != next))
1346 { 1547 {
1347 coro_cctx *prev__cctx; 1548 coro_cctx *cctx_prev;
1348 1549
1349 if (expect_false (prev->flags & CF_NEW)) 1550 if (expect_false (prev->flags & CF_NEW))
1350 { 1551 {
1351 /* create a new empty/source context */ 1552 /* create a new empty/source context */
1352 prev->cctx = cctx_new_empty ();
1353 prev->flags &= ~CF_NEW; 1553 prev->flags &= ~CF_NEW;
1354 prev->flags |= CF_RUNNING; 1554 prev->flags |= CF_RUNNING;
1355 } 1555 }
1356 1556
1357 prev->flags &= ~CF_RUNNING; 1557 prev->flags &= ~CF_RUNNING;
1363 if (expect_false (next->flags & CF_NEW)) 1563 if (expect_false (next->flags & CF_NEW))
1364 { 1564 {
1365 /* need to start coroutine */ 1565 /* need to start coroutine */
1366 next->flags &= ~CF_NEW; 1566 next->flags &= ~CF_NEW;
1367 /* setup coroutine call */ 1567 /* setup coroutine call */
1368 coro_setup (aTHX_ next); 1568 init_perl (aTHX_ next);
1369 } 1569 }
1370 else 1570 else
1371 load_perl (aTHX_ next); 1571 load_perl (aTHX_ next);
1372 1572
1373 prev__cctx = prev->cctx;
1374
1375 /* possibly untie and reuse the cctx */ 1573 /* possibly untie and reuse the cctx */
1376 if (expect_true ( 1574 if (expect_true (
1377 prev__cctx->idle_sp == STACKLEVEL 1575 cctx_current->idle_sp == STACKLEVEL
1378 && !(prev__cctx->flags & CC_TRACE) 1576 && !(cctx_current->flags & CC_TRACE)
1379 && !force_cctx 1577 && !force_cctx
1380 )) 1578 ))
1381 { 1579 {
1382 /* I assume that stacklevel is a stronger indicator than PL_top_env changes */ 1580 /* I assume that stacklevel is a stronger indicator than PL_top_env changes */
1383 assert (("FATAL: current top_env must equal previous top_env in Coro (please report)", PL_top_env == prev__cctx->idle_te)); 1581 assert (("FATAL: current top_env must equal previous top_env in Coro (please report)", PL_top_env == cctx_current->idle_te));
1384 1582
1385 prev->cctx = 0;
1386
1387 /* if the cctx is about to be destroyed we need to make sure we won't see it in cctx_get */ 1583 /* if the cctx is about to be destroyed we need to make sure we won't see it in cctx_get. */
1388 /* without this the next cctx_get might destroy the prev__cctx while still in use */ 1584 /* without this the next cctx_get might destroy the running cctx while still in use */
1389 if (expect_false (CCTX_EXPIRED (prev__cctx))) 1585 if (expect_false (CCTX_EXPIRED (cctx_current)))
1390 if (!next->cctx) 1586 if (expect_true (!next->cctx))
1391 next->cctx = cctx_get (aTHX); 1587 next->cctx = cctx_get (aTHX);
1392 1588
1393 cctx_put (prev__cctx); 1589 cctx_put (cctx_current);
1394 } 1590 }
1591 else
1592 prev->cctx = cctx_current;
1395 1593
1396 ++next->usecount; 1594 ++next->usecount;
1397 1595
1398 if (expect_true (!next->cctx)) 1596 cctx_prev = cctx_current;
1399 next->cctx = cctx_get (aTHX); 1597 cctx_current = expect_false (next->cctx) ? next->cctx : cctx_get (aTHX);
1400 1598
1401 if (expect_false (prev__cctx != next->cctx)) 1599 next->cctx = 0;
1600
1601 if (expect_false (cctx_prev != cctx_current))
1402 { 1602 {
1403 prev__cctx->top_env = PL_top_env; 1603 cctx_prev->top_env = PL_top_env;
1404 PL_top_env = next->cctx->top_env; 1604 PL_top_env = cctx_current->top_env;
1405 coro_transfer (&prev__cctx->cctx, &next->cctx->cctx); 1605 coro_transfer (&cctx_prev->cctx, &cctx_current->cctx);
1406 } 1606 }
1407 1607
1408 transfer_tail (aTHX); 1608 transfer_tail (aTHX);
1409 } 1609 }
1410} 1610}
1418coro_state_destroy (pTHX_ struct coro *coro) 1618coro_state_destroy (pTHX_ struct coro *coro)
1419{ 1619{
1420 if (coro->flags & CF_DESTROYED) 1620 if (coro->flags & CF_DESTROYED)
1421 return 0; 1621 return 0;
1422 1622
1423 if (coro->on_destroy) 1623 if (coro->on_destroy && !PL_dirty)
1424 coro->on_destroy (aTHX_ coro); 1624 coro->on_destroy (aTHX_ coro);
1425 1625
1426 coro->flags |= CF_DESTROYED; 1626 coro->flags |= CF_DESTROYED;
1427 1627
1428 if (coro->flags & CF_READY) 1628 if (coro->flags & CF_READY)
1432 --coro_nready; 1632 --coro_nready;
1433 } 1633 }
1434 else 1634 else
1435 coro->flags |= CF_READY; /* make sure it is NOT put into the readyqueue */ 1635 coro->flags |= CF_READY; /* make sure it is NOT put into the readyqueue */
1436 1636
1437 if (coro->mainstack && coro->mainstack != main_mainstack) 1637 if (coro->mainstack
1438 { 1638 && coro->mainstack != main_mainstack
1439 struct coro temp; 1639 && coro->slot
1440 1640 && !PL_dirty)
1441 assert (("FATAL: tried to destroy currently running coroutine (please report)", !(coro->flags & CF_RUNNING)));
1442
1443 save_perl (aTHX_ &temp);
1444 load_perl (aTHX_ coro); 1641 destroy_perl (aTHX_ coro);
1445 1642
1446 coro_destruct (aTHX_ coro); 1643 if (coro->next) coro->next->prev = coro->prev;
1447 1644 if (coro->prev) coro->prev->next = coro->next;
1448 load_perl (aTHX_ &temp); 1645 if (coro == coro_first) coro_first = coro->next;
1449
1450 coro->slot = 0;
1451 }
1452 1646
1453 cctx_destroy (coro->cctx); 1647 cctx_destroy (coro->cctx);
1454 SvREFCNT_dec (coro->startcv); 1648 SvREFCNT_dec (coro->startcv);
1455 SvREFCNT_dec (coro->args); 1649 SvREFCNT_dec (coro->args);
1650 SvREFCNT_dec (coro->swap_sv);
1456 SvREFCNT_dec (CORO_THROW); 1651 SvREFCNT_dec (CORO_THROW);
1457
1458 if (coro->next) coro->next->prev = coro->prev;
1459 if (coro->prev) coro->prev->next = coro->next;
1460 if (coro == coro_first) coro_first = coro->next;
1461 1652
1462 return 1; 1653 return 1;
1463} 1654}
1464 1655
1465static int 1656static int
1515 1706
1516 prepare_transfer (aTHX_ &ta, prev_sv, next_sv); 1707 prepare_transfer (aTHX_ &ta, prev_sv, next_sv);
1517 TRANSFER (ta, 1); 1708 TRANSFER (ta, 1);
1518} 1709}
1519 1710
1520/*****************************************************************************/
1521/* gensub: simple closure generation utility */
1522
1523#define GENSUB_ARG CvXSUBANY (cv).any_ptr
1524
1525/* create a closure from XS, returns a code reference */
1526/* the arg can be accessed via GENSUB_ARG from the callback */
1527/* the callback must use dXSARGS/XSRETURN */
1528static SV *
1529gensub (pTHX_ void (*xsub)(pTHX_ CV *), void *arg)
1530{
1531 CV *cv = (CV *)newSV (0);
1532
1533 sv_upgrade ((SV *)cv, SVt_PVCV);
1534
1535 CvANON_on (cv);
1536 CvISXSUB_on (cv);
1537 CvXSUB (cv) = xsub;
1538 GENSUB_ARG = arg;
1539
1540 return newRV_noinc ((SV *)cv);
1541}
1542
1543/** Coro ********************************************************************/ 1711/** Coro ********************************************************************/
1544 1712
1545INLINE void 1713INLINE void
1546coro_enq (pTHX_ struct coro *coro) 1714coro_enq (pTHX_ struct coro *coro)
1547{ 1715{
1548 av_push (coro_ready [coro->prio - PRIO_MIN], SvREFCNT_inc_NN (coro->hv)); 1716 struct coro **ready = coro_ready [coro->prio - CORO_PRIO_MIN];
1549}
1550 1717
1551INLINE SV * 1718 SvREFCNT_inc_NN (coro->hv);
1719
1720 coro->next_ready = 0;
1721 *(ready [0] ? &ready [1]->next_ready : &ready [0]) = coro;
1722 ready [1] = coro;
1723}
1724
1725INLINE struct coro *
1552coro_deq (pTHX) 1726coro_deq (pTHX)
1553{ 1727{
1554 int prio; 1728 int prio;
1555 1729
1556 for (prio = PRIO_MAX - PRIO_MIN + 1; --prio >= 0; ) 1730 for (prio = CORO_PRIO_MAX - CORO_PRIO_MIN + 1; --prio >= 0; )
1557 if (AvFILLp (coro_ready [prio]) >= 0) 1731 {
1558 return av_shift (coro_ready [prio]); 1732 struct coro **ready = coro_ready [prio];
1733
1734 if (ready [0])
1735 {
1736 struct coro *coro = ready [0];
1737 ready [0] = coro->next_ready;
1738 return coro;
1739 }
1740 }
1559 1741
1560 return 0; 1742 return 0;
1743}
1744
1745static void
1746invoke_sv_ready_hook_helper (void)
1747{
1748 dTHX;
1749 dSP;
1750
1751 ENTER;
1752 SAVETMPS;
1753
1754 PUSHMARK (SP);
1755 PUTBACK;
1756 call_sv (coro_readyhook, G_VOID | G_DISCARD);
1757
1758 FREETMPS;
1759 LEAVE;
1561} 1760}
1562 1761
1563static int 1762static int
1564api_ready (pTHX_ SV *coro_sv) 1763api_ready (pTHX_ SV *coro_sv)
1565{ 1764{
1566 struct coro *coro;
1567 SV *sv_hook;
1568 void (*xs_hook)(void);
1569
1570 if (SvROK (coro_sv))
1571 coro_sv = SvRV (coro_sv);
1572
1573 coro = SvSTATE (coro_sv); 1765 struct coro *coro = SvSTATE (coro_sv);
1574 1766
1575 if (coro->flags & CF_READY) 1767 if (coro->flags & CF_READY)
1576 return 0; 1768 return 0;
1577 1769
1578 coro->flags |= CF_READY; 1770 coro->flags |= CF_READY;
1579 1771
1580 sv_hook = coro_nready ? 0 : coro_readyhook;
1581 xs_hook = coro_nready ? 0 : coroapi.readyhook;
1582
1583 coro_enq (aTHX_ coro); 1772 coro_enq (aTHX_ coro);
1584 ++coro_nready;
1585 1773
1586 if (sv_hook) 1774 if (!coro_nready++)
1587 { 1775 if (coroapi.readyhook)
1588 dSP; 1776 coroapi.readyhook ();
1589
1590 ENTER;
1591 SAVETMPS;
1592
1593 PUSHMARK (SP);
1594 PUTBACK;
1595 call_sv (sv_hook, G_VOID | G_DISCARD);
1596
1597 FREETMPS;
1598 LEAVE;
1599 }
1600
1601 if (xs_hook)
1602 xs_hook ();
1603 1777
1604 return 1; 1778 return 1;
1605} 1779}
1606 1780
1607static int 1781static int
1608api_is_ready (pTHX_ SV *coro_sv) 1782api_is_ready (pTHX_ SV *coro_sv)
1609{ 1783{
1610 return !!(SvSTATE (coro_sv)->flags & CF_READY); 1784 return !!(SvSTATE (coro_sv)->flags & CF_READY);
1611} 1785}
1612 1786
1787/* expects to own a reference to next->hv */
1613INLINE void 1788INLINE void
1614prepare_schedule (pTHX_ struct coro_transfer_args *ta) 1789prepare_schedule_to (pTHX_ struct coro_transfer_args *ta, struct coro *next)
1615{ 1790{
1616 SV *prev_sv, *next_sv;
1617
1618 for (;;)
1619 {
1620 next_sv = coro_deq (aTHX);
1621
1622 /* nothing to schedule: call the idle handler */
1623 if (expect_false (!next_sv))
1624 {
1625 dSP;
1626
1627 ENTER;
1628 SAVETMPS;
1629
1630 PUSHMARK (SP);
1631 PUTBACK;
1632 call_sv (get_sv ("Coro::idle", FALSE), G_VOID | G_DISCARD);
1633
1634 FREETMPS;
1635 LEAVE;
1636 continue;
1637 }
1638
1639 ta->next = SvSTATE_hv (next_sv);
1640
1641 /* cannot transfer to destroyed coros, skip and look for next */
1642 if (expect_false (ta->next->flags & CF_DESTROYED))
1643 {
1644 SvREFCNT_dec (next_sv);
1645 /* coro_nready has already been taken care of by destroy */
1646 continue;
1647 }
1648
1649 --coro_nready;
1650 break;
1651 }
1652
1653 /* free this only after the transfer */
1654 prev_sv = SvRV (coro_current); 1791 SV *prev_sv = SvRV (coro_current);
1792
1655 ta->prev = SvSTATE_hv (prev_sv); 1793 ta->prev = SvSTATE_hv (prev_sv);
1794 ta->next = next;
1795
1656 TRANSFER_CHECK (*ta); 1796 TRANSFER_CHECK (*ta);
1657 assert (("FATAL: next coroutine isn't marked as ready in Coro (please report)", ta->next->flags & CF_READY)); 1797
1658 ta->next->flags &= ~CF_READY;
1659 SvRV_set (coro_current, next_sv); 1798 SvRV_set (coro_current, (SV *)next->hv);
1660 1799
1661 free_coro_mortal (aTHX); 1800 free_coro_mortal (aTHX);
1662 coro_mortal = prev_sv; 1801 coro_mortal = prev_sv;
1663} 1802}
1664 1803
1804static void
1805prepare_schedule (pTHX_ struct coro_transfer_args *ta)
1806{
1807 for (;;)
1808 {
1809 struct coro *next = coro_deq (aTHX);
1810
1811 if (expect_true (next))
1812 {
1813 /* cannot transfer to destroyed coros, skip and look for next */
1814 if (expect_false (next->flags & (CF_DESTROYED | CF_SUSPENDED)))
1815 SvREFCNT_dec (next->hv); /* coro_nready has already been taken care of by destroy */
1816 else
1817 {
1818 next->flags &= ~CF_READY;
1819 --coro_nready;
1820
1821 prepare_schedule_to (aTHX_ ta, next);
1822 break;
1823 }
1824 }
1825 else
1826 {
1827 /* nothing to schedule: call the idle handler */
1828 if (SvROK (sv_idle)
1829 && SvOBJECT (SvRV (sv_idle)))
1830 {
1831 if (SvRV (sv_idle) == SvRV (coro_current))
1832 croak ("FATAL: $Coro::IDLE blocked itself - did you try to block inside an event loop callback? Caught");
1833
1834 ++coro_nready; /* hack so that api_ready doesn't invoke ready hook */
1835 api_ready (aTHX_ SvRV (sv_idle));
1836 --coro_nready;
1837 }
1838 else
1839 {
1840 /* TODO: deprecated, remove, cannot work reliably *//*D*/
1841 dSP;
1842
1843 ENTER;
1844 SAVETMPS;
1845
1846 PUSHMARK (SP);
1847 PUTBACK;
1848 call_sv (sv_idle, G_VOID | G_DISCARD);
1849
1850 FREETMPS;
1851 LEAVE;
1852 }
1853 }
1854 }
1855}
1856
1665INLINE void 1857INLINE void
1666prepare_cede (pTHX_ struct coro_transfer_args *ta) 1858prepare_cede (pTHX_ struct coro_transfer_args *ta)
1667{ 1859{
1668 api_ready (aTHX_ coro_current); 1860 api_ready (aTHX_ coro_current);
1669 prepare_schedule (aTHX_ ta); 1861 prepare_schedule (aTHX_ ta);
1688{ 1880{
1689 struct coro_transfer_args ta; 1881 struct coro_transfer_args ta;
1690 1882
1691 prepare_schedule (aTHX_ &ta); 1883 prepare_schedule (aTHX_ &ta);
1692 TRANSFER (ta, 1); 1884 TRANSFER (ta, 1);
1885}
1886
1887static void
1888api_schedule_to (pTHX_ SV *coro_sv)
1889{
1890 struct coro_transfer_args ta;
1891 struct coro *next = SvSTATE (coro_sv);
1892
1893 SvREFCNT_inc_NN (coro_sv);
1894 prepare_schedule_to (aTHX_ &ta, next);
1693} 1895}
1694 1896
1695static int 1897static int
1696api_cede (pTHX) 1898api_cede (pTHX)
1697{ 1899{
1726static void 1928static void
1727api_trace (pTHX_ SV *coro_sv, int flags) 1929api_trace (pTHX_ SV *coro_sv, int flags)
1728{ 1930{
1729 struct coro *coro = SvSTATE (coro_sv); 1931 struct coro *coro = SvSTATE (coro_sv);
1730 1932
1933 if (coro->flags & CF_RUNNING)
1934 croak ("cannot enable tracing on a running coroutine, caught");
1935
1731 if (flags & CC_TRACE) 1936 if (flags & CC_TRACE)
1732 { 1937 {
1733 if (!coro->cctx) 1938 if (!coro->cctx)
1734 coro->cctx = cctx_new_run (); 1939 coro->cctx = cctx_new_run ();
1735 else if (!(coro->cctx->flags & CC_TRACE)) 1940 else if (!(coro->cctx->flags & CC_TRACE))
1736 croak ("cannot enable tracing on coroutine with custom stack,"); 1941 croak ("cannot enable tracing on coroutine with custom stack, caught");
1737 1942
1738 coro->cctx->flags |= CC_NOREUSE | (flags & (CC_TRACE | CC_TRACE_ALL)); 1943 coro->cctx->flags |= CC_NOREUSE | (flags & (CC_TRACE | CC_TRACE_ALL));
1739 } 1944 }
1740 else if (coro->cctx && coro->cctx->flags & CC_TRACE) 1945 else if (coro->cctx && coro->cctx->flags & CC_TRACE)
1741 { 1946 {
1746 else 1951 else
1747 coro->slot->runops = RUNOPS_DEFAULT; 1952 coro->slot->runops = RUNOPS_DEFAULT;
1748 } 1953 }
1749} 1954}
1750 1955
1956static void
1957coro_call_on_destroy (pTHX_ struct coro *coro)
1958{
1959 SV **on_destroyp = hv_fetch (coro->hv, "_on_destroy", sizeof ("_on_destroy") - 1, 0);
1960 SV **statusp = hv_fetch (coro->hv, "_status", sizeof ("_status") - 1, 0);
1961
1962 if (on_destroyp)
1963 {
1964 AV *on_destroy = (AV *)SvRV (*on_destroyp);
1965
1966 while (AvFILLp (on_destroy) >= 0)
1967 {
1968 dSP; /* don't disturb outer sp */
1969 SV *cb = av_pop (on_destroy);
1970
1971 PUSHMARK (SP);
1972
1973 if (statusp)
1974 {
1975 int i;
1976 AV *status = (AV *)SvRV (*statusp);
1977 EXTEND (SP, AvFILLp (status) + 1);
1978
1979 for (i = 0; i <= AvFILLp (status); ++i)
1980 PUSHs (AvARRAY (status)[i]);
1981 }
1982
1983 PUTBACK;
1984 call_sv (sv_2mortal (cb), G_VOID | G_DISCARD);
1985 }
1986 }
1987}
1988
1989static void
1990slf_init_terminate (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1991{
1992 int i;
1993 HV *hv = (HV *)SvRV (coro_current);
1994 AV *av = newAV ();
1995
1996 /* items are actually not so common, so optimise for this case */
1997 if (items)
1998 {
1999 av_extend (av, items - 1);
2000
2001 for (i = 0; i < items; ++i)
2002 av_push (av, SvREFCNT_inc_NN (arg [i]));
2003 }
2004
2005 hv_store (hv, "_status", sizeof ("_status") - 1, newRV_noinc ((SV *)av), 0);
2006
2007 av_push (av_destroy, (SV *)newRV_inc ((SV *)hv)); /* RVinc for perl */
2008 api_ready (aTHX_ sv_manager);
2009
2010 frame->prepare = prepare_schedule;
2011 frame->check = slf_check_repeat;
2012
2013 /* as a minor optimisation, we could unwind all stacks here */
2014 /* but that puts extra pressure on pp_slf, and is not worth much */
2015 /*coro_unwind_stacks (aTHX);*/
2016}
2017
2018/*****************************************************************************/
2019/* async pool handler */
2020
2021static int
2022slf_check_pool_handler (pTHX_ struct CoroSLF *frame)
2023{
2024 HV *hv = (HV *)SvRV (coro_current);
2025 struct coro *coro = (struct coro *)frame->data;
2026
2027 if (!coro->invoke_cb)
2028 return 1; /* loop till we have invoke */
2029 else
2030 {
2031 hv_store (hv, "desc", sizeof ("desc") - 1,
2032 newSVpvn ("[async_pool]", sizeof ("[async_pool]") - 1), 0);
2033
2034 coro->saved_deffh = SvREFCNT_inc_NN ((SV *)PL_defoutgv);
2035
2036 {
2037 dSP;
2038 XPUSHs (sv_2mortal (coro->invoke_cb)); coro->invoke_cb = 0;
2039 PUTBACK;
2040 }
2041
2042 SvREFCNT_dec (GvAV (PL_defgv));
2043 GvAV (PL_defgv) = coro->invoke_av;
2044 coro->invoke_av = 0;
2045
2046 return 0;
2047 }
2048}
2049
2050static void
2051slf_init_pool_handler (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2052{
2053 HV *hv = (HV *)SvRV (coro_current);
2054 struct coro *coro = SvSTATE_hv ((SV *)hv);
2055
2056 if (expect_true (coro->saved_deffh))
2057 {
2058 /* subsequent iteration */
2059 SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh;
2060 coro->saved_deffh = 0;
2061
2062 if (coro_rss (aTHX_ coro) > SvUV (sv_pool_rss)
2063 || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size))
2064 {
2065 coro->invoke_cb = SvREFCNT_inc_NN ((SV *)cv_coro_terminate);
2066 coro->invoke_av = newAV ();
2067
2068 frame->prepare = prepare_nop;
2069 }
2070 else
2071 {
2072 av_clear (GvAV (PL_defgv));
2073 hv_store (hv, "desc", sizeof ("desc") - 1, SvREFCNT_inc_NN (sv_async_pool_idle), 0);
2074
2075 coro->prio = 0;
2076
2077 if (coro->cctx && (coro->cctx->flags & CC_TRACE))
2078 api_trace (aTHX_ coro_current, 0);
2079
2080 frame->prepare = prepare_schedule;
2081 av_push (av_async_pool, SvREFCNT_inc (hv));
2082 }
2083 }
2084 else
2085 {
2086 /* first iteration, simply fall through */
2087 frame->prepare = prepare_nop;
2088 }
2089
2090 frame->check = slf_check_pool_handler;
2091 frame->data = (void *)coro;
2092}
2093
1751/*****************************************************************************/ 2094/*****************************************************************************/
1752/* rouse callback */ 2095/* rouse callback */
1753 2096
1754#define CORO_MAGIC_type_rouse PERL_MAGIC_ext 2097#define CORO_MAGIC_type_rouse PERL_MAGIC_ext
1755 2098
1756static void 2099static void
1757coro_rouse_callback (pTHX_ CV *cv) 2100coro_rouse_callback (pTHX_ CV *cv)
1758{ 2101{
1759 dXSARGS; 2102 dXSARGS;
1760 SV *data = (SV *)GENSUB_ARG; 2103 SV *data = (SV *)S_GENSUB_ARG;
1761 2104
1762 if (SvTYPE (SvRV (data)) != SVt_PVAV) 2105 if (SvTYPE (SvRV (data)) != SVt_PVAV)
1763 { 2106 {
1764 /* first call, set args */ 2107 /* first call, set args */
1765 int i; 2108 SV *coro = SvRV (data);
1766 AV *av = newAV (); 2109 AV *av = newAV ();
1767 SV *coro = SvRV (data);
1768 2110
1769 SvRV_set (data, (SV *)av); 2111 SvRV_set (data, (SV *)av);
1770 api_ready (aTHX_ coro);
1771 SvREFCNT_dec (coro);
1772 2112
1773 /* better take a full copy of the arguments */ 2113 /* better take a full copy of the arguments */
1774 while (items--) 2114 while (items--)
1775 av_store (av, items, newSVsv (ST (items))); 2115 av_store (av, items, newSVsv (ST (items)));
2116
2117 api_ready (aTHX_ coro);
2118 SvREFCNT_dec (coro);
1776 } 2119 }
1777 2120
1778 XSRETURN_EMPTY; 2121 XSRETURN_EMPTY;
1779} 2122}
1780 2123
1797 2140
1798 EXTEND (SP, AvFILLp (av) + 1); 2141 EXTEND (SP, AvFILLp (av) + 1);
1799 for (i = 0; i <= AvFILLp (av); ++i) 2142 for (i = 0; i <= AvFILLp (av); ++i)
1800 PUSHs (sv_2mortal (AvARRAY (av)[i])); 2143 PUSHs (sv_2mortal (AvARRAY (av)[i]));
1801 2144
1802 /* we have stolen the elements, so ste length to zero and free */ 2145 /* we have stolen the elements, so set length to zero and free */
1803 AvFILLp (av) = -1; 2146 AvFILLp (av) = -1;
1804 av_undef (av); 2147 av_undef (av);
1805 2148
1806 PUTBACK; 2149 PUTBACK;
1807 } 2150 }
1831 || SvTYPE (SvRV (cb)) != SVt_PVCV 2174 || SvTYPE (SvRV (cb)) != SVt_PVCV
1832 || CvXSUB ((CV *)SvRV (cb)) != coro_rouse_callback) 2175 || CvXSUB ((CV *)SvRV (cb)) != coro_rouse_callback)
1833 croak ("Coro::rouse_wait called with illegal callback argument,"); 2176 croak ("Coro::rouse_wait called with illegal callback argument,");
1834 2177
1835 { 2178 {
1836 CV *cv = (CV *)SvRV (cb); /* for GENSUB_ARG */ 2179 CV *cv = (CV *)SvRV (cb); /* for S_GENSUB_ARG */
1837 SV *data = (SV *)GENSUB_ARG; 2180 SV *data = (SV *)S_GENSUB_ARG;
1838 2181
1839 frame->data = (void *)data; 2182 frame->data = (void *)data;
1840 frame->prepare = SvTYPE (SvRV (data)) == SVt_PVAV ? prepare_nop : prepare_schedule; 2183 frame->prepare = SvTYPE (SvRV (data)) == SVt_PVAV ? prepare_nop : prepare_schedule;
1841 frame->check = slf_check_rouse_wait; 2184 frame->check = slf_check_rouse_wait;
1842 } 2185 }
1846coro_new_rouse_cb (pTHX) 2189coro_new_rouse_cb (pTHX)
1847{ 2190{
1848 HV *hv = (HV *)SvRV (coro_current); 2191 HV *hv = (HV *)SvRV (coro_current);
1849 struct coro *coro = SvSTATE_hv (hv); 2192 struct coro *coro = SvSTATE_hv (hv);
1850 SV *data = newRV_inc ((SV *)hv); 2193 SV *data = newRV_inc ((SV *)hv);
1851 SV *cb = gensub (aTHX_ coro_rouse_callback, (void *)data); 2194 SV *cb = s_gensub (aTHX_ coro_rouse_callback, (void *)data);
1852 2195
1853 sv_magicext (SvRV (cb), data, CORO_MAGIC_type_rouse, 0, 0, 0); 2196 sv_magicext (SvRV (cb), data, CORO_MAGIC_type_rouse, 0, 0, 0);
1854 SvREFCNT_dec (data); /* magicext increases the refcount */ 2197 SvREFCNT_dec (data); /* magicext increases the refcount */
1855 2198
1856 SvREFCNT_dec (coro->rouse_cb); 2199 SvREFCNT_dec (coro->rouse_cb);
1911static void 2254static void
1912slf_init_schedule (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) 2255slf_init_schedule (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1913{ 2256{
1914 frame->prepare = prepare_schedule; 2257 frame->prepare = prepare_schedule;
1915 frame->check = slf_check_nop; 2258 frame->check = slf_check_nop;
2259}
2260
2261static void
2262slf_prepare_schedule_to (pTHX_ struct coro_transfer_args *ta)
2263{
2264 struct coro *next = (struct coro *)slf_frame.data;
2265
2266 SvREFCNT_inc_NN (next->hv);
2267 prepare_schedule_to (aTHX_ ta, next);
2268}
2269
2270static void
2271slf_init_schedule_to (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2272{
2273 if (!items)
2274 croak ("Coro::schedule_to expects a coroutine argument, caught");
2275
2276 frame->data = (void *)SvSTATE (arg [0]);
2277 frame->prepare = slf_prepare_schedule_to;
2278 frame->check = slf_check_nop;
2279}
2280
2281static void
2282slf_init_cede_to (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2283{
2284 api_ready (aTHX_ SvRV (coro_current));
2285
2286 slf_init_schedule_to (aTHX_ frame, cv, arg, items);
1916} 2287}
1917 2288
1918static void 2289static void
1919slf_init_cede (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) 2290slf_init_cede (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1920{ 2291{
2053 if (PL_op->op_flags & OPf_STACKED) 2424 if (PL_op->op_flags & OPf_STACKED)
2054 { 2425 {
2055 if (items > slf_arga) 2426 if (items > slf_arga)
2056 { 2427 {
2057 slf_arga = items; 2428 slf_arga = items;
2058 free (slf_argv); 2429 Safefree (slf_argv);
2059 slf_argv = malloc (slf_arga * sizeof (SV *)); 2430 New (0, slf_argv, slf_arga, SV *);
2060 } 2431 }
2061 2432
2062 slf_argc = items; 2433 slf_argc = items;
2063 2434
2064 for (i = 0; i < items; ++i) 2435 for (i = 0; i < items; ++i)
2066 } 2437 }
2067 else 2438 else
2068 slf_argc = 0; 2439 slf_argc = 0;
2069 2440
2070 PL_op->op_ppaddr = pp_slf; 2441 PL_op->op_ppaddr = pp_slf;
2071 PL_op->op_type = OP_CUSTOM; /* maybe we should leave it at entersub? */ 2442 /*PL_op->op_type = OP_CUSTOM; /* we do behave like entersub still */
2072 2443
2073 PL_op = (OP *)&slf_restore; 2444 PL_op = (OP *)&slf_restore;
2445}
2446
2447/*****************************************************************************/
2448/* dynamic wind */
2449
2450static void
2451on_enterleave_call (pTHX_ SV *cb)
2452{
2453 dSP;
2454
2455 PUSHSTACK;
2456
2457 PUSHMARK (SP);
2458 PUTBACK;
2459 call_sv (cb, G_VOID | G_DISCARD);
2460 SPAGAIN;
2461
2462 POPSTACK;
2463}
2464
2465static SV *
2466coro_avp_pop_and_free (pTHX_ AV **avp)
2467{
2468 AV *av = *avp;
2469 SV *res = av_pop (av);
2470
2471 if (AvFILLp (av) < 0)
2472 {
2473 *avp = 0;
2474 SvREFCNT_dec (av);
2475 }
2476
2477 return res;
2478}
2479
2480static void
2481coro_pop_on_enter (pTHX_ void *coro)
2482{
2483 SV *cb = coro_avp_pop_and_free (aTHX_ &((struct coro *)coro)->on_enter);
2484 SvREFCNT_dec (cb);
2485}
2486
2487static void
2488coro_pop_on_leave (pTHX_ void *coro)
2489{
2490 SV *cb = coro_avp_pop_and_free (aTHX_ &((struct coro *)coro)->on_leave);
2491 on_enterleave_call (aTHX_ sv_2mortal (cb));
2074} 2492}
2075 2493
2076/*****************************************************************************/ 2494/*****************************************************************************/
2077/* PerlIO::cede */ 2495/* PerlIO::cede */
2078 2496
2152/* Coro::Semaphore & Coro::Signal */ 2570/* Coro::Semaphore & Coro::Signal */
2153 2571
2154static SV * 2572static SV *
2155coro_waitarray_new (pTHX_ int count) 2573coro_waitarray_new (pTHX_ int count)
2156{ 2574{
2157 /* a semaphore contains a counter IV in $sem->[0] and any waiters after that */ 2575 /* a waitarray=semaphore contains a counter IV in $sem->[0] and any waiters after that */
2158 AV *av = newAV (); 2576 AV *av = newAV ();
2159 SV **ary; 2577 SV **ary;
2160 2578
2161 /* unfortunately, building manually saves memory */ 2579 /* unfortunately, building manually saves memory */
2162 Newx (ary, 2, SV *); 2580 Newx (ary, 2, SV *);
2163 AvALLOC (av) = ary; 2581 AvALLOC (av) = ary;
2582#if PERL_VERSION_ATLEAST (5,10,0)
2164 /*AvARRAY (av) = ary;*/ 2583 AvARRAY (av) = ary;
2584#else
2165 SvPVX ((SV *)av) = (char *)ary; /* 5.8.8 needs this syntax instead of AvARRAY = ary */ 2585 /* 5.8.8 needs this syntax instead of AvARRAY = ary, yet */
2586 /* -DDEBUGGING flags this as a bug, despite it perfectly working */
2587 SvPVX ((SV *)av) = (char *)ary;
2588#endif
2166 AvMAX (av) = 1; 2589 AvMAX (av) = 1;
2167 AvFILLp (av) = 0; 2590 AvFILLp (av) = 0;
2168 ary [0] = newSViv (count); 2591 ary [0] = newSViv (count);
2169 2592
2170 return newRV_noinc ((SV *)av); 2593 return newRV_noinc ((SV *)av);
2299{ 2722{
2300 if (items >= 2) 2723 if (items >= 2)
2301 { 2724 {
2302 /* callback form */ 2725 /* callback form */
2303 AV *av = (AV *)SvRV (arg [0]); 2726 AV *av = (AV *)SvRV (arg [0]);
2304 CV *cb_cv = coro_sv_2cv (arg [1]); 2727 SV *cb_cv = s_get_cv_croak (arg [1]);
2305 2728
2306 av_push (av, (SV *)SvREFCNT_inc_NN (cb_cv)); 2729 av_push (av, SvREFCNT_inc_NN (cb_cv));
2307 2730
2308 if (SvIVX (AvARRAY (av)[0]) > 0) 2731 if (SvIVX (AvARRAY (av)[0]) > 0)
2309 coro_semaphore_adjust (aTHX_ av, 0); 2732 coro_semaphore_adjust (aTHX_ av, 0);
2310 2733
2311 frame->prepare = prepare_nop; 2734 frame->prepare = prepare_nop;
2335 AvARRAY (av)[0] = AvARRAY (av)[1]; 2758 AvARRAY (av)[0] = AvARRAY (av)[1];
2336 AvARRAY (av)[1] = cb; 2759 AvARRAY (av)[1] = cb;
2337 2760
2338 cb = av_shift (av); 2761 cb = av_shift (av);
2339 2762
2763 if (SvTYPE (cb) == SVt_PVCV)
2764 {
2765 dSP;
2766 PUSHMARK (SP);
2767 XPUSHs (sv_2mortal (newRV_inc ((SV *)av)));
2768 PUTBACK;
2769 call_sv (cb, G_VOID | G_DISCARD | G_EVAL | G_KEEPERR);
2770 }
2771 else
2772 {
2340 api_ready (aTHX_ cb); 2773 api_ready (aTHX_ cb);
2341 sv_setiv (cb, 0); /* signal waiter */ 2774 sv_setiv (cb, 0); /* signal waiter */
2775 }
2776
2342 SvREFCNT_dec (cb); 2777 SvREFCNT_dec (cb);
2343 2778
2344 --count; 2779 --count;
2345 } 2780 }
2346} 2781}
2355static void 2790static void
2356slf_init_signal_wait (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) 2791slf_init_signal_wait (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2357{ 2792{
2358 AV *av = (AV *)SvRV (arg [0]); 2793 AV *av = (AV *)SvRV (arg [0]);
2359 2794
2795 if (items >= 2)
2796 {
2797 SV *cb_cv = s_get_cv_croak (arg [1]);
2798 av_push (av, SvREFCNT_inc_NN (cb_cv));
2799
2360 if (SvIVX (AvARRAY (av)[0])) 2800 if (SvIVX (AvARRAY (av)[0]))
2801 coro_signal_wake (aTHX_ av, 1); /* must be the only waiter */
2802
2803 frame->prepare = prepare_nop;
2804 frame->check = slf_check_nop;
2805 }
2806 else if (SvIVX (AvARRAY (av)[0]))
2361 { 2807 {
2362 SvIVX (AvARRAY (av)[0]) = 0; 2808 SvIVX (AvARRAY (av)[0]) = 0;
2363 frame->prepare = prepare_nop; 2809 frame->prepare = prepare_nop;
2364 frame->check = slf_check_nop; 2810 frame->check = slf_check_nop;
2365 } 2811 }
2366 else 2812 else
2367 { 2813 {
2368 SV *waiter = newRV_inc (SvRV (coro_current)); /* owned by signal av */ 2814 SV *waiter = newSVsv (coro_current); /* owned by signal av */
2369 2815
2370 av_push (av, waiter); 2816 av_push (av, waiter);
2371 2817
2372 frame->data = (void *)sv_2mortal (SvREFCNT_inc_NN (waiter)); /* owned by process */ 2818 frame->data = (void *)sv_2mortal (SvREFCNT_inc_NN (waiter)); /* owned by process */
2373 frame->prepare = prepare_schedule; 2819 frame->prepare = prepare_schedule;
2391 2837
2392static void 2838static void
2393coro_aio_callback (pTHX_ CV *cv) 2839coro_aio_callback (pTHX_ CV *cv)
2394{ 2840{
2395 dXSARGS; 2841 dXSARGS;
2396 AV *state = (AV *)GENSUB_ARG; 2842 AV *state = (AV *)S_GENSUB_ARG;
2397 SV *coro = av_pop (state); 2843 SV *coro = av_pop (state);
2398 SV *data_sv = newSV (sizeof (struct io_state)); 2844 SV *data_sv = newSV (sizeof (struct io_state));
2399 2845
2400 av_extend (state, items); 2846 av_extend (state, items - 1);
2401 2847
2402 sv_upgrade (data_sv, SVt_PV); 2848 sv_upgrade (data_sv, SVt_PV);
2403 SvCUR_set (data_sv, sizeof (struct io_state)); 2849 SvCUR_set (data_sv, sizeof (struct io_state));
2404 SvPOK_only (data_sv); 2850 SvPOK_only (data_sv);
2405 2851
2515 2961
2516 for (i = 0; i < items; ++i) 2962 for (i = 0; i < items; ++i)
2517 PUSHs (arg [i]); 2963 PUSHs (arg [i]);
2518 2964
2519 /* now push the callback closure */ 2965 /* now push the callback closure */
2520 PUSHs (sv_2mortal (gensub (aTHX_ coro_aio_callback, (void *)SvREFCNT_inc_NN ((SV *)state)))); 2966 PUSHs (sv_2mortal (s_gensub (aTHX_ coro_aio_callback, (void *)SvREFCNT_inc_NN ((SV *)state))));
2521 2967
2522 /* now call the AIO function - we assume our request is uncancelable */ 2968 /* now call the AIO function - we assume our request is uncancelable */
2523 PUTBACK; 2969 PUTBACK;
2524 call_sv ((SV *)req, G_VOID | G_DISCARD); 2970 call_sv ((SV *)req, G_VOID | G_DISCARD);
2525 } 2971 }
2526 2972
2527 /* now that the requets is going, we loop toll we have a result */ 2973 /* now that the request is going, we loop till we have a result */
2528 frame->data = (void *)state; 2974 frame->data = (void *)state;
2529 frame->prepare = prepare_schedule; 2975 frame->prepare = prepare_schedule;
2530 frame->check = slf_check_aio_req; 2976 frame->check = slf_check_aio_req;
2531} 2977}
2532 2978
2539 2985
2540 XSRETURN_EMPTY; 2986 XSRETURN_EMPTY;
2541} 2987}
2542 2988
2543/*****************************************************************************/ 2989/*****************************************************************************/
2990
2991#if CORO_CLONE
2992# include "clone.c"
2993#endif
2994
2995/*****************************************************************************/
2996
2997static SV *
2998coro_new (pTHX_ HV *stash, SV **argv, int argc, int is_coro)
2999{
3000 SV *coro_sv;
3001 struct coro *coro;
3002 MAGIC *mg;
3003 HV *hv;
3004 SV *cb;
3005 int i;
3006
3007 if (argc > 0)
3008 {
3009 cb = s_get_cv_croak (argv [0]);
3010
3011 if (!is_coro)
3012 {
3013 if (CvISXSUB (cb))
3014 croak ("Coro::State doesn't support XS functions as coroutine start, caught");
3015
3016 if (!CvROOT (cb))
3017 croak ("Coro::State doesn't support autoloaded or undefined functions as coroutine start, caught");
3018 }
3019 }
3020
3021 Newz (0, coro, 1, struct coro);
3022 coro->args = newAV ();
3023 coro->flags = CF_NEW;
3024
3025 if (coro_first) coro_first->prev = coro;
3026 coro->next = coro_first;
3027 coro_first = coro;
3028
3029 coro->hv = hv = newHV ();
3030 mg = sv_magicext ((SV *)hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)coro, 0);
3031 mg->mg_flags |= MGf_DUP;
3032 coro_sv = sv_bless (newRV_noinc ((SV *)hv), stash);
3033
3034 if (argc > 0)
3035 {
3036 av_extend (coro->args, argc + is_coro - 1);
3037
3038 if (is_coro)
3039 {
3040 av_push (coro->args, SvREFCNT_inc_NN ((SV *)cb));
3041 cb = (SV *)cv_coro_run;
3042 }
3043
3044 coro->startcv = (CV *)SvREFCNT_inc_NN ((SV *)cb);
3045
3046 for (i = 1; i < argc; i++)
3047 av_push (coro->args, newSVsv (argv [i]));
3048 }
3049
3050 return coro_sv;
3051}
2544 3052
2545MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_ 3053MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_
2546 3054
2547PROTOTYPES: DISABLE 3055PROTOTYPES: DISABLE
2548 3056
2553 coro_thx = PERL_GET_CONTEXT; 3061 coro_thx = PERL_GET_CONTEXT;
2554# endif 3062# endif
2555#endif 3063#endif
2556 BOOT_PAGESIZE; 3064 BOOT_PAGESIZE;
2557 3065
3066 cctx_current = cctx_new_empty ();
3067
2558 irsgv = gv_fetchpv ("/" , GV_ADD|GV_NOTQUAL, SVt_PV); 3068 irsgv = gv_fetchpv ("/" , GV_ADD|GV_NOTQUAL, SVt_PV);
2559 stdoutgv = gv_fetchpv ("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO); 3069 stdoutgv = gv_fetchpv ("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO);
2560 3070
2561 orig_sigelem_get = PL_vtbl_sigelem.svt_get; PL_vtbl_sigelem.svt_get = coro_sigelem_get; 3071 orig_sigelem_get = PL_vtbl_sigelem.svt_get; PL_vtbl_sigelem.svt_get = coro_sigelem_get;
2562 orig_sigelem_set = PL_vtbl_sigelem.svt_set; PL_vtbl_sigelem.svt_set = coro_sigelem_set; 3072 orig_sigelem_set = PL_vtbl_sigelem.svt_set; PL_vtbl_sigelem.svt_set = coro_sigelem_set;
2581 3091
2582 { 3092 {
2583 SV *slf = sv_2mortal (newSViv (PTR2IV (pp_slf))); 3093 SV *slf = sv_2mortal (newSViv (PTR2IV (pp_slf)));
2584 3094
2585 if (!PL_custom_op_names) PL_custom_op_names = newHV (); 3095 if (!PL_custom_op_names) PL_custom_op_names = newHV ();
2586 hv_store_ent (PL_custom_op_names, slf, 3096 hv_store_ent (PL_custom_op_names, slf, newSVpv ("coro_slf", 0), 0);
2587 newSVpv ("coro_slf", 0), 0);
2588 3097
2589 if (!PL_custom_op_descs) PL_custom_op_descs = newHV (); 3098 if (!PL_custom_op_descs) PL_custom_op_descs = newHV ();
2590 hv_store_ent (PL_custom_op_descs, slf, 3099 hv_store_ent (PL_custom_op_descs, slf, newSVpv ("coro schedule like function", 0), 0);
2591 newSVpv ("coro schedule like function", 0), 0);
2592 } 3100 }
2593 3101
2594 coroapi.ver = CORO_API_VERSION; 3102 coroapi.ver = CORO_API_VERSION;
2595 coroapi.rev = CORO_API_REVISION; 3103 coroapi.rev = CORO_API_REVISION;
2596 3104
2608 3116
2609 if (!svp) croak ("Time::HiRes is required"); 3117 if (!svp) croak ("Time::HiRes is required");
2610 if (!SvIOK (*svp)) croak ("Time::NVtime isn't a function pointer"); 3118 if (!SvIOK (*svp)) croak ("Time::NVtime isn't a function pointer");
2611 3119
2612 nvtime = INT2PTR (double (*)(), SvIV (*svp)); 3120 nvtime = INT2PTR (double (*)(), SvIV (*svp));
3121
3122 svp = hv_fetch (PL_modglobal, "Time::U2time", 12, 0);
3123 u2time = INT2PTR (void (*)(pTHX_ UV ret[2]), SvIV (*svp));
2613 } 3124 }
2614 3125
2615 assert (("PRIO_NORMAL must be 0", !PRIO_NORMAL)); 3126 assert (("PRIO_NORMAL must be 0", !CORO_PRIO_NORMAL));
2616} 3127}
2617 3128
2618SV * 3129SV *
2619new (char *klass, ...) 3130new (SV *klass, ...)
2620 ALIAS: 3131 ALIAS:
2621 Coro::new = 1 3132 Coro::new = 1
2622 CODE: 3133 CODE:
2623{ 3134 RETVAL = coro_new (aTHX_ ix ? coro_stash : coro_state_stash, &ST (1), items - 1, ix);
2624 struct coro *coro; 3135 OUTPUT:
2625 MAGIC *mg;
2626 HV *hv;
2627 CV *cb;
2628 int i;
2629
2630 if (items > 1)
2631 {
2632 cb = coro_sv_2cv (ST (1));
2633
2634 if (CvISXSUB (cb))
2635 croak ("Coro::State doesn't support XS functions as coroutine start, caught");
2636
2637 if (!CvROOT (cb))
2638 croak ("Coro::State doesn't support autoloaded or undefined functions as coroutine start, caught");
2639 }
2640
2641 Newz (0, coro, 1, struct coro);
2642 coro->args = newAV ();
2643 coro->flags = CF_NEW;
2644
2645 if (coro_first) coro_first->prev = coro;
2646 coro->next = coro_first;
2647 coro_first = coro;
2648
2649 coro->hv = hv = newHV ();
2650 mg = sv_magicext ((SV *)hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)coro, 0);
2651 mg->mg_flags |= MGf_DUP;
2652 RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1));
2653
2654 if (items > 1)
2655 {
2656 av_extend (coro->args, items - 1 + ix);
2657
2658 if (ix)
2659 {
2660 av_push (coro->args, SvREFCNT_inc_NN ((SV *)cb));
2661 cb = coro_run_cv;
2662 }
2663
2664 coro->startcv = (CV *)SvREFCNT_inc_NN ((SV *)cb);
2665
2666 for (i = 2; i < items; i++)
2667 av_push (coro->args, newSVsv (ST (i)));
2668 }
2669}
2670 OUTPUT:
2671 RETVAL 3136 RETVAL
2672 3137
2673void 3138void
2674transfer (...) 3139transfer (...)
2675 PROTOTYPE: $$ 3140 PROTOTYPE: $$
2686void 3151void
2687_exit (int code) 3152_exit (int code)
2688 PROTOTYPE: $ 3153 PROTOTYPE: $
2689 CODE: 3154 CODE:
2690 _exit (code); 3155 _exit (code);
3156
3157SV *
3158clone (Coro::State coro)
3159 CODE:
3160{
3161#if CORO_CLONE
3162 struct coro *ncoro = coro_clone (aTHX_ coro);
3163 MAGIC *mg;
3164 /* TODO: too much duplication */
3165 ncoro->hv = newHV ();
3166 mg = sv_magicext ((SV *)ncoro->hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)ncoro, 0);
3167 mg->mg_flags |= MGf_DUP;
3168 RETVAL = sv_bless (newRV_noinc ((SV *)ncoro->hv), SvSTASH (coro->hv));
3169#else
3170 croak ("Coro::State->clone has not been configured into this installation of Coro, realised");
3171#endif
3172}
3173 OUTPUT:
3174 RETVAL
2691 3175
2692int 3176int
2693cctx_stacksize (int new_stacksize = 0) 3177cctx_stacksize (int new_stacksize = 0)
2694 PROTOTYPE: ;$ 3178 PROTOTYPE: ;$
2695 CODE: 3179 CODE:
2745 eval = 1 3229 eval = 1
2746 CODE: 3230 CODE:
2747{ 3231{
2748 if (coro->mainstack && ((coro->flags & CF_RUNNING) || coro->slot)) 3232 if (coro->mainstack && ((coro->flags & CF_RUNNING) || coro->slot))
2749 { 3233 {
2750 struct coro temp; 3234 struct coro *current = SvSTATE_current;
2751 3235
2752 if (!(coro->flags & CF_RUNNING)) 3236 if (current != coro)
2753 { 3237 {
2754 PUTBACK; 3238 PUTBACK;
2755 save_perl (aTHX_ &temp); 3239 save_perl (aTHX_ current);
2756 load_perl (aTHX_ coro); 3240 load_perl (aTHX_ coro);
3241 SPAGAIN;
2757 } 3242 }
2758 3243
2759 {
2760 dSP;
2761 ENTER;
2762 SAVETMPS;
2763 PUTBACK;
2764 PUSHSTACK; 3244 PUSHSTACK;
3245
2765 PUSHMARK (SP); 3246 PUSHMARK (SP);
3247 PUTBACK;
2766 3248
2767 if (ix) 3249 if (ix)
2768 eval_sv (coderef, 0); 3250 eval_sv (coderef, 0);
2769 else 3251 else
2770 call_sv (coderef, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD); 3252 call_sv (coderef, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
2771 3253
2772 POPSTACK; 3254 POPSTACK;
2773 SPAGAIN; 3255 SPAGAIN;
2774 FREETMPS;
2775 LEAVE;
2776 PUTBACK;
2777 }
2778 3256
2779 if (!(coro->flags & CF_RUNNING)) 3257 if (current != coro)
2780 { 3258 {
3259 PUTBACK;
2781 save_perl (aTHX_ coro); 3260 save_perl (aTHX_ coro);
2782 load_perl (aTHX_ &temp); 3261 load_perl (aTHX_ current);
2783 SPAGAIN; 3262 SPAGAIN;
2784 } 3263 }
2785 } 3264 }
2786} 3265}
2787 3266
2791 ALIAS: 3270 ALIAS:
2792 is_ready = CF_READY 3271 is_ready = CF_READY
2793 is_running = CF_RUNNING 3272 is_running = CF_RUNNING
2794 is_new = CF_NEW 3273 is_new = CF_NEW
2795 is_destroyed = CF_DESTROYED 3274 is_destroyed = CF_DESTROYED
3275 is_suspended = CF_SUSPENDED
2796 CODE: 3276 CODE:
2797 RETVAL = boolSV (coro->flags & ix); 3277 RETVAL = boolSV (coro->flags & ix);
2798 OUTPUT: 3278 OUTPUT:
2799 RETVAL 3279 RETVAL
2800 3280
2801void 3281void
2802throw (Coro::State self, SV *throw = &PL_sv_undef) 3282throw (Coro::State self, SV *exception = &PL_sv_undef)
2803 PROTOTYPE: $;$ 3283 PROTOTYPE: $;$
2804 CODE: 3284 CODE:
2805{ 3285{
2806 struct coro *current = SvSTATE_current; 3286 struct coro *current = SvSTATE_current;
2807 SV **throwp = self == current ? &CORO_THROW : &self->except; 3287 SV **exceptionp = self == current ? &CORO_THROW : &self->except;
2808 SvREFCNT_dec (*throwp); 3288 SvREFCNT_dec (*exceptionp);
2809 *throwp = SvOK (throw) ? newSVsv (throw) : 0; 3289 SvGETMAGIC (exception);
3290 *exceptionp = SvOK (exception) ? newSVsv (exception) : 0;
2810} 3291}
2811 3292
2812void 3293void
2813api_trace (SV *coro, int flags = CC_TRACE | CC_TRACE_SUB) 3294api_trace (SV *coro, int flags = CC_TRACE | CC_TRACE_SUB)
2814 PROTOTYPE: $;$ 3295 PROTOTYPE: $;$
2816 3297
2817SV * 3298SV *
2818has_cctx (Coro::State coro) 3299has_cctx (Coro::State coro)
2819 PROTOTYPE: $ 3300 PROTOTYPE: $
2820 CODE: 3301 CODE:
2821 RETVAL = boolSV (!!coro->cctx); 3302 /* maybe manage the running flag differently */
3303 RETVAL = boolSV (!!coro->cctx || (coro->flags & CF_RUNNING));
2822 OUTPUT: 3304 OUTPUT:
2823 RETVAL 3305 RETVAL
2824 3306
2825int 3307int
2826is_traced (Coro::State coro) 3308is_traced (Coro::State coro)
2846 3328
2847void 3329void
2848force_cctx () 3330force_cctx ()
2849 PROTOTYPE: 3331 PROTOTYPE:
2850 CODE: 3332 CODE:
2851 SvSTATE_current->cctx->idle_sp = 0; 3333 cctx_current->idle_sp = 0;
2852 3334
2853void 3335void
2854swap_defsv (Coro::State self) 3336swap_defsv (Coro::State self)
2855 PROTOTYPE: $ 3337 PROTOTYPE: $
2856 ALIAS: 3338 ALIAS:
2864 SV **dst = ix ? (SV **)&self->slot->defav : (SV **)&self->slot->defsv; 3346 SV **dst = ix ? (SV **)&self->slot->defav : (SV **)&self->slot->defsv;
2865 3347
2866 SV *tmp = *src; *src = *dst; *dst = tmp; 3348 SV *tmp = *src; *src = *dst; *dst = tmp;
2867 } 3349 }
2868 3350
3351void
3352cancel (Coro::State self)
3353 CODE:
3354 coro_state_destroy (aTHX_ self);
3355 coro_call_on_destroy (aTHX_ self); /* actually only for Coro objects */
3356
3357
3358SV *
3359enable_times (int enabled = enable_times)
3360 CODE:
3361{
3362 RETVAL = boolSV (enable_times);
3363
3364 if (enabled != enable_times)
3365 {
3366 enable_times = enabled;
3367
3368 coro_times_update ();
3369 (enabled ? coro_times_sub : coro_times_add)(SvSTATE (coro_current));
3370 }
3371}
3372 OUTPUT:
3373 RETVAL
3374
3375void
3376times (Coro::State self)
3377 PPCODE:
3378{
3379 struct coro *current = SvSTATE (coro_current);
3380
3381 if (expect_false (current == self))
3382 {
3383 coro_times_update ();
3384 coro_times_add (SvSTATE (coro_current));
3385 }
3386
3387 EXTEND (SP, 2);
3388 PUSHs (sv_2mortal (newSVnv (self->t_real [0] + self->t_real [1] * 1e-9)));
3389 PUSHs (sv_2mortal (newSVnv (self->t_cpu [0] + self->t_cpu [1] * 1e-9)));
3390
3391 if (expect_false (current == self))
3392 coro_times_sub (SvSTATE (coro_current));
3393}
3394
3395void
3396swap_sv (Coro::State coro, SV *sv, SV *swapsv)
3397 CODE:
3398{
3399 struct coro *current = SvSTATE_current;
3400
3401 if (current == coro)
3402 SWAP_SVS (current);
3403
3404 if (!coro->swap_sv)
3405 coro->swap_sv = newAV ();
3406
3407 av_push (coro->swap_sv, SvREFCNT_inc_NN (SvRV (sv )));
3408 av_push (coro->swap_sv, SvREFCNT_inc_NN (SvRV (swapsv)));
3409
3410 if (current == coro)
3411 SWAP_SVS (current);
3412}
3413
2869 3414
2870MODULE = Coro::State PACKAGE = Coro 3415MODULE = Coro::State PACKAGE = Coro
2871 3416
2872BOOT: 3417BOOT:
2873{ 3418{
2874 int i;
2875
2876 av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE);
2877 sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE); 3419 sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE);
2878 sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE); 3420 sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE);
2879 coro_run_cv = get_cv (aTHX_ "Coro::_terminate", GV_ADD); 3421 cv_coro_run = get_cv ( "Coro::_coro_run" , GV_ADD);
3422 cv_coro_terminate = get_cv ( "Coro::terminate" , GV_ADD);
2880 coro_current = coro_get_sv (aTHX_ "Coro::current" , FALSE); 3423 coro_current = coro_get_sv (aTHX_ "Coro::current" , FALSE); SvREADONLY_on (coro_current);
2881 SvREADONLY_on (coro_current); 3424 av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE);
3425 av_destroy = coro_get_av (aTHX_ "Coro::destroy" , TRUE);
3426 sv_manager = coro_get_sv (aTHX_ "Coro::manager" , TRUE);
3427 sv_idle = coro_get_sv (aTHX_ "Coro::idle" , TRUE);
2882 3428
3429 sv_async_pool_idle = newSVpv ("[async pool idle]", 0); SvREADONLY_on (sv_async_pool_idle);
3430 sv_Coro = newSVpv ("Coro", 0); SvREADONLY_on (sv_Coro);
3431 cv_pool_handler = get_cv ("Coro::pool_handler", GV_ADD); SvREADONLY_on (cv_pool_handler);
3432 CvNODEBUG_on (get_cv ("Coro::_pool_handler", 0)); /* work around a debugger bug */
3433
2883 coro_stash = gv_stashpv ("Coro", TRUE); 3434 coro_stash = gv_stashpv ("Coro", TRUE);
2884 3435
2885 newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (PRIO_MAX)); 3436 newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (CORO_PRIO_MAX));
2886 newCONSTSUB (coro_stash, "PRIO_HIGH", newSViv (PRIO_HIGH)); 3437 newCONSTSUB (coro_stash, "PRIO_HIGH", newSViv (CORO_PRIO_HIGH));
2887 newCONSTSUB (coro_stash, "PRIO_NORMAL", newSViv (PRIO_NORMAL)); 3438 newCONSTSUB (coro_stash, "PRIO_NORMAL", newSViv (CORO_PRIO_NORMAL));
2888 newCONSTSUB (coro_stash, "PRIO_LOW", newSViv (PRIO_LOW)); 3439 newCONSTSUB (coro_stash, "PRIO_LOW", newSViv (CORO_PRIO_LOW));
2889 newCONSTSUB (coro_stash, "PRIO_IDLE", newSViv (PRIO_IDLE)); 3440 newCONSTSUB (coro_stash, "PRIO_IDLE", newSViv (CORO_PRIO_IDLE));
2890 newCONSTSUB (coro_stash, "PRIO_MIN", newSViv (PRIO_MIN)); 3441 newCONSTSUB (coro_stash, "PRIO_MIN", newSViv (CORO_PRIO_MIN));
2891
2892 for (i = PRIO_MAX - PRIO_MIN + 1; i--; )
2893 coro_ready[i] = newAV ();
2894 3442
2895 { 3443 {
2896 SV *sv = coro_get_sv (aTHX_ "Coro::API", TRUE); 3444 SV *sv = coro_get_sv (aTHX_ "Coro::API", TRUE);
2897 3445
2898 coroapi.schedule = api_schedule; 3446 coroapi.schedule = api_schedule;
3447 coroapi.schedule_to = api_schedule_to;
2899 coroapi.cede = api_cede; 3448 coroapi.cede = api_cede;
2900 coroapi.cede_notself = api_cede_notself; 3449 coroapi.cede_notself = api_cede_notself;
2901 coroapi.ready = api_ready; 3450 coroapi.ready = api_ready;
2902 coroapi.is_ready = api_is_ready; 3451 coroapi.is_ready = api_is_ready;
2903 coroapi.nready = coro_nready; 3452 coroapi.nready = coro_nready;
2907 sv_setiv (sv, (IV)&coroapi); 3456 sv_setiv (sv, (IV)&coroapi);
2908 SvREADONLY_on (sv); 3457 SvREADONLY_on (sv);
2909 } 3458 }
2910} 3459}
2911 3460
3461SV *
3462async (...)
3463 PROTOTYPE: &@
3464 CODE:
3465 RETVAL = coro_new (aTHX_ coro_stash, &ST (0), items, 1);
3466 api_ready (aTHX_ RETVAL);
3467 OUTPUT:
3468 RETVAL
3469
3470void
3471terminate (...)
3472 CODE:
3473 CORO_EXECUTE_SLF_XS (slf_init_terminate);
3474
2912void 3475void
2913schedule (...) 3476schedule (...)
2914 CODE: 3477 CODE:
2915 CORO_EXECUTE_SLF_XS (slf_init_schedule); 3478 CORO_EXECUTE_SLF_XS (slf_init_schedule);
3479
3480void
3481schedule_to (...)
3482 CODE:
3483 CORO_EXECUTE_SLF_XS (slf_init_schedule_to);
3484
3485void
3486cede_to (...)
3487 CODE:
3488 CORO_EXECUTE_SLF_XS (slf_init_cede_to);
2916 3489
2917void 3490void
2918cede (...) 3491cede (...)
2919 CODE: 3492 CODE:
2920 CORO_EXECUTE_SLF_XS (slf_init_cede); 3493 CORO_EXECUTE_SLF_XS (slf_init_cede);
2934void 3507void
2935_set_readyhook (SV *hook) 3508_set_readyhook (SV *hook)
2936 PROTOTYPE: $ 3509 PROTOTYPE: $
2937 CODE: 3510 CODE:
2938 SvREFCNT_dec (coro_readyhook); 3511 SvREFCNT_dec (coro_readyhook);
3512 SvGETMAGIC (hook);
3513 if (SvOK (hook))
3514 {
2939 coro_readyhook = SvOK (hook) ? newSVsv (hook) : 0; 3515 coro_readyhook = newSVsv (hook);
3516 CORO_READYHOOK = invoke_sv_ready_hook_helper;
3517 }
3518 else
3519 {
3520 coro_readyhook = 0;
3521 CORO_READYHOOK = 0;
3522 }
2940 3523
2941int 3524int
2942prio (Coro::State coro, int newprio = 0) 3525prio (Coro::State coro, int newprio = 0)
2943 PROTOTYPE: $;$ 3526 PROTOTYPE: $;$
2944 ALIAS: 3527 ALIAS:
2950 if (items > 1) 3533 if (items > 1)
2951 { 3534 {
2952 if (ix) 3535 if (ix)
2953 newprio = coro->prio - newprio; 3536 newprio = coro->prio - newprio;
2954 3537
2955 if (newprio < PRIO_MIN) newprio = PRIO_MIN; 3538 if (newprio < CORO_PRIO_MIN) newprio = CORO_PRIO_MIN;
2956 if (newprio > PRIO_MAX) newprio = PRIO_MAX; 3539 if (newprio > CORO_PRIO_MAX) newprio = CORO_PRIO_MAX;
2957 3540
2958 coro->prio = newprio; 3541 coro->prio = newprio;
2959 } 3542 }
2960} 3543}
2961 OUTPUT: 3544 OUTPUT:
2975 CODE: 3558 CODE:
2976 RETVAL = coro_nready; 3559 RETVAL = coro_nready;
2977 OUTPUT: 3560 OUTPUT:
2978 RETVAL 3561 RETVAL
2979 3562
2980# for async_pool speedup
2981void 3563void
2982_pool_1 (SV *cb) 3564suspend (Coro::State self)
3565 PROTOTYPE: $
2983 CODE: 3566 CODE:
2984{ 3567 self->flags |= CF_SUSPENDED;
2985 HV *hv = (HV *)SvRV (coro_current);
2986 struct coro *coro = SvSTATE_hv ((SV *)hv);
2987 AV *defav = GvAV (PL_defgv);
2988 SV *invoke = hv_delete (hv, "_invoke", sizeof ("_invoke") - 1, 0);
2989 AV *invoke_av;
2990 int i, len;
2991 3568
2992 if (!invoke) 3569void
3570resume (Coro::State self)
3571 PROTOTYPE: $
3572 CODE:
3573 self->flags &= ~CF_SUSPENDED;
3574
3575void
3576_pool_handler (...)
3577 CODE:
3578 CORO_EXECUTE_SLF_XS (slf_init_pool_handler);
3579
3580void
3581async_pool (SV *cv, ...)
3582 PROTOTYPE: &@
3583 PPCODE:
3584{
3585 HV *hv = (HV *)av_pop (av_async_pool);
3586 AV *av = newAV ();
3587 SV *cb = ST (0);
3588 int i;
3589
3590 av_extend (av, items - 2);
3591 for (i = 1; i < items; ++i)
3592 av_push (av, SvREFCNT_inc_NN (ST (i)));
3593
3594 if ((SV *)hv == &PL_sv_undef)
2993 { 3595 {
2994 SV *old = PL_diehook; 3596 SV *sv = coro_new (aTHX_ coro_stash, (SV **)&cv_pool_handler, 1, 1);
2995 PL_diehook = 0; 3597 hv = (HV *)SvREFCNT_inc_NN (SvRV (sv));
2996 SvREFCNT_dec (old); 3598 SvREFCNT_dec (sv);
2997 croak ("\3async_pool terminate\2\n");
2998 } 3599 }
2999 3600
3000 SvREFCNT_dec (coro->saved_deffh);
3001 coro->saved_deffh = SvREFCNT_inc_NN ((SV *)PL_defoutgv);
3002
3003 hv_store (hv, "desc", sizeof ("desc") - 1,
3004 newSVpvn ("[async_pool]", sizeof ("[async_pool]") - 1), 0);
3005
3006 invoke_av = (AV *)SvRV (invoke);
3007 len = av_len (invoke_av);
3008
3009 sv_setsv (cb, AvARRAY (invoke_av)[0]);
3010
3011 if (len > 0)
3012 { 3601 {
3013 av_fill (defav, len - 1); 3602 struct coro *coro = SvSTATE_hv (hv);
3014 for (i = 0; i < len; ++i) 3603
3015 av_store (defav, i, SvREFCNT_inc_NN (AvARRAY (invoke_av)[i + 1])); 3604 assert (!coro->invoke_cb);
3605 assert (!coro->invoke_av);
3606 coro->invoke_cb = SvREFCNT_inc (cb);
3607 coro->invoke_av = av;
3016 } 3608 }
3017}
3018 3609
3019void 3610 api_ready (aTHX_ (SV *)hv);
3020_pool_2 (SV *cb)
3021 CODE:
3022{
3023 HV *hv = (HV *)SvRV (coro_current);
3024 struct coro *coro = SvSTATE_hv ((SV *)hv);
3025 3611
3026 sv_setsv (cb, &PL_sv_undef); 3612 if (GIMME_V != G_VOID)
3027 3613 XPUSHs (sv_2mortal (newRV_noinc ((SV *)hv)));
3028 SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh; 3614 else
3029 coro->saved_deffh = 0;
3030
3031 if (coro_rss (aTHX_ coro) > SvUV (sv_pool_rss)
3032 || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size))
3033 {
3034 SV *old = PL_diehook;
3035 PL_diehook = 0;
3036 SvREFCNT_dec (old); 3615 SvREFCNT_dec (hv);
3037 croak ("\3async_pool terminate\2\n");
3038 }
3039
3040 av_clear (GvAV (PL_defgv));
3041 hv_store (hv, "desc", sizeof ("desc") - 1,
3042 newSVpvn ("[async_pool idle]", sizeof ("[async_pool idle]") - 1), 0);
3043
3044 coro->prio = 0;
3045
3046 if (coro->cctx && (coro->cctx->flags & CC_TRACE))
3047 api_trace (aTHX_ coro_current, 0);
3048
3049 av_push (av_async_pool, newSVsv (coro_current));
3050} 3616}
3051 3617
3052SV * 3618SV *
3053rouse_cb () 3619rouse_cb ()
3054 PROTOTYPE: 3620 PROTOTYPE:
3061rouse_wait (...) 3627rouse_wait (...)
3062 PROTOTYPE: ;$ 3628 PROTOTYPE: ;$
3063 PPCODE: 3629 PPCODE:
3064 CORO_EXECUTE_SLF_XS (slf_init_rouse_wait); 3630 CORO_EXECUTE_SLF_XS (slf_init_rouse_wait);
3065 3631
3632void
3633on_enter (SV *block)
3634 ALIAS:
3635 on_leave = 1
3636 PROTOTYPE: &
3637 CODE:
3638{
3639 struct coro *coro = SvSTATE_current;
3640 AV **avp = ix ? &coro->on_leave : &coro->on_enter;
3641
3642 block = s_get_cv_croak (block);
3643
3644 if (!*avp)
3645 *avp = newAV ();
3646
3647 av_push (*avp, SvREFCNT_inc (block));
3648
3649 if (!ix)
3650 on_enterleave_call (aTHX_ block);
3651
3652 LEAVE; /* pp_entersub unfortunately forces an ENTER/LEAVE around XS calls */
3653 SAVEDESTRUCTOR_X (ix ? coro_pop_on_leave : coro_pop_on_enter, (void *)coro);
3654 ENTER; /* pp_entersub unfortunately forces an ENTER/LEAVE around XS calls */
3655}
3656
3066 3657
3067MODULE = Coro::State PACKAGE = PerlIO::cede 3658MODULE = Coro::State PACKAGE = PerlIO::cede
3068 3659
3069BOOT: 3660BOOT:
3070 PerlIO_define_layer (aTHX_ &PerlIO_cede); 3661 PerlIO_define_layer (aTHX_ &PerlIO_cede);
3073MODULE = Coro::State PACKAGE = Coro::Semaphore 3664MODULE = Coro::State PACKAGE = Coro::Semaphore
3074 3665
3075SV * 3666SV *
3076new (SV *klass, SV *count = 0) 3667new (SV *klass, SV *count = 0)
3077 CODE: 3668 CODE:
3669{
3670 int semcnt = 1;
3671
3672 if (count)
3673 {
3674 SvGETMAGIC (count);
3675
3676 if (SvOK (count))
3677 semcnt = SvIV (count);
3678 }
3679
3078 RETVAL = sv_bless ( 3680 RETVAL = sv_bless (
3079 coro_waitarray_new (aTHX_ count && SvOK (count) ? SvIV (count) : 1), 3681 coro_waitarray_new (aTHX_ semcnt),
3080 GvSTASH (CvGV (cv)) 3682 GvSTASH (CvGV (cv))
3081 ); 3683 );
3684}
3082 OUTPUT: 3685 OUTPUT:
3083 RETVAL 3686 RETVAL
3084 3687
3085# helper for Coro::Channel 3688# helper for Coro::Channel and others
3086SV * 3689SV *
3087_alloc (int count) 3690_alloc (int count)
3088 CODE: 3691 CODE:
3089 RETVAL = coro_waitarray_new (aTHX_ count); 3692 RETVAL = coro_waitarray_new (aTHX_ count);
3090 OUTPUT: 3693 OUTPUT:
3148 for (i = 1; i <= wcount; ++i) 3751 for (i = 1; i <= wcount; ++i)
3149 PUSHs (sv_2mortal (newRV_inc (AvARRAY (av)[i]))); 3752 PUSHs (sv_2mortal (newRV_inc (AvARRAY (av)[i])));
3150 } 3753 }
3151} 3754}
3152 3755
3756MODULE = Coro::State PACKAGE = Coro::SemaphoreSet
3757
3758void
3759_may_delete (SV *sem, int count, int extra_refs)
3760 PPCODE:
3761{
3762 AV *av = (AV *)SvRV (sem);
3763
3764 if (SvREFCNT ((SV *)av) == 1 + extra_refs
3765 && AvFILLp (av) == 0 /* no waiters, just count */
3766 && SvIV (AvARRAY (av)[0]) == count)
3767 XSRETURN_YES;
3768
3769 XSRETURN_NO;
3770}
3771
3153MODULE = Coro::State PACKAGE = Coro::Signal 3772MODULE = Coro::State PACKAGE = Coro::Signal
3154 3773
3155SV * 3774SV *
3156new (SV *klass) 3775new (SV *klass)
3157 CODE: 3776 CODE:
3228 3847
3229void 3848void
3230_register (char *target, char *proto, SV *req) 3849_register (char *target, char *proto, SV *req)
3231 CODE: 3850 CODE:
3232{ 3851{
3233 CV *req_cv = coro_sv_2cv (req); 3852 SV *req_cv = s_get_cv_croak (req);
3234 /* newXSproto doesn't return the CV on 5.8 */ 3853 /* newXSproto doesn't return the CV on 5.8 */
3235 CV *slf_cv = newXS (target, coro_aio_req_xs, __FILE__); 3854 CV *slf_cv = newXS (target, coro_aio_req_xs, __FILE__);
3236 sv_setpv ((SV *)slf_cv, proto); 3855 sv_setpv ((SV *)slf_cv, proto);
3237 sv_magicext ((SV *)slf_cv, (SV *)req_cv, CORO_MAGIC_type_aio, 0, 0, 0); 3856 sv_magicext ((SV *)slf_cv, (SV *)req_cv, CORO_MAGIC_type_aio, 0, 0, 0);
3238} 3857}
3239 3858
3859MODULE = Coro::State PACKAGE = Coro::Select
3860
3861void
3862patch_pp_sselect ()
3863 CODE:
3864 if (!coro_old_pp_sselect)
3865 {
3866 coro_select_select = (SV *)get_cv ("Coro::Select::select", 0);
3867 coro_old_pp_sselect = PL_ppaddr [OP_SSELECT];
3868 PL_ppaddr [OP_SSELECT] = coro_pp_sselect;
3869 }
3870
3871void
3872unpatch_pp_sselect ()
3873 CODE:
3874 if (coro_old_pp_sselect)
3875 {
3876 PL_ppaddr [OP_SSELECT] = coro_old_pp_sselect;
3877 coro_old_pp_sselect = 0;
3878 }
3879

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines