--- Coro/Coro/State.xs 2008/11/20 07:02:43 1.318 +++ Coro/Coro/State.xs 2012/10/08 23:13:36 1.423 @@ -1,3 +1,8 @@ +/* this works around a bug in mingw32 providing a non-working setjmp */ +#define USE_NO_MINGW_SETJMP_TWO_ARGS + +#define NDEBUG 1 + #include "libcoro/coro.c" #define PERL_NO_GET_CONTEXT @@ -8,13 +13,22 @@ #include "XSUB.h" #include "perliol.h" -#include "patchlevel.h" +#include "schmorp.h" +#define ECB_NO_THREADS 1 +#include "ecb.h" + +#include #include #include #include -#ifdef WIN32 +#ifndef SVs_PADSTALE +# define SVs_PADSTALE 0 +#endif + +#if defined(_WIN32) +# undef HAS_GETTIMEOFDAY # undef setjmp # undef longjmp # undef _exit @@ -23,7 +37,7 @@ # include /* most portable stdint.h */ #endif -#ifdef HAVE_MMAP +#if HAVE_MMAP # include # include # ifndef MAP_ANONYMOUS @@ -53,60 +67,8 @@ /* the maximum number of idle cctx that will be pooled */ static int cctx_max_idle = 4; -#define PERL_VERSION_ATLEAST(a,b,c) \ - (PERL_REVISION > (a) \ - || (PERL_REVISION == (a) \ - && (PERL_VERSION > (b) \ - || (PERL_VERSION == (b) && PERL_SUBVERSION >= (c))))) - -#if !PERL_VERSION_ATLEAST (5,6,0) -# ifndef PL_ppaddr -# define PL_ppaddr ppaddr -# endif -# ifndef call_sv -# define call_sv perl_call_sv -# endif -# ifndef get_sv -# define get_sv perl_get_sv -# endif -# ifndef get_cv -# define get_cv perl_get_cv -# endif -# ifndef IS_PADGV -# define IS_PADGV(v) 0 -# endif -# ifndef IS_PADCONST -# define IS_PADCONST(v) 0 -# endif -#endif - -/* 5.11 */ -#ifndef CxHASARGS -# define CxHASARGS(cx) (cx)->blk_sub.hasargs -#endif - -/* 5.10.0 */ -#ifndef SvREFCNT_inc_NN -# define SvREFCNT_inc_NN(sv) SvREFCNT_inc (sv) -#endif - -/* 5.8.8 */ -#ifndef GV_NOTQUAL -# define GV_NOTQUAL 0 -#endif -#ifndef newSV -# define newSV(l) NEWSV(0,l) -#endif -#ifndef CvISXSUB_on -# define CvISXSUB_on(cv) (void)cv -#endif -#ifndef CvISXSUB -# define CvISXSUB(cv) (CvXSUB (cv) ? TRUE : FALSE) -#endif - -/* 5.8.7 */ -#ifndef SvRV_set -# define SvRV_set(s,v) SvRV(s) = (v) +#if defined(DEBUGGING) && PERL_VERSION_ATLEAST(5,12,0) +# define HAS_SCOPESTACK_NAME 1 #endif #if !__i386 && !__x86_64 && !__powerpc && !__m68k && !__alpha && !__mips && !__sparc64 @@ -132,22 +94,7 @@ # define STACKLEVEL ((void *)&stacklevel) #endif -#define IN_DESTRUCT (PL_main_cv == Nullcv) - -#if __GNUC__ >= 3 -# define attribute(x) __attribute__(x) -# define expect(expr,value) __builtin_expect ((expr),(value)) -# define INLINE static inline -#else -# define attribute(x) -# define expect(expr,value) (expr) -# define INLINE static -#endif - -#define expect_false(expr) expect ((expr) != 0, 0) -#define expect_true(expr) expect ((expr) != 0, 1) - -#define NOINLINE attribute ((noinline)) +#define IN_DESTRUCT PL_dirty #include "CoroAPI.h" #define GCoroAPI (&coroapi) /* very sneaky */ @@ -158,11 +105,23 @@ # endif #endif +#ifdef __linux +# include /* for timespec */ +# include /* for SYS_* */ +# ifdef SYS_clock_gettime +# define coro_clock_gettime(id, ts) syscall (SYS_clock_gettime, (id), (ts)) +# define CORO_CLOCK_MONOTONIC 1 +# define CORO_CLOCK_THREAD_CPUTIME_ID 3 +# endif +#endif + static double (*nvtime)(); /* so why doesn't it take void? */ +static void (*u2time)(pTHX_ UV ret[2]); /* we hijack an hopefully unused CV flag for our purposes */ #define CVf_SLF 0x4000 static OP *pp_slf (pTHX); +static void slf_destroy (pTHX_ struct coro *coro); static U32 cctx_gen; static size_t cctx_stacksize = CORO_STACKSIZE; @@ -174,6 +133,7 @@ static AV *av_destroy; /* destruction queue */ static SV *sv_manager; /* the manager coro */ +static SV *sv_idle; /* $Coro::idle */ static GV *irsgv; /* $/ */ static GV *stdoutgv; /* *STDOUT */ @@ -188,15 +148,21 @@ static AV *av_async_pool; /* idle pool */ static SV *sv_Coro; /* class string */ static CV *cv_pool_handler; -static CV *cv_coro_state_new; /* Coro::AnyEvent */ static SV *sv_activity; +/* enable processtime/realtime profiling */ +static char enable_times; +typedef U32 coro_ts[2]; +static coro_ts time_real, time_cpu; +static char times_valid; + static struct coro_cctx *cctx_first; static int cctx_count, cctx_idle; -enum { +enum +{ CC_MAPPED = 0x01, CC_NOREUSE = 0x02, /* throw this away after tracing */ CC_TRACE = 0x04, @@ -216,7 +182,9 @@ /* cpu state */ void *idle_sp; /* sp of top-level transfer/schedule/cede call */ - JMPENV *idle_te; /* same as idle_sp, but for top_env, TODO: remove once stable */ +#ifndef NDEBUG + JMPENV *idle_te; /* same as idle_sp, but for top_env */ +#endif JMPENV *top_env; coro_context cctx; @@ -227,57 +195,76 @@ unsigned char flags; } coro_cctx; -enum { +static coro_cctx *cctx_current; /* the currently running cctx */ + +/*****************************************************************************/ + +static MGVTBL coro_state_vtbl; + +enum +{ CF_RUNNING = 0x0001, /* coroutine is running */ CF_READY = 0x0002, /* coroutine is ready */ CF_NEW = 0x0004, /* has never been switched to */ - CF_DESTROYED = 0x0008, /* coroutine data has been freed */ + CF_ZOMBIE = 0x0008, /* coroutine data has been freed */ + CF_SUSPENDED = 0x0010, /* coroutine can't be scheduled */ + CF_NOCANCEL = 0x0020, /* cannot cancel, set slf_frame.data to 1 (hackish) */ }; /* the structure where most of the perl state is stored, overlaid on the cxstack */ typedef struct { - SV *defsv; - AV *defav; - SV *errsv; - SV *irsgv; -#define VAR(name,type) type name; -# include "state.h" -#undef VAR + #define VARx(name,expr,type) type name; + #include "state.h" } perl_slots; +/* how many context stack entries do we need for perl_slots */ #define SLOT_COUNT ((sizeof (perl_slots) + sizeof (PERL_CONTEXT) - 1) / sizeof (PERL_CONTEXT)) /* this is a structure representing a perl-level coroutine */ -struct coro { +struct coro +{ /* the C coroutine allocated to this perl coroutine, if any */ coro_cctx *cctx; + /* ready queue */ + struct coro *next_ready; + /* state data */ struct CoroSLF slf_frame; /* saved slf frame */ AV *mainstack; perl_slots *slot; /* basically the saved sp */ - CV *startcv; /* the CV to execute */ - AV *args; /* data associated with this coroutine (initial args) */ - int refcnt; /* coroutines are refcounted, yes */ - int flags; /* CF_ flags */ - HV *hv; /* the perl hash associated with this coro, if any */ - void (*on_destroy)(pTHX_ struct coro *coro); + CV *startcv; /* the CV to execute */ + AV *args; /* data associated with this coroutine (initial args) */ + int flags; /* CF_ flags */ + HV *hv; /* the perl hash associated with this coro, if any */ /* statistics */ int usecount; /* number of transfers to this coro */ /* coro process data */ int prio; - SV *except; /* exception to be thrown */ - SV *rouse_cb; + SV *except; /* exception to be thrown */ + SV *rouse_cb; /* last rouse callback */ + AV *on_destroy; /* callbacks or coros to notify on destroy */ + AV *status; /* the exit status list */ /* async_pool */ SV *saved_deffh; SV *invoke_cb; AV *invoke_av; + /* on_enter/on_leave */ + AV *on_enter; + AV *on_leave; + + /* swap_sv */ + AV *swap_sv; + + /* times */ + coro_ts t_cpu, t_real; + /* linked list */ struct coro *next, *prev; }; @@ -287,29 +274,124 @@ /* the following variables are effectively part of the perl context */ /* and get copied between struct coro and these variables */ -/* the mainr easonw e don't support windows process emulation */ +/* the main reason we don't support windows process emulation */ static struct CoroSLF slf_frame; /* the current slf frame */ /** Coro ********************************************************************/ -#define PRIO_MAX 3 -#define PRIO_HIGH 1 -#define PRIO_NORMAL 0 -#define PRIO_LOW -1 -#define PRIO_IDLE -3 -#define PRIO_MIN -4 +#define CORO_PRIO_MAX 3 +#define CORO_PRIO_HIGH 1 +#define CORO_PRIO_NORMAL 0 +#define CORO_PRIO_LOW -1 +#define CORO_PRIO_IDLE -3 +#define CORO_PRIO_MIN -4 /* for Coro.pm */ static SV *coro_current; static SV *coro_readyhook; -static AV *coro_ready [PRIO_MAX - PRIO_MIN + 1]; -static CV *cv_coro_run, *cv_coro_terminate; +static struct coro *coro_ready [CORO_PRIO_MAX - CORO_PRIO_MIN + 1][2]; /* head|tail */ +static CV *cv_coro_run; static struct coro *coro_first; #define coro_nready coroapi.nready +/** JIT *********************************************************************/ + +#if CORO_JIT + /* APPLE doesn't have HAVE_MMAP though */ + #define CORO_JIT_UNIXY (__linux || __FreeBSD__ || __OpenBSD__ || __NetBSD__ || __solaris || __APPLE__) + #ifndef CORO_JIT_TYPE + #if __x86_64 && CORO_JIT_UNIXY + #define CORO_JIT_TYPE "amd64-unix" + #elif __i386 && CORO_JIT_UNIXY + #define CORO_JIT_TYPE "x86-unix" + #endif + #endif +#endif + +#if !defined(CORO_JIT_TYPE) || !HAVE_MMAP + #undef CORO_JIT +#endif + +#if CORO_JIT + typedef void (*load_save_perl_slots_type)(perl_slots *); + static load_save_perl_slots_type load_perl_slots, save_perl_slots; +#endif + +/** Coro::Select ************************************************************/ + +static OP *(*coro_old_pp_sselect) (pTHX); +static SV *coro_select_select; + +/* horrible hack, but if it works... */ +static OP * +coro_pp_sselect (pTHX) +{ + dSP; + PUSHMARK (SP - 4); /* fake argument list */ + XPUSHs (coro_select_select); + PUTBACK; + + /* entersub is an UNOP, select a LISTOP... keep your fingers crossed */ + PL_op->op_flags |= OPf_STACKED; + PL_op->op_private = 0; + return PL_ppaddr [OP_ENTERSUB](aTHX); +} + +/** time stuff **************************************************************/ + +#ifdef HAS_GETTIMEOFDAY + +ecb_inline void +coro_u2time (pTHX_ UV ret[2]) +{ + struct timeval tv; + gettimeofday (&tv, 0); + + ret [0] = tv.tv_sec; + ret [1] = tv.tv_usec; +} + +ecb_inline double +coro_nvtime (void) +{ + struct timeval tv; + gettimeofday (&tv, 0); + + return tv.tv_sec + tv.tv_usec * 1e-6; +} + +ecb_inline void +time_init (pTHX) +{ + nvtime = coro_nvtime; + u2time = coro_u2time; +} + +#else + +ecb_inline void +time_init (pTHX) +{ + SV **svp; + + require_pv ("Time/HiRes.pm"); + + svp = hv_fetch (PL_modglobal, "Time::NVtime", 12, 0); + + if (!svp) croak ("Time::HiRes is required, but missing. Caught"); + if (!SvIOK (*svp)) croak ("Time::NVtime isn't a function pointer. Caught"); + + nvtime = INT2PTR (double (*)(), SvIV (*svp)); + + svp = hv_fetch (PL_modglobal, "Time::U2time", 12, 0); + u2time = INT2PTR (void (*)(pTHX_ UV ret[2]), SvIV (*svp)); +} + +#endif + /** lowlevel stuff **********************************************************/ -static SV * +static SV * ecb_noinline coro_get_sv (pTHX_ const char *name, int create) { #if PERL_VERSION_ATLEAST (5,10,0) @@ -319,7 +401,7 @@ return get_sv (name, create); } -static AV * +static AV * ecb_noinline coro_get_av (pTHX_ const char *name, int create) { #if PERL_VERSION_ATLEAST (5,10,0) @@ -329,7 +411,7 @@ return get_av (name, create); } -static HV * +static HV * ecb_noinline coro_get_hv (pTHX_ const char *name, int create) { #if PERL_VERSION_ATLEAST (5,10,0) @@ -339,17 +421,113 @@ return get_hv (name, create); } -/* may croak */ -INLINE CV * -coro_sv_2cv (pTHX_ SV *sv) +ecb_inline void +coro_times_update (void) +{ +#ifdef coro_clock_gettime + struct timespec ts; + + ts.tv_sec = ts.tv_nsec = 0; + coro_clock_gettime (CORO_CLOCK_THREAD_CPUTIME_ID, &ts); + time_cpu [0] = ts.tv_sec; time_cpu [1] = ts.tv_nsec; + + ts.tv_sec = ts.tv_nsec = 0; + coro_clock_gettime (CORO_CLOCK_MONOTONIC, &ts); + time_real [0] = ts.tv_sec; time_real [1] = ts.tv_nsec; +#else + dTHX; + UV tv[2]; + + u2time (aTHX_ tv); + time_real [0] = tv [0]; + time_real [1] = tv [1] * 1000; +#endif +} + +ecb_inline void +coro_times_add (struct coro *c) +{ + c->t_real [1] += time_real [1]; + if (c->t_real [1] > 1000000000) { c->t_real [1] -= 1000000000; ++c->t_real [0]; } + c->t_real [0] += time_real [0]; + + c->t_cpu [1] += time_cpu [1]; + if (c->t_cpu [1] > 1000000000) { c->t_cpu [1] -= 1000000000; ++c->t_cpu [0]; } + c->t_cpu [0] += time_cpu [0]; +} + +ecb_inline void +coro_times_sub (struct coro *c) +{ + if (c->t_real [1] < time_real [1]) { c->t_real [1] += 1000000000; --c->t_real [0]; } + c->t_real [1] -= time_real [1]; + c->t_real [0] -= time_real [0]; + + if (c->t_cpu [1] < time_cpu [1]) { c->t_cpu [1] += 1000000000; --c->t_cpu [0]; } + c->t_cpu [1] -= time_cpu [1]; + c->t_cpu [0] -= time_cpu [0]; +} + +/*****************************************************************************/ +/* magic glue */ + +#define CORO_MAGIC_type_cv 26 +#define CORO_MAGIC_type_state PERL_MAGIC_ext + +#define CORO_MAGIC_NN(sv, type) \ + (ecb_expect_true (SvMAGIC (sv)->mg_type == type) \ + ? SvMAGIC (sv) \ + : mg_find (sv, type)) + +#define CORO_MAGIC(sv, type) \ + (ecb_expect_true (SvMAGIC (sv)) \ + ? CORO_MAGIC_NN (sv, type) \ + : 0) + +#define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv) +#define CORO_MAGIC_state(sv) CORO_MAGIC_NN (((SV *)(sv)), CORO_MAGIC_type_state) + +ecb_inline MAGIC * +SvSTATEhv_p (pTHX_ SV *coro) { - HV *st; - GV *gvp; - return sv_2cv (sv, &st, &gvp, 0); + MAGIC *mg; + + if (ecb_expect_true ( + SvTYPE (coro) == SVt_PVHV + && (mg = CORO_MAGIC_state (coro)) + && mg->mg_virtual == &coro_state_vtbl + )) + return mg; + + return 0; +} + +ecb_inline struct coro * +SvSTATE_ (pTHX_ SV *coro) +{ + MAGIC *mg; + + if (SvROK (coro)) + coro = SvRV (coro); + + mg = SvSTATEhv_p (aTHX_ coro); + if (!mg) + croak ("Coro::State object required"); + + return (struct coro *)mg->mg_ptr; } -static AV * -coro_clone_padlist (pTHX_ CV *cv) +#define SvSTATE(sv) SvSTATE_ (aTHX_ (sv)) + +/* faster than SvSTATE, but expects a coroutine hv */ +#define SvSTATE_hv(hv) ((struct coro *)CORO_MAGIC_NN ((SV *)hv, CORO_MAGIC_type_state)->mg_ptr) +#define SvSTATE_current SvSTATE_hv (SvRV (coro_current)) + +/*****************************************************************************/ +/* padlist management and caching */ + +ecb_inline AV * +coro_derive_padlist (pTHX_ CV *cv) { AV *padlist = CvPADLIST (cv); AV *newpadlist, *newpad; @@ -364,32 +542,36 @@ newpad = (AV *)AvARRAY (padlist)[AvFILLp (padlist)]; --AvFILLp (padlist); - av_store (newpadlist, 0, SvREFCNT_inc_NN (*av_fetch (padlist, 0, FALSE))); + av_store (newpadlist, 0, SvREFCNT_inc_NN (AvARRAY (padlist)[0])); av_store (newpadlist, 1, (SV *)newpad); return newpadlist; } -static void +ecb_inline void free_padlist (pTHX_ AV *padlist) { /* may be during global destruction */ - if (SvREFCNT (padlist)) + if (!IN_DESTRUCT) { I32 i = AvFILLp (padlist); - while (i >= 0) + + while (i > 0) /* special-case index 0 */ { - SV **svp = av_fetch (padlist, i--, FALSE); - if (svp) - { - SV *sv; - while (&PL_sv_undef != (sv = av_pop ((AV *)*svp))) - SvREFCNT_dec (sv); + /* we try to be extra-careful here */ + AV *av = (AV *)AvARRAY (padlist)[i--]; + I32 j = AvFILLp (av); - SvREFCNT_dec (*svp); - } + while (j >= 0) + SvREFCNT_dec (AvARRAY (av)[j--]); + + AvFILLp (av) = -1; + SvREFCNT_dec (av); } + SvREFCNT_dec (AvARRAY (padlist)[0]); + + AvFILLp (padlist) = -1; SvREFCNT_dec ((SV*)padlist); } } @@ -400,6 +582,10 @@ AV *padlist; AV *av = (AV *)mg->mg_obj; + /* perl manages to free our internal AV and _then_ call us */ + if (IN_DESTRUCT) + return 0; + /* casting is fun. */ while (&PL_sv_undef != (SV *)(padlist = (AV *)av_pop (av))) free_padlist (aTHX_ padlist); @@ -409,65 +595,19 @@ return 0; } -#define CORO_MAGIC_type_cv 26 -#define CORO_MAGIC_type_state PERL_MAGIC_ext - static MGVTBL coro_cv_vtbl = { 0, 0, 0, 0, coro_cv_free }; -#define CORO_MAGIC_NN(sv, type) \ - (expect_true (SvMAGIC (sv)->mg_type == type) \ - ? SvMAGIC (sv) \ - : mg_find (sv, type)) - -#define CORO_MAGIC(sv, type) \ - (expect_true (SvMAGIC (sv)) \ - ? CORO_MAGIC_NN (sv, type) \ - : 0) - -#define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv) -#define CORO_MAGIC_state(sv) CORO_MAGIC_NN (((SV *)(sv)), CORO_MAGIC_type_state) - -INLINE struct coro * -SvSTATE_ (pTHX_ SV *coro) -{ - HV *stash; - MAGIC *mg; - - if (SvROK (coro)) - coro = SvRV (coro); - - if (expect_false (SvTYPE (coro) != SVt_PVHV)) - croak ("Coro::State object required"); - - stash = SvSTASH (coro); - if (expect_false (stash != coro_stash && stash != coro_state_stash)) - { - /* very slow, but rare, check */ - if (!sv_derived_from (sv_2mortal (newRV_inc (coro)), "Coro::State")) - croak ("Coro::State object required"); - } - - mg = CORO_MAGIC_state (coro); - return (struct coro *)mg->mg_ptr; -} - -#define SvSTATE(sv) SvSTATE_ (aTHX_ (sv)) - -/* faster than SvSTATE, but expects a coroutine hv */ -#define SvSTATE_hv(hv) ((struct coro *)CORO_MAGIC_NN ((SV *)hv, CORO_MAGIC_type_state)->mg_ptr) -#define SvSTATE_current SvSTATE_hv (SvRV (coro_current)) - /* the next two functions merely cache the padlists */ -static void +ecb_inline void get_padlist (pTHX_ CV *cv) { MAGIC *mg = CORO_MAGIC_cv (cv); AV *av; - if (expect_true (mg && AvFILLp ((av = (AV *)mg->mg_obj)) >= 0)) + if (ecb_expect_true (mg && AvFILLp ((av = (AV *)mg->mg_obj)) >= 0)) CvPADLIST (cv) = (AV *)AvARRAY (av)[AvFILLp (av)--]; else { @@ -479,30 +619,85 @@ CvPADLIST (cp) = 0; SvREFCNT_dec (cp); #else - CvPADLIST (cv) = coro_clone_padlist (aTHX_ cv); + CvPADLIST (cv) = coro_derive_padlist (aTHX_ cv); #endif } } -static void +ecb_inline void put_padlist (pTHX_ CV *cv) { MAGIC *mg = CORO_MAGIC_cv (cv); AV *av; - if (expect_false (!mg)) + if (ecb_expect_false (!mg)) mg = sv_magicext ((SV *)cv, (SV *)newAV (), CORO_MAGIC_type_cv, &coro_cv_vtbl, 0, 0); av = (AV *)mg->mg_obj; - if (expect_false (AvFILLp (av) >= AvMAX (av))) - av_extend (av, AvMAX (av) + 1); + if (ecb_expect_false (AvFILLp (av) >= AvMAX (av))) + av_extend (av, AvFILLp (av) + 1); AvARRAY (av)[++AvFILLp (av)] = (SV *)CvPADLIST (cv); } /** load & save, init *******************************************************/ +ecb_inline void +swap_sv (SV *a, SV *b) +{ + const U32 keep = SVs_PADSTALE | SVs_PADTMP | SVs_PADMY; /* keep these flags */ + SV tmp; + + /* swap sv_any */ + SvANY (&tmp) = SvANY (a); SvANY (a) = SvANY (b); SvANY (b) = SvANY (&tmp); + + /* swap sv_flags */ + SvFLAGS (&tmp) = SvFLAGS (a); + SvFLAGS (a) = (SvFLAGS (a) & keep) | (SvFLAGS (b ) & ~keep); + SvFLAGS (b) = (SvFLAGS (b) & keep) | (SvFLAGS (&tmp) & ~keep); + +#if PERL_VERSION_ATLEAST (5,10,0) + /* perl 5.10 and later complicates this _quite_ a bit, but it also + * is much faster, so no quarrels here. alternatively, we could + * sv_upgrade to avoid this. + */ + { + /* swap sv_u */ + tmp.sv_u = a->sv_u; a->sv_u = b->sv_u; b->sv_u = tmp.sv_u; + + /* if SvANY points to the head, we need to adjust the pointers, + * as the pointer for a still points to b, and maybe vice versa. + */ + #define svany_in_head(type) \ + (((1 << SVt_NULL) | (1 << SVt_BIND) | (1 << SVt_IV) | (1 << SVt_RV)) & (1 << (type))) + + if (svany_in_head (SvTYPE (a))) + SvANY (a) = (void *)((PTRV)SvANY (a) - (PTRV)b + (PTRV)a); + + if (svany_in_head (SvTYPE (b))) + SvANY (b) = (void *)((PTRV)SvANY (b) - (PTRV)a + (PTRV)b); + } +#endif +} + +/* swap sv heads, at least logically */ +static void +swap_svs (pTHX_ Coro__State c) +{ + int i; + + for (i = 0; i <= AvFILLp (c->swap_sv); i += 2) + swap_sv (AvARRAY (c->swap_sv)[i], AvARRAY (c->swap_sv)[i + 1]); +} + +#define SWAP_SVS(coro) \ + if (ecb_expect_false ((coro)->swap_sv)) \ + swap_svs (aTHX_ (coro)) + +static void +on_enterleave_call (pTHX_ SV *cb); + static void load_perl (pTHX_ Coro__State c) { @@ -511,14 +706,12 @@ PL_mainstack = c->mainstack; - GvSV (PL_defgv) = slot->defsv; - GvAV (PL_defgv) = slot->defav; - GvSV (PL_errgv) = slot->errsv; - GvSV (irsgv) = slot->irsgv; - - #define VAR(name,type) PL_ ## name = slot->name; - # include "state.h" - #undef VAR +#if CORO_JIT + load_perl_slots (slot); +#else + #define VARx(name,expr,type) expr = slot->name; + #include "state.h" +#endif { dSP; @@ -526,7 +719,7 @@ CV *cv; /* now do the ugly restore mess */ - while (expect_true (cv = (CV *)POPs)) + while (ecb_expect_true (cv = (CV *)POPs)) { put_padlist (aTHX_ cv); /* mark this padlist as available */ CvDEPTH (cv) = PTR2IV (POPs); @@ -538,11 +731,47 @@ slf_frame = c->slf_frame; CORO_THROW = c->except; + + if (ecb_expect_false (enable_times)) + { + if (ecb_expect_false (!times_valid)) + coro_times_update (); + + coro_times_sub (c); + } + + if (ecb_expect_false (c->on_enter)) + { + int i; + + for (i = 0; i <= AvFILLp (c->on_enter); ++i) + on_enterleave_call (aTHX_ AvARRAY (c->on_enter)[i]); + } + + SWAP_SVS (c); } static void save_perl (pTHX_ Coro__State c) { + SWAP_SVS (c); + + if (ecb_expect_false (c->on_leave)) + { + int i; + + for (i = AvFILLp (c->on_leave); i >= 0; --i) + on_enterleave_call (aTHX_ AvARRAY (c->on_leave)[i]); + } + + times_valid = 0; + + if (ecb_expect_false (enable_times)) + { + coro_times_update (); times_valid = 1; + coro_times_add (c); + } + c->except = CORO_THROW; c->slf_frame = slf_frame; @@ -561,15 +790,15 @@ /* this loop was inspired by pp_caller */ for (;;) { - while (expect_true (cxix >= 0)) + while (ecb_expect_true (cxix >= 0)) { PERL_CONTEXT *cx = &ccstk[cxix--]; - if (expect_true (CxTYPE (cx) == CXt_SUB || CxTYPE (cx) == CXt_FORMAT)) + if (ecb_expect_true (CxTYPE (cx) == CXt_SUB) || ecb_expect_false (CxTYPE (cx) == CXt_FORMAT)) { CV *cv = cx->blk_sub.cv; - if (expect_true (CvDEPTH (cv))) + if (ecb_expect_true (CvDEPTH (cv))) { EXTEND (SP, 3); PUSHs ((SV *)CvPADLIST (cv)); @@ -582,7 +811,7 @@ } } - if (expect_true (top_si->si_type == PERLSI_MAIN)) + if (ecb_expect_true (top_si->si_type == PERLSI_MAIN)) break; top_si = top_si->si_prev; @@ -594,30 +823,27 @@ } /* allocate some space on the context stack for our purposes */ - /* we manually unroll here, as usually 2 slots is enough */ - if (SLOT_COUNT >= 1) CXINC; - if (SLOT_COUNT >= 2) CXINC; - if (SLOT_COUNT >= 3) CXINC; - { - int i; - for (i = 3; i < SLOT_COUNT; ++i) - CXINC; - } - cxstack_ix -= SLOT_COUNT; /* undo allocation */ + if (ecb_expect_false (cxstack_ix + (int)SLOT_COUNT >= cxstack_max)) + { + unsigned int i; + + for (i = 0; i < SLOT_COUNT; ++i) + CXINC; + + cxstack_ix -= SLOT_COUNT; /* undo allocation */ + } c->mainstack = PL_mainstack; { perl_slots *slot = c->slot = (perl_slots *)(cxstack + cxstack_ix + 1); - slot->defav = GvAV (PL_defgv); - slot->defsv = DEFSV; - slot->errsv = ERRSV; - slot->irsgv = GvSV (irsgv); - - #define VAR(name,type) slot->name = PL_ ## name; - # include "state.h" - #undef VAR +#if CORO_JIT + save_perl_slots (slot); +#else + #define VARx(name,expr,type) slot->name = expr; + #include "state.h" +#endif } } @@ -633,7 +859,7 @@ static void coro_init_stacks (pTHX) { - PL_curstackinfo = new_stackinfo(32, 8); + PL_curstackinfo = new_stackinfo(32, 4 + SLOT_COUNT); /* 3 is minimum due to perl rounding down in scope.c:GROW() */ PL_curstackinfo->si_type = PERLSI_MAIN; PL_curstack = PL_curstackinfo->si_stack; PL_mainstack = PL_curstack; /* remember in case we switch stacks */ @@ -658,6 +884,9 @@ New(54,PL_scopestack,8,I32); PL_scopestack_ix = 0; PL_scopestack_max = 8; +#if HAS_SCOPESTACK_NAME + New(54,PL_scopestack_name,8,const char*); +#endif New(54,PL_savestack,24,ANY); PL_savestack_ix = 0; @@ -695,6 +924,9 @@ Safefree (PL_tmps_stack); Safefree (PL_markstack); Safefree (PL_scopestack); +#if HAS_SCOPESTACK_NAME + Safefree (PL_scopestack_name); +#endif Safefree (PL_savestack); #if !PERL_VERSION_ATLEAST (5,10,0) Safefree (PL_retstack); @@ -750,13 +982,10 @@ /* * This overrides the default magic get method of %SIG elements. * The original one doesn't provide for reading back of PL_diehook/PL_warnhook - * and instead of tryign to save and restore the hash elements, we just provide - * readback here. - * We only do this when the hook is != 0, as they are often set to 0 temporarily, - * not expecting this to actually change the hook. This is a potential problem - * when a schedule happens then, but we ignore this. + * and instead of trying to save and restore the hash elements (extremely slow), + * we just provide our own readback here. */ -static int +static int ecb_cold coro_sigelem_get (pTHX_ SV *sv, MAGIC *mg) { const char *s = MgPV_nolen_const (mg); @@ -770,7 +999,16 @@ if (svp) { - sv_setsv (sv, *svp ? *svp : &PL_sv_undef); + SV *ssv; + + if (!*svp) + ssv = &PL_sv_undef; + else if (SvTYPE (*svp) == SVt_PVCV) /* perlio directly stores a CV in warnhook. ugh. */ + ssv = sv_2mortal (newRV_inc (*svp)); + else + ssv = *svp; + + sv_setsv (sv, ssv); return 0; } } @@ -778,7 +1016,7 @@ return orig_sigelem_get ? orig_sigelem_get (aTHX_ sv, mg) : 0; } -static int +static int ecb_cold coro_sigelem_clr (pTHX_ SV *sv, MAGIC *mg) { const char *s = MgPV_nolen_const (mg); @@ -802,7 +1040,7 @@ return orig_sigelem_clr ? orig_sigelem_clr (aTHX_ sv, mg) : 0; } -static int +static int ecb_cold coro_sigelem_set (pTHX_ SV *sv, MAGIC *mg) { const char *s = MgPV_nolen_const (mg); @@ -817,7 +1055,7 @@ if (svp) { SV *old = *svp; - *svp = newSVsv (sv); + *svp = SvOK (sv) ? newSVsv (sv) : 0; SvREFCNT_dec (old); return 0; } @@ -845,10 +1083,10 @@ return 1; } -static UNOP coro_setup_op; +static UNOP init_perl_op; -static void NOINLINE /* noinline to keep it out of the transfer fast path */ -coro_setup (pTHX_ struct coro *coro) +ecb_noinline static void /* noinline to keep it out of the transfer fast path */ +init_perl (pTHX_ struct coro *coro) { /* * emulate part of the perl startup here. @@ -859,23 +1097,27 @@ PL_curcop = &PL_compiling; PL_in_eval = EVAL_NULL; PL_comppad = 0; + PL_comppad_name = 0; + PL_comppad_name_fill = 0; + PL_comppad_name_floor = 0; PL_curpm = 0; PL_curpad = 0; PL_localizing = 0; - PL_dirty = 0; PL_restartop = 0; #if PERL_VERSION_ATLEAST (5,10,0) PL_parser = 0; #endif + PL_hints = 0; /* recreate the die/warn hooks */ - PL_diehook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__DIE__" , sizeof ("__DIE__" ) - 1, 1), rv_diehook ); - PL_warnhook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__WARN__", sizeof ("__WARN__") - 1, 1), rv_warnhook); + PL_diehook = SvREFCNT_inc (rv_diehook); + PL_warnhook = SvREFCNT_inc (rv_warnhook); GvSV (PL_defgv) = newSV (0); GvAV (PL_defgv) = coro->args; coro->args = 0; GvSV (PL_errgv) = newSV (0); GvSV (irsgv) = newSVpvn ("\n", 1); sv_magic (GvSV (irsgv), (SV *)irsgv, PERL_MAGIC_sv, "/", 0); + GvHV (PL_hintgv) = 0; PL_rs = newSVsv (GvSV (irsgv)); PL_defoutgv = (GV *)SvREFCNT_inc_NN (stdoutgv); @@ -900,21 +1142,30 @@ */ slf_frame.prepare = prepare_nop; /* provide a nop function for an eventual pp_slf */ slf_frame.check = slf_check_nop; /* signal pp_slf to not repeat */ + slf_frame.destroy = 0; /* and we have to provide the pp_slf op in any case, so pp_slf can skip it */ - coro_setup_op.op_next = PL_op; - coro_setup_op.op_type = OP_CUSTOM; - coro_setup_op.op_ppaddr = pp_slf; + init_perl_op.op_next = PL_op; + init_perl_op.op_type = OP_ENTERSUB; + init_perl_op.op_ppaddr = pp_slf; /* no flags etc. required, as an init function won't be called */ - PL_op = (OP *)&coro_setup_op; + PL_op = (OP *)&init_perl_op; - /* copy throw, in case it was set before coro_setup */ + /* copy throw, in case it was set before init_perl */ CORO_THROW = coro->except; + + SWAP_SVS (coro); + + if (ecb_expect_false (enable_times)) + { + coro_times_update (); + coro_times_sub (coro); + } } static void -coro_destruct (pTHX_ struct coro *coro) +coro_unwind_stacks (pTHX) { if (!IN_DESTRUCT) { @@ -932,31 +1183,69 @@ /* unwind main stack */ dounwind (-1); } +} - SvREFCNT_dec (GvSV (PL_defgv)); - SvREFCNT_dec (GvAV (PL_defgv)); - SvREFCNT_dec (GvSV (PL_errgv)); - SvREFCNT_dec (PL_defoutgv); - SvREFCNT_dec (PL_rs); - SvREFCNT_dec (GvSV (irsgv)); +static void +destroy_perl (pTHX_ struct coro *coro) +{ + SV *svf [9]; - SvREFCNT_dec (PL_diehook); - SvREFCNT_dec (PL_warnhook); - - SvREFCNT_dec (coro->saved_deffh); - SvREFCNT_dec (coro->rouse_cb); - SvREFCNT_dec (coro->invoke_cb); - SvREFCNT_dec (coro->invoke_av); + { + SV *old_current = SvRV (coro_current); + struct coro *current = SvSTATE (old_current); + + assert (("FATAL: tried to destroy currently running coroutine", coro->mainstack != PL_mainstack)); + + save_perl (aTHX_ current); + + /* this will cause transfer_check to croak on block*/ + SvRV_set (coro_current, (SV *)coro->hv); + + load_perl (aTHX_ coro); + + coro_unwind_stacks (aTHX); + + /* restore swapped sv's */ + SWAP_SVS (coro); - coro_destruct_stacks (aTHX); + coro_destruct_stacks (aTHX); + + /* now save some sv's to be free'd later */ + svf [0] = GvSV (PL_defgv); + svf [1] = (SV *)GvAV (PL_defgv); + svf [2] = GvSV (PL_errgv); + svf [3] = (SV *)PL_defoutgv; + svf [4] = PL_rs; + svf [5] = GvSV (irsgv); + svf [6] = (SV *)GvHV (PL_hintgv); + svf [7] = PL_diehook; + svf [8] = PL_warnhook; + assert (9 == sizeof (svf) / sizeof (*svf)); + + SvRV_set (coro_current, old_current); + + load_perl (aTHX_ current); + } + + { + unsigned int i; + + for (i = 0; i < sizeof (svf) / sizeof (*svf); ++i) + SvREFCNT_dec (svf [i]); + + SvREFCNT_dec (coro->saved_deffh); + SvREFCNT_dec (coro->rouse_cb); + SvREFCNT_dec (coro->invoke_cb); + SvREFCNT_dec (coro->invoke_av); + } } -INLINE void +ecb_inline void free_coro_mortal (pTHX) { - if (expect_true (coro_mortal)) + if (ecb_expect_true (coro_mortal)) { - SvREFCNT_dec (coro_mortal); + SvREFCNT_dec ((SV *)coro_mortal); coro_mortal = 0; } } @@ -966,16 +1255,14 @@ { COP *oldcop = 0; int oldcxix = -2; - struct coro *coro = SvSTATE_current; /* trace cctx is tied to specific coro */ - coro_cctx *cctx = coro->cctx; while ((PL_op = CALL_FPTR (PL_op->op_ppaddr) (aTHX))) { PERL_ASYNC_CHECK (); - if (cctx->flags & CC_TRACE_ALL) + if (cctx_current->flags & CC_TRACE_ALL) { - if (PL_op->op_type == OP_LEAVESUB && cctx->flags & CC_TRACE_SUB) + if (PL_op->op_type == OP_LEAVESUB && cctx_current->flags & CC_TRACE_SUB) { PERL_CONTEXT *cx = &cxstack[cxstack_ix]; SV **bot, **top; @@ -1022,13 +1309,12 @@ { SV **cb; - if (oldcxix != cxstack_ix && cctx->flags & CC_TRACE_SUB) + if (oldcxix != cxstack_ix && cctx_current->flags & CC_TRACE_SUB) { PERL_CONTEXT *cx = &cxstack[cxstack_ix]; if (CxTYPE (cx) == CXt_SUB && oldcxix < cxstack_ix) { - runops_proc_t old_runops = PL_runops; dSP; GV *gv = CvGV (cx->blk_sub.cv); SV *fullname = sv_2mortal (newSV (0)); @@ -1056,7 +1342,7 @@ oldcxix = cxstack_ix; } - if (cctx->flags & CC_TRACE_LINE) + if (cctx_current->flags & CC_TRACE_LINE) { dSP; @@ -1085,14 +1371,12 @@ return 0; } -static struct coro_cctx *cctx_ssl_cctx; static struct CoroSLF cctx_ssl_frame; static void slf_prepare_set_stacklevel (pTHX_ struct coro_transfer_args *ta) { - ta->prev = (struct coro *)cctx_ssl_cctx; - ta->next = 0; + ta->prev = 0; } static int @@ -1104,12 +1388,12 @@ } /* initialises PL_top_env and injects a pseudo-slf-call to set the stacklevel */ -static void NOINLINE -cctx_prepare (pTHX_ coro_cctx *cctx) +static void ecb_noinline +cctx_prepare (pTHX) { PL_top_env = &PL_start_env; - if (cctx->flags & CC_TRACE) + if (cctx_current->flags & CC_TRACE) PL_runops = runops_trace; /* we already must be executing an SLF op, there is no other valid way @@ -1118,7 +1402,6 @@ slf_frame.prepare && PL_op->op_ppaddr == pp_slf)); /* we must emulate leaving pp_slf, which is done inside slf_check_set_stacklevel */ - cctx_ssl_cctx = cctx; cctx_ssl_frame = slf_frame; slf_frame.prepare = slf_prepare_set_stacklevel; @@ -1126,12 +1409,24 @@ } /* the tail of transfer: execute stuff we can only do after a transfer */ -INLINE void +ecb_inline void transfer_tail (pTHX) { free_coro_mortal (aTHX); } +/* try to exit the same way perl's main function would do */ +/* we do not bother resetting the environment or other things *7 +/* that are not, uhm, essential */ +/* this obviously also doesn't work when perl is embedded */ +static void ecb_noinline ecb_cold +perlish_exit (pTHX) +{ + int exitstatus = perl_destruct (PL_curinterp); + perl_free (PL_curinterp); + exit (exitstatus); +} + /* * this is a _very_ stripped down perl interpreter ;) */ @@ -1151,7 +1446,7 @@ /* PL_nop = PL_nop->op_next */ /* inject a fake subroutine call to cctx_init */ - cctx_prepare (aTHX_ (coro_cctx *)arg); + cctx_prepare (aTHX); /* cctx_run is the alternative tail of transfer() */ transfer_tail (aTHX); @@ -1161,23 +1456,22 @@ perl_run (PL_curinterp); /* * Unfortunately, there is no way to get at the return values of the - * coro body here, as perl_run destroys these + * coro body here, as perl_run destroys these. Likewise, we cannot catch + * runtime errors here, as this is just a random interpreter, not a thread. */ /* * If perl-run returns we assume exit() was being called or the coro * fell off the end, which seems to be the only valid (non-bug) - * reason for perl_run to return. We try to exit by jumping to the - * bootstrap-time "top" top_env, as we cannot restore the "main" - * coroutine as Coro has no such concept + * reason for perl_run to return. We try to mimic whatever perl is normally + * doing in that case. YMMV. */ - PL_top_env = main_top_env; - JMPENV_JUMP (2); /* I do not feel well about the hardcoded 2 at all */ + perlish_exit (aTHX); } } static coro_cctx * -cctx_new () +cctx_new (void) { coro_cctx *cctx; @@ -1193,7 +1487,7 @@ /* create a new cctx only suitable as source */ static coro_cctx * -cctx_new_empty () +cctx_new_empty (void) { coro_cctx *cctx = cctx_new (); @@ -1205,7 +1499,7 @@ /* create a new cctx suitable as destination/running a perl interpreter */ static coro_cctx * -cctx_new_run () +cctx_new_run (void) { coro_cctx *cctx = cctx_new (); void *stack_start; @@ -1214,7 +1508,7 @@ #if HAVE_MMAP cctx->ssize = ((cctx_stacksize * sizeof (long) + PAGESIZE - 1) / PAGESIZE + CORO_STACKGUARD) * PAGESIZE; /* mmap supposedly does allocate-on-write for us */ - cctx->sptr = mmap (0, cctx->ssize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0); + cctx->sptr = mmap (0, cctx->ssize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANONYMOUS, -1, 0); if (cctx->sptr != (void *)-1) { @@ -1256,6 +1550,8 @@ if (!cctx) return; + assert (("FATAL: tried to destroy current cctx", cctx != cctx_current)); + --cctx_count; coro_destroy (&cctx->cctx); @@ -1283,13 +1579,13 @@ static coro_cctx * cctx_get (pTHX) { - while (expect_true (cctx_first)) + while (ecb_expect_true (cctx_first)) { coro_cctx *cctx = cctx_first; cctx_first = cctx->next; --cctx_idle; - if (expect_true (!CCTX_EXPIRED (cctx))) + if (ecb_expect_true (!CCTX_EXPIRED (cctx))) return cctx; cctx_destroy (cctx); @@ -1304,7 +1600,7 @@ assert (("FATAL: cctx_put called on non-initialised cctx in Coro (please report)", cctx->sptr)); /* free another cctx if overlimit */ - if (expect_false (cctx_idle >= cctx_max_idle)) + if (ecb_expect_false (cctx_idle >= cctx_max_idle)) { coro_cctx *first = cctx_first; cctx_first = first->next; @@ -1325,44 +1621,40 @@ { /* TODO: throwing up here is considered harmful */ - if (expect_true (prev != next)) + if (ecb_expect_true (prev != next)) { - if (expect_false (!(prev->flags & (CF_RUNNING | CF_NEW)))) - croak ("Coro::State::transfer called with non-running/new prev Coro::State, but can only transfer from running or new states,"); + if (ecb_expect_false (!(prev->flags & (CF_RUNNING | CF_NEW)))) + croak ("Coro::State::transfer called with a blocked prev Coro::State, but can only transfer from running or new states,"); - if (expect_false (next->flags & CF_RUNNING)) - croak ("Coro::State::transfer called with running next Coro::State, but can only transfer to inactive states,"); - - if (expect_false (next->flags & CF_DESTROYED)) - croak ("Coro::State::transfer called with destroyed next Coro::State, but can only transfer to inactive states,"); + if (ecb_expect_false (next->flags & (CF_RUNNING | CF_ZOMBIE | CF_SUSPENDED))) + croak ("Coro::State::transfer called with running, destroyed or suspended next Coro::State, but can only transfer to inactive states,"); #if !PERL_VERSION_ATLEAST (5,10,0) - if (expect_false (PL_lex_state != LEX_NOTPARSING)) + if (ecb_expect_false (PL_lex_state != LEX_NOTPARSING)) croak ("Coro::State::transfer called while parsing, but this is not supported in your perl version,"); #endif } } /* always use the TRANSFER macro */ -static void NOINLINE /* noinline so we have a fixed stackframe */ +static void ecb_noinline /* noinline so we have a fixed stackframe */ transfer (pTHX_ struct coro *prev, struct coro *next, int force_cctx) { dSTACKLEVEL; /* sometimes transfer is only called to set idle_sp */ - if (expect_false (!next)) + if (ecb_expect_false (!prev)) { - ((coro_cctx *)prev)->idle_sp = STACKLEVEL; - assert (((coro_cctx *)prev)->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */ + cctx_current->idle_sp = STACKLEVEL; + assert (cctx_current->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */ } - else if (expect_true (prev != next)) + else if (ecb_expect_true (prev != next)) { - coro_cctx *prev__cctx; + coro_cctx *cctx_prev; - if (expect_false (prev->flags & CF_NEW)) + if (ecb_expect_false (prev->flags & CF_NEW)) { /* create a new empty/source context */ - prev->cctx = cctx_new_empty (); prev->flags &= ~CF_NEW; prev->flags |= CF_RUNNING; } @@ -1373,49 +1665,49 @@ /* first get rid of the old state */ save_perl (aTHX_ prev); - if (expect_false (next->flags & CF_NEW)) + if (ecb_expect_false (next->flags & CF_NEW)) { /* need to start coroutine */ next->flags &= ~CF_NEW; /* setup coroutine call */ - coro_setup (aTHX_ next); + init_perl (aTHX_ next); } else load_perl (aTHX_ next); - prev__cctx = prev->cctx; - /* possibly untie and reuse the cctx */ - if (expect_true ( - prev__cctx->idle_sp == STACKLEVEL - && !(prev__cctx->flags & CC_TRACE) + if (ecb_expect_true ( + cctx_current->idle_sp == STACKLEVEL + && !(cctx_current->flags & CC_TRACE) && !force_cctx )) { /* I assume that stacklevel is a stronger indicator than PL_top_env changes */ - assert (("FATAL: current top_env must equal previous top_env in Coro (please report)", PL_top_env == prev__cctx->idle_te)); - - prev->cctx = 0; + assert (("FATAL: current top_env must equal previous top_env in Coro (please report)", PL_top_env == cctx_current->idle_te)); - /* if the cctx is about to be destroyed we need to make sure we won't see it in cctx_get */ - /* without this the next cctx_get might destroy the prev__cctx while still in use */ - if (expect_false (CCTX_EXPIRED (prev__cctx))) - if (!next->cctx) + /* if the cctx is about to be destroyed we need to make sure we won't see it in cctx_get. */ + /* without this the next cctx_get might destroy the running cctx while still in use */ + if (ecb_expect_false (CCTX_EXPIRED (cctx_current))) + if (ecb_expect_true (!next->cctx)) next->cctx = cctx_get (aTHX); - cctx_put (prev__cctx); + cctx_put (cctx_current); } + else + prev->cctx = cctx_current; ++next->usecount; - if (expect_true (!next->cctx)) - next->cctx = cctx_get (aTHX); + cctx_prev = cctx_current; + cctx_current = ecb_expect_false (next->cctx) ? next->cctx : cctx_get (aTHX); + + next->cctx = 0; - if (expect_false (prev__cctx != next->cctx)) + if (ecb_expect_false (cctx_prev != cctx_current)) { - prev__cctx->top_env = PL_top_env; - PL_top_env = next->cctx->top_env; - coro_transfer (&prev__cctx->cctx, &next->cctx->cctx); + cctx_prev->top_env = PL_top_env; + PL_top_env = cctx_current->top_env; + coro_transfer (&cctx_prev->cctx, &cctx_current->cctx); } transfer_tail (aTHX); @@ -1427,16 +1719,20 @@ /** high level stuff ********************************************************/ -static int +/* this function is actually Coro, not Coro::State, but we call it from here */ +/* because it is convenient - but it hasn't been declared yet for that reason */ +static void +coro_call_on_destroy (pTHX_ struct coro *coro); + +static void coro_state_destroy (pTHX_ struct coro *coro) { - if (coro->flags & CF_DESTROYED) - return 0; + if (coro->flags & CF_ZOMBIE) + return; - if (coro->on_destroy) - coro->on_destroy (aTHX_ coro); + slf_destroy (aTHX_ coro); - coro->flags |= CF_DESTROYED; + coro->flags |= CF_ZOMBIE; if (coro->flags & CF_READY) { @@ -1447,32 +1743,25 @@ else coro->flags |= CF_READY; /* make sure it is NOT put into the readyqueue */ - if (coro->mainstack && coro->mainstack != main_mainstack) - { - struct coro temp; - - assert (("FATAL: tried to destroy currently running coroutine (please report)", !(coro->flags & CF_RUNNING))); - - save_perl (aTHX_ &temp); - load_perl (aTHX_ coro); - - coro_destruct (aTHX_ coro); + if (coro->next) coro->next->prev = coro->prev; + if (coro->prev) coro->prev->next = coro->next; + if (coro == coro_first) coro_first = coro->next; - load_perl (aTHX_ &temp); - - coro->slot = 0; - } + if (coro->mainstack + && coro->mainstack != main_mainstack + && coro->slot + && !PL_dirty) + destroy_perl (aTHX_ coro); cctx_destroy (coro->cctx); SvREFCNT_dec (coro->startcv); SvREFCNT_dec (coro->args); + SvREFCNT_dec (coro->swap_sv); SvREFCNT_dec (CORO_THROW); - if (coro->next) coro->next->prev = coro->prev; - if (coro->prev) coro->prev->next = coro->next; - if (coro == coro_first) coro_first = coro->next; + coro_call_on_destroy (aTHX_ coro); - return 1; + /* more destruction mayhem in coro_state_free */ } static int @@ -1481,23 +1770,22 @@ struct coro *coro = (struct coro *)mg->mg_ptr; mg->mg_ptr = 0; - coro->hv = 0; + coro_state_destroy (aTHX_ coro); + SvREFCNT_dec (coro->on_destroy); + SvREFCNT_dec (coro->status); - if (--coro->refcnt < 0) - { - coro_state_destroy (aTHX_ coro); - Safefree (coro); - } + Safefree (coro); return 0; } -static int +static int ecb_cold coro_state_dup (pTHX_ MAGIC *mg, CLONE_PARAMS *params) { - struct coro *coro = (struct coro *)mg->mg_ptr; - - ++coro->refcnt; + /* called when perl clones the current process the slow way (windows process emulation) */ + /* WE SIMply nuke the pointers in the copy, causing perl to croak */ + mg->mg_ptr = 0; + mg->mg_virtual = 0; return 0; } @@ -1530,89 +1818,72 @@ TRANSFER (ta, 1); } -/*****************************************************************************/ -/* gensub: simple closure generation utility */ - -#define GENSUB_ARG CvXSUBANY (cv).any_ptr - -/* create a closure from XS, returns a code reference */ -/* the arg can be accessed via GENSUB_ARG from the callback */ -/* the callback must use dXSARGS/XSRETURN */ -static SV * -gensub (pTHX_ void (*xsub)(pTHX_ CV *), void *arg) -{ - CV *cv = (CV *)newSV (0); - - sv_upgrade ((SV *)cv, SVt_PVCV); - - CvANON_on (cv); - CvISXSUB_on (cv); - CvXSUB (cv) = xsub; - GENSUB_ARG = arg; - - return newRV_noinc ((SV *)cv); -} - /** Coro ********************************************************************/ -INLINE void +ecb_inline void coro_enq (pTHX_ struct coro *coro) { - av_push (coro_ready [coro->prio - PRIO_MIN], SvREFCNT_inc_NN (coro->hv)); + struct coro **ready = coro_ready [coro->prio - CORO_PRIO_MIN]; + + SvREFCNT_inc_NN (coro->hv); + + coro->next_ready = 0; + *(ready [0] ? &ready [1]->next_ready : &ready [0]) = coro; + ready [1] = coro; } -INLINE SV * +ecb_inline struct coro * coro_deq (pTHX) { int prio; - for (prio = PRIO_MAX - PRIO_MIN + 1; --prio >= 0; ) - if (AvFILLp (coro_ready [prio]) >= 0) - return av_shift (coro_ready [prio]); + for (prio = CORO_PRIO_MAX - CORO_PRIO_MIN + 1; --prio >= 0; ) + { + struct coro **ready = coro_ready [prio]; + + if (ready [0]) + { + struct coro *coro = ready [0]; + ready [0] = coro->next_ready; + return coro; + } + } return 0; } -static int -api_ready (pTHX_ SV *coro_sv) +static void +invoke_sv_ready_hook_helper (void) { - struct coro *coro; - SV *sv_hook; - void (*xs_hook)(void); + dTHX; + dSP; + + ENTER; + SAVETMPS; + + PUSHMARK (SP); + PUTBACK; + call_sv (coro_readyhook, G_VOID | G_DISCARD); - if (SvROK (coro_sv)) - coro_sv = SvRV (coro_sv); + FREETMPS; + LEAVE; +} - coro = SvSTATE (coro_sv); +static int +api_ready (pTHX_ SV *coro_sv) +{ + struct coro *coro = SvSTATE (coro_sv); if (coro->flags & CF_READY) return 0; coro->flags |= CF_READY; - sv_hook = coro_nready ? 0 : coro_readyhook; - xs_hook = coro_nready ? 0 : coroapi.readyhook; - coro_enq (aTHX_ coro); - ++coro_nready; - - if (sv_hook) - { - dSP; - ENTER; - SAVETMPS; - - PUSHMARK (SP); - PUTBACK; - call_sv (sv_hook, G_VOID | G_DISCARD); - - FREETMPS; - LEAVE; - } - - if (xs_hook) - xs_hook (); + if (!coro_nready++) + if (coroapi.readyhook) + coroapi.readyhook (); return 1; } @@ -1624,7 +1895,7 @@ } /* expects to own a reference to next->hv */ -INLINE void +ecb_inline void prepare_schedule_to (pTHX_ struct coro_transfer_args *ta, struct coro *next) { SV *prev_sv = SvRV (coro_current); @@ -1645,49 +1916,62 @@ { for (;;) { - SV *next_sv = coro_deq (aTHX); + struct coro *next = coro_deq (aTHX); - if (expect_true (next_sv)) + if (ecb_expect_true (next)) { - struct coro *next = SvSTATE_hv (next_sv); - /* cannot transfer to destroyed coros, skip and look for next */ - if (expect_false (next->flags & CF_DESTROYED)) - SvREFCNT_dec (next_sv); /* coro_nready has already been taken care of by destroy */ + if (ecb_expect_false (next->flags & (CF_ZOMBIE | CF_SUSPENDED))) + SvREFCNT_dec (next->hv); /* coro_nready has already been taken care of by destroy */ else { next->flags &= ~CF_READY; --coro_nready; - return prepare_schedule_to (aTHX_ ta, next); + prepare_schedule_to (aTHX_ ta, next); + break; } } else { /* nothing to schedule: call the idle handler */ - dSP; + if (SvROK (sv_idle) + && SvOBJECT (SvRV (sv_idle))) + { + if (SvRV (sv_idle) == SvRV (coro_current)) + croak ("FATAL: $Coro::IDLE blocked itself - did you try to block inside an event loop callback? Caught"); - ENTER; - SAVETMPS; + ++coro_nready; /* hack so that api_ready doesn't invoke ready hook */ + api_ready (aTHX_ SvRV (sv_idle)); + --coro_nready; + } + else + { + /* TODO: deprecated, remove, cannot work reliably *//*D*/ + dSP; - PUSHMARK (SP); - PUTBACK; - call_sv (get_sv ("Coro::idle", FALSE), G_VOID | G_DISCARD); + ENTER; + SAVETMPS; + + PUSHMARK (SP); + PUTBACK; + call_sv (sv_idle, G_VOID | G_DISCARD); - FREETMPS; - LEAVE; + FREETMPS; + LEAVE; + } } } } -INLINE void +ecb_inline void prepare_cede (pTHX_ struct coro_transfer_args *ta) { api_ready (aTHX_ coro_current); prepare_schedule (aTHX_ ta); } -INLINE void +ecb_inline void prepare_cede_notself (pTHX_ struct coro_transfer_args *ta) { SV *prev = SvRV (coro_current); @@ -1727,7 +2011,7 @@ prepare_cede (aTHX_ &ta); - if (expect_true (ta.prev != ta.next)) + if (ecb_expect_true (ta.prev != ta.next)) { TRANSFER (ta, 1); return 1; @@ -1756,12 +2040,15 @@ { struct coro *coro = SvSTATE (coro_sv); + if (coro->flags & CF_RUNNING) + croak ("cannot enable tracing on a running coroutine, caught"); + if (flags & CC_TRACE) { if (!coro->cctx) coro->cctx = cctx_new_run (); else if (!(coro->cctx->flags & CC_TRACE)) - croak ("cannot enable tracing on coroutine with custom stack,"); + croak ("cannot enable tracing on coroutine with custom stack, caught"); coro->cctx->flags |= CC_NOREUSE | (flags & (CC_TRACE | CC_TRACE_ALL)); } @@ -1777,56 +2064,254 @@ } static void +coro_push_av (pTHX_ AV *av, I32 gimme_v) +{ + if (AvFILLp (av) >= 0 && gimme_v != G_VOID) + { + dSP; + + if (gimme_v == G_SCALAR) + XPUSHs (AvARRAY (av)[AvFILLp (av)]); + else + { + int i; + EXTEND (SP, AvFILLp (av) + 1); + + for (i = 0; i <= AvFILLp (av); ++i) + PUSHs (AvARRAY (av)[i]); + } + + PUTBACK; + } +} + +static void +coro_push_on_destroy (pTHX_ struct coro *coro, SV *cb) +{ + if (!coro->on_destroy) + coro->on_destroy = newAV (); + + av_push (coro->on_destroy, cb); +} + +static void +slf_destroy_join (pTHX_ struct CoroSLF *frame) +{ + SvREFCNT_dec ((SV *)((struct coro *)frame->data)->hv); +} + +static int +slf_check_join (pTHX_ struct CoroSLF *frame) +{ + struct coro *coro = (struct coro *)frame->data; + + if (!coro->status) + return 1; + + frame->destroy = 0; + + coro_push_av (aTHX_ coro->status, GIMME_V); + + SvREFCNT_dec ((SV *)coro->hv); + + return 0; +} + +static void +slf_init_join (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + struct coro *coro = SvSTATE (items > 0 ? arg [0] : &PL_sv_undef); + + if (items > 1) + croak ("join called with too many arguments"); + + if (coro->status) + frame->prepare = prepare_nop; + else + { + coro_push_on_destroy (aTHX_ coro, SvREFCNT_inc_NN (SvRV (coro_current))); + frame->prepare = prepare_schedule; + } + + frame->check = slf_check_join; + frame->destroy = slf_destroy_join; + frame->data = (void *)coro; + SvREFCNT_inc (coro->hv); +} + +static void coro_call_on_destroy (pTHX_ struct coro *coro) { - SV **on_destroyp = hv_fetch (coro->hv, "_on_destroy", sizeof ("_on_destroy") - 1, 0); - SV **statusp = hv_fetch (coro->hv, "_status", sizeof ("_status") - 1, 0); + AV *od = coro->on_destroy; + + if (!od) + return; - if (on_destroyp) + while (AvFILLp (od) >= 0) { - AV *on_destroy = (AV *)SvRV (*on_destroyp); + SV *cb = sv_2mortal (av_pop (od)); - while (AvFILLp (on_destroy) >= 0) + /* coro hv's (and only hv's at the moment) are supported as well */ + if (SvSTATEhv_p (aTHX_ cb)) + api_ready (aTHX_ cb); + else { dSP; /* don't disturb outer sp */ - SV *cb = av_pop (on_destroy); - PUSHMARK (SP); - if (statusp) + if (coro->status) { - int i; - AV *status = (AV *)SvRV (*statusp); - EXTEND (SP, AvFILLp (status) + 1); - - for (i = 0; i <= AvFILLp (status); ++i) - PUSHs (AvARRAY (status)[i]); + PUTBACK; + coro_push_av (aTHX_ coro->status, G_ARRAY); + SPAGAIN; } PUTBACK; - call_sv (sv_2mortal (cb), G_VOID | G_DISCARD); + call_sv (cb, G_VOID | G_DISCARD); } } } static void -slf_init_terminate (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +coro_set_status (pTHX_ struct coro *coro, SV **arg, int items) { - int i; - HV *hv = (HV *)SvRV (coro_current); - AV *av = newAV (); + AV *av; + + if (coro->status) + { + av = coro->status; + av_clear (av); + } + else + av = coro->status = newAV (); + + /* items are actually not so common, so optimise for this case */ + if (items) + { + int i; - av_extend (av, items - 1); - for (i = 0; i < items; ++i) - av_push (av, SvREFCNT_inc_NN (arg [i])); + av_extend (av, items - 1); - hv_store (hv, "_status", sizeof ("_status") - 1, newRV_noinc ((SV *)av), 0); + for (i = 0; i < items; ++i) + av_push (av, SvREFCNT_inc_NN (arg [i])); + } +} - av_push (av_destroy, (SV *)newRV_inc ((SV *)hv)); /* RVinc for perl */ +static void +slf_init_terminate_cancel_common (pTHX_ struct CoroSLF *frame, HV *coro_hv) +{ + av_push (av_destroy, (SV *)newRV_inc ((SV *)coro_hv)); /* RVinc for perl */ api_ready (aTHX_ sv_manager); frame->prepare = prepare_schedule; frame->check = slf_check_repeat; + + /* as a minor optimisation, we could unwind all stacks here */ + /* but that puts extra pressure on pp_slf, and is not worth much */ + /*coro_unwind_stacks (aTHX);*/ +} + +static void +slf_init_terminate (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + HV *coro_hv = (HV *)SvRV (coro_current); + + coro_set_status (aTHX_ SvSTATE ((SV *)coro_hv), arg, items); + slf_init_terminate_cancel_common (aTHX_ frame, coro_hv); +} + +static void +slf_init_cancel (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + HV *coro_hv; + struct coro *coro; + + if (items <= 0) + croak ("Coro::cancel called without coro object,"); + + coro = SvSTATE (arg [0]); + coro_hv = coro->hv; + + coro_set_status (aTHX_ coro, arg + 1, items - 1); + + if (ecb_expect_false (coro->flags & CF_NOCANCEL)) + { + /* coro currently busy cancelling something, so just notify it */ + coro->slf_frame.data = (void *)coro; + + frame->prepare = prepare_nop; + frame->check = slf_check_nop; + } + else if (coro_hv == (HV *)SvRV (coro_current)) + { + /* cancelling the current coro is allowed, and equals terminate */ + slf_init_terminate_cancel_common (aTHX_ frame, coro_hv); + } + else + { + struct coro *self = SvSTATE_current; + + /* otherwise we cancel directly, purely for speed reasons + * unfortunately, this requires some magic trickery, as + * somebody else could cancel us, so we have to fight the cancellation. + * this is ugly, and hopefully fully worth the extra speed. + * besides, I can't get the slow-but-safe version working... + */ + slf_frame.data = 0; + self->flags |= CF_NOCANCEL; + coro_state_destroy (aTHX_ coro); + self->flags &= ~CF_NOCANCEL; + + if (slf_frame.data) + { + /* while we were busy we have been cancelled, so terminate */ + slf_init_terminate_cancel_common (aTHX_ frame, self->hv); + } + else + { + frame->prepare = prepare_nop; + frame->check = slf_check_nop; + } + } +} + +static int +slf_check_safe_cancel (pTHX_ struct CoroSLF *frame) +{ + frame->prepare = 0; + coro_unwind_stacks (aTHX); + + slf_init_terminate_cancel_common (aTHX_ frame, (HV *)SvRV (coro_current)); + + return 1; +} + +static int +safe_cancel (pTHX_ struct coro *coro, SV **arg, int items) +{ + if (coro->cctx) + croak ("coro inside C callback, unable to cancel at this time, caught"); + + if (coro->flags & CF_NEW) + { + coro_set_status (aTHX_ coro, arg, items); + coro_state_destroy (aTHX_ coro); + } + else + { + if (!coro->slf_frame.prepare) + croak ("coro outside an SLF function, unable to cancel at this time, caught"); + + slf_destroy (aTHX_ coro); + + coro_set_status (aTHX_ coro, arg, items); + coro->slf_frame.prepare = prepare_nop; + coro->slf_frame.check = slf_check_safe_cancel; + + api_ready (aTHX_ (SV *)coro->hv); + } + + return 1; } /*****************************************************************************/ @@ -1867,7 +2352,7 @@ HV *hv = (HV *)SvRV (coro_current); struct coro *coro = SvSTATE_hv ((SV *)hv); - if (expect_true (coro->saved_deffh)) + if (ecb_expect_true (coro->saved_deffh)) { /* subsequent iteration */ SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh; @@ -1876,10 +2361,8 @@ if (coro_rss (aTHX_ coro) > SvUV (sv_pool_rss) || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size)) { - coro->invoke_cb = SvREFCNT_inc_NN ((SV *)cv_coro_terminate); - coro->invoke_av = newAV (); - - frame->prepare = prepare_nop; + slf_init_terminate_cancel_common (aTHX_ frame, hv); + return; } else { @@ -1914,21 +2397,22 @@ coro_rouse_callback (pTHX_ CV *cv) { dXSARGS; - SV *data = (SV *)GENSUB_ARG; + SV *data = (SV *)S_GENSUB_ARG; if (SvTYPE (SvRV (data)) != SVt_PVAV) { /* first call, set args */ - AV *av = newAV (); SV *coro = SvRV (data); + AV *av = newAV (); SvRV_set (data, (SV *)av); - api_ready (aTHX_ coro); - SvREFCNT_dec (coro); /* better take a full copy of the arguments */ while (items--) av_store (av, items, newSVsv (ST (items))); + + api_ready (aTHX_ coro); + SvREFCNT_dec (coro); } XSRETURN_EMPTY; @@ -1955,7 +2439,7 @@ for (i = 0; i <= AvFILLp (av); ++i) PUSHs (sv_2mortal (AvARRAY (av)[i])); - /* we have stolen the elements, so ste length to zero and free */ + /* we have stolen the elements, so set length to zero and free */ AvFILLp (av) = -1; av_undef (av); @@ -1989,8 +2473,8 @@ croak ("Coro::rouse_wait called with illegal callback argument,"); { - CV *cv = (CV *)SvRV (cb); /* for GENSUB_ARG */ - SV *data = (SV *)GENSUB_ARG; + CV *cv = (CV *)SvRV (cb); /* for S_GENSUB_ARG */ + SV *data = (SV *)S_GENSUB_ARG; frame->data = (void *)data; frame->prepare = SvTYPE (SvRV (data)) == SVt_PVAV ? prepare_nop : prepare_schedule; @@ -2004,7 +2488,7 @@ HV *hv = (HV *)SvRV (coro_current); struct coro *coro = SvSTATE_hv (hv); SV *data = newRV_inc ((SV *)hv); - SV *cb = gensub (aTHX_ coro_rouse_callback, (void *)data); + SV *cb = s_gensub (aTHX_ coro_rouse_callback, (void *)data); sv_magicext (SvRV (cb), data, CORO_MAGIC_type_rouse, 0, 0, 0); SvREFCNT_dec (data); /* magicext increases the refcount */ @@ -2113,6 +2597,23 @@ frame->check = slf_check_nop; } +/* "undo"/cancel a running slf call - used when cancelling a coro, mainly */ +static void +slf_destroy (pTHX_ struct coro *coro) +{ + /* this callback is reserved for slf functions needing to do cleanup */ + if (coro->slf_frame.destroy && coro->slf_frame.prepare && !PL_dirty) + coro->slf_frame.destroy (aTHX_ &coro->slf_frame); + + /* + * The on_destroy above most likely is from an SLF call. + * Since by definition the SLF call will not finish when we destroy + * the coro, we will have to force-finish it here, otherwise + * cleanup functions cannot call SLF functions. + */ + coro->slf_frame.prepare = 0; +} + /* * these not obviously related functions are all rolled into one * function to increase chances that they all will call transfer with the same @@ -2127,7 +2628,7 @@ /* set up the slf frame, unless it has already been set-up */ /* the latter happens when a new coro has been started */ /* or when a new cctx was attached to an existing coroutine */ - if (expect_true (!slf_frame.prepare)) + if (ecb_expect_true (!slf_frame.prepare)) { /* first iteration */ dSP; @@ -2178,7 +2679,7 @@ slf_frame.prepare = 0; /* invalidate the frame, we are done processing it */ /* exception handling */ - if (expect_false (CORO_THROW)) + if (ecb_expect_false (CORO_THROW)) { SV *exception = sv_2mortal (CORO_THROW); @@ -2189,14 +2690,15 @@ /* return value handling - mostly like entersub */ /* make sure we put something on the stack in scalar context */ - if (GIMME_V == G_SCALAR) + if (GIMME_V == G_SCALAR + && ecb_expect_false (PL_stack_sp != PL_stack_base + checkmark + 1)) { dSP; SV **bot = PL_stack_base + checkmark; if (sp == bot) /* too few, push undef */ bot [1] = &PL_sv_undef; - else if (sp != bot + 1) /* too many, take last one */ + else /* too many, take last one */ bot [1] = *sp; SP = bot + 1; @@ -2239,8 +2741,8 @@ if (items > slf_arga) { slf_arga = items; - free (slf_argv); - slf_argv = malloc (slf_arga * sizeof (SV *)); + Safefree (slf_argv); + New (0, slf_argv, slf_arga, SV *); } slf_argc = items; @@ -2252,12 +2754,59 @@ slf_argc = 0; PL_op->op_ppaddr = pp_slf; - PL_op->op_type = OP_CUSTOM; /* maybe we should leave it at entersub? */ + /*PL_op->op_type = OP_CUSTOM; /* we do behave like entersub still */ PL_op = (OP *)&slf_restore; } /*****************************************************************************/ +/* dynamic wind */ + +static void +on_enterleave_call (pTHX_ SV *cb) +{ + dSP; + + PUSHSTACK; + + PUSHMARK (SP); + PUTBACK; + call_sv (cb, G_VOID | G_DISCARD); + SPAGAIN; + + POPSTACK; +} + +static SV * +coro_avp_pop_and_free (pTHX_ AV **avp) +{ + AV *av = *avp; + SV *res = av_pop (av); + + if (AvFILLp (av) < 0) + { + *avp = 0; + SvREFCNT_dec (av); + } + + return res; +} + +static void +coro_pop_on_enter (pTHX_ void *coro) +{ + SV *cb = coro_avp_pop_and_free (aTHX_ &((struct coro *)coro)->on_enter); + SvREFCNT_dec (cb); +} + +static void +coro_pop_on_leave (pTHX_ void *coro) +{ + SV *cb = coro_avp_pop_and_free (aTHX_ &((struct coro *)coro)->on_leave); + on_enterleave_call (aTHX_ sv_2mortal (cb)); +} + +/*****************************************************************************/ /* PerlIO::cede */ typedef struct @@ -2266,7 +2815,7 @@ NV next, every; } PerlIOCede; -static IV +static IV ecb_cold PerlIOCede_pushed (pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab) { PerlIOCede *self = PerlIOSelf (f, PerlIOCede); @@ -2277,7 +2826,7 @@ return PerlIOBuf_pushed (aTHX_ f, mode, Nullsv, tab); } -static SV * +static SV * ecb_cold PerlIOCede_getarg (pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags) { PerlIOCede *self = PerlIOSelf (f, PerlIOCede); @@ -2338,15 +2887,20 @@ static SV * coro_waitarray_new (pTHX_ int count) { - /* a semaphore contains a counter IV in $sem->[0] and any waiters after that */ + /* a waitarray=semaphore contains a counter IV in $sem->[0] and any waiters after that */ AV *av = newAV (); SV **ary; /* unfortunately, building manually saves memory */ Newx (ary, 2, SV *); AvALLOC (av) = ary; - /*AvARRAY (av) = ary;*/ - SvPVX ((SV *)av) = (char *)ary; /* 5.8.8 needs this syntax instead of AvARRAY = ary */ +#if PERL_VERSION_ATLEAST (5,10,0) + AvARRAY (av) = ary; +#else + /* 5.8.8 needs this syntax instead of AvARRAY = ary, yet */ + /* -DDEBUGGING flags this as a bug, despite it perfectly working */ + SvPVX ((SV *)av) = (char *)ary; +#endif AvMAX (av) = 1; AvFILLp (av) = 0; ary [0] = newSViv (count); @@ -2394,10 +2948,10 @@ } static void -coro_semaphore_on_destroy (pTHX_ struct coro *coro) +coro_semaphore_destroy (pTHX_ struct CoroSLF *frame) { /* call $sem->adjust (0) to possibly wake up some other waiters */ - coro_semaphore_adjust (aTHX_ (AV *)coro->slf_frame.data, 0); + coro_semaphore_adjust (aTHX_ (AV *)frame->data, 0); } static int @@ -2405,13 +2959,14 @@ { AV *av = (AV *)frame->data; SV *count_sv = AvARRAY (av)[0]; + SV *coro_hv = SvRV (coro_current); /* if we are about to throw, don't actually acquire the lock, just throw */ if (CORO_THROW) return 0; else if (SvIVX (count_sv) > 0) { - SvSTATE_current->on_destroy = 0; + frame->destroy = 0; if (acquire) SvIVX (count_sv) = SvIVX (count_sv) - 1; @@ -2426,12 +2981,11 @@ /* if we were woken up but can't down, we look through the whole */ /* waiters list and only add us if we aren't in there already */ /* this avoids some degenerate memory usage cases */ - - for (i = 1; i <= AvFILLp (av); ++i) - if (AvARRAY (av)[i] == SvRV (coro_current)) + for (i = AvFILLp (av); i > 0; --i) /* i > 0 is not an off-by-one bug */ + if (AvARRAY (av)[i] == coro_hv) return 1; - av_push (av, SvREFCNT_inc (SvRV (coro_current))); + av_push (av, SvREFCNT_inc (coro_hv)); return 1; } } @@ -2464,10 +3018,9 @@ frame->data = (void *)sv_2mortal (SvREFCNT_inc ((SV *)av)); frame->prepare = prepare_schedule; - /* to avoid race conditions when a woken-up coro gets terminated */ /* we arrange for a temporary on_destroy that calls adjust (0) */ - SvSTATE_current->on_destroy = coro_semaphore_on_destroy; + frame->destroy = coro_semaphore_destroy; } } @@ -2485,9 +3038,9 @@ { /* callback form */ AV *av = (AV *)SvRV (arg [0]); - CV *cb_cv = coro_sv_2cv (aTHX_ arg [1]); + SV *cb_cv = s_get_cv_croak (arg [1]); - av_push (av, (SV *)SvREFCNT_inc_NN (cb_cv)); + av_push (av, SvREFCNT_inc_NN (cb_cv)); if (SvIVX (AvARRAY (av)[0]) > 0) coro_semaphore_adjust (aTHX_ av, 0); @@ -2521,8 +3074,20 @@ cb = av_shift (av); - api_ready (aTHX_ cb); - sv_setiv (cb, 0); /* signal waiter */ + if (SvTYPE (cb) == SVt_PVCV) + { + dSP; + PUSHMARK (SP); + XPUSHs (sv_2mortal (newRV_inc ((SV *)av))); + PUTBACK; + call_sv (cb, G_VOID | G_DISCARD | G_EVAL | G_KEEPERR); + } + else + { + api_ready (aTHX_ cb); + sv_setiv (cb, 0); /* signal waiter */ + } + SvREFCNT_dec (cb); --count; @@ -2541,7 +3106,18 @@ { AV *av = (AV *)SvRV (arg [0]); - if (SvIVX (AvARRAY (av)[0])) + if (items >= 2) + { + SV *cb_cv = s_get_cv_croak (arg [1]); + av_push (av, SvREFCNT_inc_NN (cb_cv)); + + if (SvIVX (AvARRAY (av)[0])) + coro_signal_wake (aTHX_ av, 1); /* must be the only waiter */ + + frame->prepare = prepare_nop; + frame->check = slf_check_nop; + } + else if (SvIVX (AvARRAY (av)[0])) { SvIVX (AvARRAY (av)[0]) = 0; frame->prepare = prepare_nop; @@ -2549,7 +3125,7 @@ } else { - SV *waiter = newRV_inc (SvRV (coro_current)); /* owned by signal av */ + SV *waiter = newSVsv (coro_current); /* owned by signal av */ av_push (av, waiter); @@ -2577,7 +3153,7 @@ coro_aio_callback (pTHX_ CV *cv) { dXSARGS; - AV *state = (AV *)GENSUB_ARG; + AV *state = (AV *)S_GENSUB_ARG; SV *coro = av_pop (state); SV *data_sv = newSV (sizeof (struct io_state)); @@ -2672,7 +3248,7 @@ static SV *prio_cv; static SV *prio_sv; - if (expect_false (!prio_cv)) + if (ecb_expect_false (!prio_cv)) { prio_cv = (SV *)get_cv ("IO::AIO::aioreq_pri", 0); prio_sv = newSViv (0); @@ -2701,14 +3277,14 @@ PUSHs (arg [i]); /* now push the callback closure */ - PUSHs (sv_2mortal (gensub (aTHX_ coro_aio_callback, (void *)SvREFCNT_inc_NN ((SV *)state)))); + PUSHs (sv_2mortal (s_gensub (aTHX_ coro_aio_callback, (void *)SvREFCNT_inc_NN ((SV *)state)))); /* now call the AIO function - we assume our request is uncancelable */ PUTBACK; call_sv ((SV *)req, G_VOID | G_DISCARD); } - /* now that the requets is going, we loop toll we have a result */ + /* now that the request is going, we loop till we have a result */ frame->data = (void *)state; frame->prepare = prepare_schedule; frame->check = slf_check_aio_req; @@ -2726,6 +3302,135 @@ /*****************************************************************************/ +#if CORO_CLONE +# include "clone.c" +#endif + +/*****************************************************************************/ + +static SV * +coro_new (pTHX_ HV *stash, SV **argv, int argc, int is_coro) +{ + SV *coro_sv; + struct coro *coro; + MAGIC *mg; + HV *hv; + SV *cb; + int i; + + if (argc > 0) + { + cb = s_get_cv_croak (argv [0]); + + if (!is_coro) + { + if (CvISXSUB (cb)) + croak ("Coro::State doesn't support XS functions as coroutine start, caught"); + + if (!CvROOT (cb)) + croak ("Coro::State doesn't support autoloaded or undefined functions as coroutine start, caught"); + } + } + + Newz (0, coro, 1, struct coro); + coro->args = newAV (); + coro->flags = CF_NEW; + + if (coro_first) coro_first->prev = coro; + coro->next = coro_first; + coro_first = coro; + + coro->hv = hv = newHV (); + mg = sv_magicext ((SV *)hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)coro, 0); + mg->mg_flags |= MGf_DUP; + coro_sv = sv_bless (newRV_noinc ((SV *)hv), stash); + + if (argc > 0) + { + av_extend (coro->args, argc + is_coro - 1); + + if (is_coro) + { + av_push (coro->args, SvREFCNT_inc_NN ((SV *)cb)); + cb = (SV *)cv_coro_run; + } + + coro->startcv = (CV *)SvREFCNT_inc_NN ((SV *)cb); + + for (i = 1; i < argc; i++) + av_push (coro->args, newSVsv (argv [i])); + } + + return coro_sv; +} + +#ifndef __cplusplus +ecb_cold XS(boot_Coro__State); +#endif + +#if CORO_JIT + +static void ecb_noinline ecb_cold +pushav_4uv (pTHX_ UV a, UV b, UV c, UV d) +{ + dSP; + AV *av = newAV (); + + av_store (av, 3, newSVuv (d)); + av_store (av, 2, newSVuv (c)); + av_store (av, 1, newSVuv (b)); + av_store (av, 0, newSVuv (a)); + + XPUSHs (sv_2mortal (newRV_noinc ((SV *)av))); + + PUTBACK; +} + +static void ecb_noinline ecb_cold +jit_init (pTHX) +{ + dSP; + SV *load, *save; + char *map_base; + char *load_ptr, *save_ptr; + STRLEN load_len, save_len, map_len; + int count; + + eval_pv ("require 'Coro/jit-" CORO_JIT_TYPE ".pl'", 1); + + PUSHMARK (SP); + #define VARx(name,expr,type) pushav_4uv (aTHX_ (UV)&(expr), sizeof (expr), offsetof (perl_slots, name), sizeof (type)); + #include "state.h" + count = call_pv ("Coro::State::_jit", G_ARRAY); + SPAGAIN; + + save = POPs; save_ptr = SvPVbyte (save, save_len); + load = POPs; load_ptr = SvPVbyte (load, load_len); + + map_len = load_len + save_len + 16; + + map_base = mmap (0, map_len, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + + assert (("Coro: unable to mmap jit code page, cannot continue.", map_base != (char *)MAP_FAILED)); + + load_perl_slots = (load_save_perl_slots_type)map_base; + memcpy (map_base, load_ptr, load_len); + + map_base += (load_len + 15) & ~15; + + save_perl_slots = (load_save_perl_slots_type)map_base; + memcpy (map_base, save_ptr, save_len); + + /* we are good citizens and try to make the page read-only, so the evil evil */ + /* hackers might have it a bit more difficult */ + mprotect (map_base, map_len, PROT_READ | PROT_EXEC); + + PUTBACK; + eval_pv ("undef &Coro::State::_jit", 1); +} + +#endif + MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_ PROTOTYPES: DISABLE @@ -2739,6 +3444,15 @@ #endif BOOT_PAGESIZE; + /* perl defines these to check for existance first, but why it doesn't */ + /* just create them one at init time is not clear to me, except for */ + /* programs trying to delete them, but... */ + /* anyway, we declare this as invalid and make sure they are initialised here */ + DEFSV; + ERRSV; + + cctx_current = cctx_new_empty (); + irsgv = gv_fetchpv ("/" , GV_ADD|GV_NOTQUAL, SVt_PV); stdoutgv = gv_fetchpv ("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO); @@ -2767,12 +3481,10 @@ SV *slf = sv_2mortal (newSViv (PTR2IV (pp_slf))); if (!PL_custom_op_names) PL_custom_op_names = newHV (); - hv_store_ent (PL_custom_op_names, slf, - newSVpv ("coro_slf", 0), 0); + hv_store_ent (PL_custom_op_names, slf, newSVpv ("coro_slf", 0), 0); if (!PL_custom_op_descs) PL_custom_op_descs = newHV (); - hv_store_ent (PL_custom_op_descs, slf, - newSVpv ("coro schedule like function", 0), 0); + hv_store_ent (PL_custom_op_descs, slf, newSVpv ("coro schedule like function", 0), 0); } coroapi.ver = CORO_API_VERSION; @@ -2787,74 +3499,23 @@ coroapi.prepare_cede = prepare_cede; coroapi.prepare_cede_notself = prepare_cede_notself; - { - SV **svp = hv_fetch (PL_modglobal, "Time::NVtime", 12, 0); - - if (!svp) croak ("Time::HiRes is required"); - if (!SvIOK (*svp)) croak ("Time::NVtime isn't a function pointer"); - - nvtime = INT2PTR (double (*)(), SvIV (*svp)); - } + time_init (aTHX); - assert (("PRIO_NORMAL must be 0", !PRIO_NORMAL)); + assert (("PRIO_NORMAL must be 0", !CORO_PRIO_NORMAL)); +#if CORO_JIT + PUTBACK; + jit_init (aTHX); + SPAGAIN; +#endif } SV * -new (char *klass, ...) +new (SV *klass, ...) ALIAS: Coro::new = 1 CODE: -{ - struct coro *coro; - MAGIC *mg; - HV *hv; - CV *cb; - int i; - - if (items > 1) - { - cb = coro_sv_2cv (aTHX_ ST (1)); - - if (!ix) - { - if (CvISXSUB (cb)) - croak ("Coro::State doesn't support XS functions as coroutine start, caught"); - - if (!CvROOT (cb)) - croak ("Coro::State doesn't support autoloaded or undefined functions as coroutine start, caught"); - } - } - - Newz (0, coro, 1, struct coro); - coro->args = newAV (); - coro->flags = CF_NEW; - - if (coro_first) coro_first->prev = coro; - coro->next = coro_first; - coro_first = coro; - - coro->hv = hv = newHV (); - mg = sv_magicext ((SV *)hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)coro, 0); - mg->mg_flags |= MGf_DUP; - RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1)); - - if (items > 1) - { - av_extend (coro->args, items - 1 + ix - 1); - - if (ix) - { - av_push (coro->args, SvREFCNT_inc_NN ((SV *)cb)); - cb = cv_coro_run; - } - - coro->startcv = (CV *)SvREFCNT_inc_NN ((SV *)cb); - - for (i = 2; i < items; i++) - av_push (coro->args, newSVsv (ST (i))); - } -} - OUTPUT: + RETVAL = coro_new (aTHX_ ix ? coro_stash : coro_state_stash, &ST (1), items - 1, ix); + OUTPUT: RETVAL void @@ -2863,19 +3524,31 @@ CODE: CORO_EXECUTE_SLF_XS (slf_init_transfer); -bool -_destroy (SV *coro_sv) - CODE: - RETVAL = coro_state_destroy (aTHX_ SvSTATE (coro_sv)); - OUTPUT: - RETVAL - void _exit (int code) PROTOTYPE: $ CODE: _exit (code); +SV * +clone (Coro::State coro) + CODE: +{ +#if CORO_CLONE + struct coro *ncoro = coro_clone (aTHX_ coro); + MAGIC *mg; + /* TODO: too much duplication */ + ncoro->hv = newHV (); + mg = sv_magicext ((SV *)ncoro->hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)ncoro, 0); + mg->mg_flags |= MGf_DUP; + RETVAL = sv_bless (newRV_noinc ((SV *)ncoro->hv), SvSTASH (coro->hv)); +#else + croak ("Coro::State->clone has not been configured into this installation of Coro, realised"); +#endif +} + OUTPUT: + RETVAL + int cctx_stacksize (int new_stacksize = 0) PROTOTYPE: ;$ @@ -2934,39 +3607,45 @@ { if (coro->mainstack && ((coro->flags & CF_RUNNING) || coro->slot)) { - struct coro temp; + struct coro *current = SvSTATE_current; + struct CoroSLF slf_save; - if (!(coro->flags & CF_RUNNING)) + if (current != coro) { PUTBACK; - save_perl (aTHX_ &temp); + save_perl (aTHX_ current); load_perl (aTHX_ coro); + /* the coro is most likely in an active SLF call. + * while not strictly required (the code we execute is + * not allowed to call any SLF functions), it's cleaner + * to reinitialise the slf_frame and restore it later. + * This might one day allow us to actually do SLF calls + * from code executed here. + */ + slf_save = slf_frame; + slf_frame.prepare = 0; + SPAGAIN; } - { - dSP; - ENTER; - SAVETMPS; - PUTBACK; - PUSHSTACK; - PUSHMARK (SP); + PUSHSTACK; + + PUSHMARK (SP); + PUTBACK; - if (ix) - eval_sv (coderef, 0); - else - call_sv (coderef, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD); + if (ix) + eval_sv (coderef, 0); + else + call_sv (coderef, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD); - POPSTACK; - SPAGAIN; - FREETMPS; - LEAVE; - PUTBACK; - } + POPSTACK; + SPAGAIN; - if (!(coro->flags & CF_RUNNING)) + if (current != coro) { + PUTBACK; + slf_frame = slf_save; save_perl (aTHX_ coro); - load_perl (aTHX_ &temp); + load_perl (aTHX_ current); SPAGAIN; } } @@ -2979,21 +3658,27 @@ is_ready = CF_READY is_running = CF_RUNNING is_new = CF_NEW - is_destroyed = CF_DESTROYED + is_destroyed = CF_ZOMBIE + is_zombie = CF_ZOMBIE + is_suspended = CF_SUSPENDED CODE: RETVAL = boolSV (coro->flags & ix); OUTPUT: RETVAL void -throw (Coro::State self, SV *throw = &PL_sv_undef) +throw (SV *self, SV *exception = &PL_sv_undef) PROTOTYPE: $;$ CODE: { + struct coro *coro = SvSTATE (self); struct coro *current = SvSTATE_current; - SV **throwp = self == current ? &CORO_THROW : &self->except; - SvREFCNT_dec (*throwp); - *throwp = SvOK (throw) ? newSVsv (throw) : 0; + SV **exceptionp = coro == current ? &CORO_THROW : &coro->except; + SvREFCNT_dec (*exceptionp); + SvGETMAGIC (exception); + *exceptionp = SvOK (exception) ? newSVsv (exception) : 0; + + api_ready (aTHX_ self); } void @@ -3005,7 +3690,8 @@ has_cctx (Coro::State coro) PROTOTYPE: $ CODE: - RETVAL = boolSV (!!coro->cctx); + /* maybe manage the running flag differently */ + RETVAL = boolSV (!!coro->cctx || (coro->flags & CF_RUNNING)); OUTPUT: RETVAL @@ -3035,7 +3721,7 @@ force_cctx () PROTOTYPE: CODE: - SvSTATE_current->cctx->idle_sp = 0; + cctx_current->idle_sp = 0; void swap_defsv (Coro::State self) @@ -3053,38 +3739,94 @@ SV *tmp = *src; *src = *dst; *dst = tmp; } +void +cancel (Coro::State self) + CODE: + coro_state_destroy (aTHX_ self); + +SV * +enable_times (int enabled = enable_times) + CODE: +{ + RETVAL = boolSV (enable_times); + + if (enabled != enable_times) + { + enable_times = enabled; + + coro_times_update (); + (enabled ? coro_times_sub : coro_times_add)(SvSTATE (coro_current)); + } +} + OUTPUT: + RETVAL + +void +times (Coro::State self) + PPCODE: +{ + struct coro *current = SvSTATE (coro_current); + + if (ecb_expect_false (current == self)) + { + coro_times_update (); + coro_times_add (SvSTATE (coro_current)); + } + + EXTEND (SP, 2); + PUSHs (sv_2mortal (newSVnv (self->t_real [0] + self->t_real [1] * 1e-9))); + PUSHs (sv_2mortal (newSVnv (self->t_cpu [0] + self->t_cpu [1] * 1e-9))); + + if (ecb_expect_false (current == self)) + coro_times_sub (SvSTATE (coro_current)); +} + +void +swap_sv (Coro::State coro, SV *sv, SV *swapsv) + CODE: +{ + struct coro *current = SvSTATE_current; + + if (current == coro) + SWAP_SVS (current); + + if (!coro->swap_sv) + coro->swap_sv = newAV (); + + av_push (coro->swap_sv, SvREFCNT_inc_NN (SvRV (sv ))); + av_push (coro->swap_sv, SvREFCNT_inc_NN (SvRV (swapsv))); + + if (current == coro) + SWAP_SVS (current); +} + MODULE = Coro::State PACKAGE = Coro BOOT: { - int i; - sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE); sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE); - cv_coro_run = get_cv ( "Coro::_terminate", GV_ADD); - cv_coro_terminate = get_cv ( "Coro::terminate" , GV_ADD); + cv_coro_run = get_cv ( "Coro::_coro_run" , GV_ADD); coro_current = coro_get_sv (aTHX_ "Coro::current" , FALSE); SvREADONLY_on (coro_current); av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE); av_destroy = coro_get_av (aTHX_ "Coro::destroy" , TRUE); sv_manager = coro_get_sv (aTHX_ "Coro::manager" , TRUE); + sv_idle = coro_get_sv (aTHX_ "Coro::idle" , TRUE); sv_async_pool_idle = newSVpv ("[async pool idle]", 0); SvREADONLY_on (sv_async_pool_idle); sv_Coro = newSVpv ("Coro", 0); SvREADONLY_on (sv_Coro); cv_pool_handler = get_cv ("Coro::pool_handler", GV_ADD); SvREADONLY_on (cv_pool_handler); - cv_coro_state_new = get_cv ("Coro::State::new", 0); SvREADONLY_on (cv_coro_state_new); - + CvNODEBUG_on (get_cv ("Coro::_pool_handler", 0)); /* work around a debugger bug */ + coro_stash = gv_stashpv ("Coro", TRUE); - newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (PRIO_MAX)); - newCONSTSUB (coro_stash, "PRIO_HIGH", newSViv (PRIO_HIGH)); - newCONSTSUB (coro_stash, "PRIO_NORMAL", newSViv (PRIO_NORMAL)); - newCONSTSUB (coro_stash, "PRIO_LOW", newSViv (PRIO_LOW)); - newCONSTSUB (coro_stash, "PRIO_IDLE", newSViv (PRIO_IDLE)); - newCONSTSUB (coro_stash, "PRIO_MIN", newSViv (PRIO_MIN)); - - for (i = PRIO_MAX - PRIO_MIN + 1; i--; ) - coro_ready[i] = newAV (); + newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (CORO_PRIO_MAX)); + newCONSTSUB (coro_stash, "PRIO_HIGH", newSViv (CORO_PRIO_HIGH)); + newCONSTSUB (coro_stash, "PRIO_NORMAL", newSViv (CORO_PRIO_NORMAL)); + newCONSTSUB (coro_stash, "PRIO_LOW", newSViv (CORO_PRIO_LOW)); + newCONSTSUB (coro_stash, "PRIO_IDLE", newSViv (CORO_PRIO_IDLE)); + newCONSTSUB (coro_stash, "PRIO_MIN", newSViv (CORO_PRIO_MIN)); { SV *sv = coro_get_sv (aTHX_ "Coro::API", TRUE); @@ -3104,12 +3846,46 @@ } } +SV * +async (...) + PROTOTYPE: &@ + CODE: + RETVAL = coro_new (aTHX_ coro_stash, &ST (0), items, 1); + api_ready (aTHX_ RETVAL); + OUTPUT: + RETVAL + +void +_destroy (Coro::State coro) + CODE: + /* used by the manager thread */ + coro_state_destroy (aTHX_ coro); + +void +on_destroy (Coro::State coro, SV *cb) + CODE: + coro_push_on_destroy (aTHX_ coro, newSVsv (cb)); + +void +join (...) + CODE: + CORO_EXECUTE_SLF_XS (slf_init_join); + void terminate (...) CODE: CORO_EXECUTE_SLF_XS (slf_init_terminate); void +cancel (...) + CODE: + CORO_EXECUTE_SLF_XS (slf_init_cancel); + +int +safe_cancel (Coro::State self, ...) + C_ARGS: aTHX_ self, &ST (1), items - 1 + +void schedule (...) CODE: CORO_EXECUTE_SLF_XS (slf_init_schedule); @@ -3135,12 +3911,6 @@ CORO_EXECUTE_SLF_XS (slf_init_cede_notself); void -_cancel (Coro::State self) - CODE: - coro_state_destroy (aTHX_ self); - coro_call_on_destroy (aTHX_ self); - -void _set_current (SV *current) PROTOTYPE: $ CODE: @@ -3152,7 +3922,17 @@ PROTOTYPE: $ CODE: SvREFCNT_dec (coro_readyhook); - coro_readyhook = SvOK (hook) ? newSVsv (hook) : 0; + SvGETMAGIC (hook); + if (SvOK (hook)) + { + coro_readyhook = newSVsv (hook); + CORO_READYHOOK = invoke_sv_ready_hook_helper; + } + else + { + coro_readyhook = 0; + CORO_READYHOOK = 0; + } int prio (Coro::State coro, int newprio = 0) @@ -3168,8 +3948,8 @@ if (ix) newprio = coro->prio - newprio; - if (newprio < PRIO_MIN) newprio = PRIO_MIN; - if (newprio > PRIO_MAX) newprio = PRIO_MAX; + if (newprio < CORO_PRIO_MIN) newprio = CORO_PRIO_MIN; + if (newprio > CORO_PRIO_MAX) newprio = CORO_PRIO_MAX; coro->prio = newprio; } @@ -3194,6 +3974,18 @@ RETVAL void +suspend (Coro::State self) + PROTOTYPE: $ + CODE: + self->flags |= CF_SUSPENDED; + +void +resume (Coro::State self) + PROTOTYPE: $ + CODE: + self->flags &= ~CF_SUSPENDED; + +void _pool_handler (...) CODE: CORO_EXECUTE_SLF_XS (slf_init_pool_handler); @@ -3214,15 +4006,9 @@ if ((SV *)hv == &PL_sv_undef) { - PUSHMARK (SP); - EXTEND (SP, 2); - PUSHs (sv_Coro); - PUSHs ((SV *)cv_pool_handler); - PUTBACK; - call_sv ((SV *)cv_coro_state_new, G_SCALAR); - SPAGAIN; - - hv = (HV *)SvREFCNT_inc_NN (SvRV (POPs)); + SV *sv = coro_new (aTHX_ coro_stash, (SV **)&cv_pool_handler, 1, 1); + hv = (HV *)SvREFCNT_inc_NN (SvRV (sv)); + SvREFCNT_dec (sv); } { @@ -3256,6 +4042,31 @@ PPCODE: CORO_EXECUTE_SLF_XS (slf_init_rouse_wait); +void +on_enter (SV *block) + ALIAS: + on_leave = 1 + PROTOTYPE: & + CODE: +{ + struct coro *coro = SvSTATE_current; + AV **avp = ix ? &coro->on_leave : &coro->on_enter; + + block = s_get_cv_croak (block); + + if (!*avp) + *avp = newAV (); + + av_push (*avp, SvREFCNT_inc (block)); + + if (!ix) + on_enterleave_call (aTHX_ block); + + LEAVE; /* pp_entersub unfortunately forces an ENTER/LEAVE around XS calls */ + SAVEDESTRUCTOR_X (ix ? coro_pop_on_leave : coro_pop_on_enter, (void *)coro); + ENTER; /* pp_entersub unfortunately forces an ENTER/LEAVE around XS calls */ +} + MODULE = Coro::State PACKAGE = PerlIO::cede @@ -3268,14 +4079,26 @@ SV * new (SV *klass, SV *count = 0) CODE: +{ + int semcnt = 1; + + if (count) + { + SvGETMAGIC (count); + + if (SvOK (count)) + semcnt = SvIV (count); + } + RETVAL = sv_bless ( - coro_waitarray_new (aTHX_ count && SvOK (count) ? SvIV (count) : 1), + coro_waitarray_new (aTHX_ semcnt), GvSTASH (CvGV (cv)) ); +} OUTPUT: RETVAL -# helper for Coro::Channel +# helper for Coro::Channel and others SV * _alloc (int count) CODE: @@ -3343,6 +4166,22 @@ } } +MODULE = Coro::State PACKAGE = Coro::SemaphoreSet + +void +_may_delete (SV *sem, int count, unsigned int extra_refs) + PPCODE: +{ + AV *av = (AV *)SvRV (sem); + + if (SvREFCNT ((SV *)av) == 1 + extra_refs + && AvFILLp (av) == 0 /* no waiters, just count */ + && SvIV (AvARRAY (av)[0]) == count) + XSRETURN_YES; + + XSRETURN_NO; +} + MODULE = Coro::State PACKAGE = Coro::Signal SV * @@ -3423,10 +4262,31 @@ _register (char *target, char *proto, SV *req) CODE: { - CV *req_cv = coro_sv_2cv (aTHX_ req); + SV *req_cv = s_get_cv_croak (req); /* newXSproto doesn't return the CV on 5.8 */ CV *slf_cv = newXS (target, coro_aio_req_xs, __FILE__); sv_setpv ((SV *)slf_cv, proto); sv_magicext ((SV *)slf_cv, (SV *)req_cv, CORO_MAGIC_type_aio, 0, 0, 0); } +MODULE = Coro::State PACKAGE = Coro::Select + +void +patch_pp_sselect () + CODE: + if (!coro_old_pp_sselect) + { + coro_select_select = (SV *)get_cv ("Coro::Select::select", 0); + coro_old_pp_sselect = PL_ppaddr [OP_SSELECT]; + PL_ppaddr [OP_SSELECT] = coro_pp_sselect; + } + +void +unpatch_pp_sselect () + CODE: + if (coro_old_pp_sselect) + { + PL_ppaddr [OP_SSELECT] = coro_old_pp_sselect; + coro_old_pp_sselect = 0; + } +