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.362 by root, Wed Jul 1 07:58:45 2009 UTC vs.
Revision 1.414 by root, Wed Jun 29 16:08:31 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"
17#include "ecb.h"
12 18
19#include <stddef.h>
13#include <stdio.h> 20#include <stdio.h>
14#include <errno.h> 21#include <errno.h>
15#include <assert.h> 22#include <assert.h>
16 23
17#ifdef WIN32 24#ifndef SVs_PADSTALE
25# define SVs_PADSTALE 0
26#endif
27
28#if defined(_WIN32)
29# undef HAS_GETTIMEOFDAY
18# undef setjmp 30# undef setjmp
19# undef longjmp 31# undef longjmp
20# undef _exit 32# undef _exit
21# define setjmp _setjmp /* deep magic */ 33# define setjmp _setjmp /* deep magic */
22#else 34#else
23# include <inttypes.h> /* most portable stdint.h */ 35# include <inttypes.h> /* most portable stdint.h */
24#endif 36#endif
25 37
26#ifdef HAVE_MMAP 38#if HAVE_MMAP
27# include <unistd.h> 39# include <unistd.h>
28# include <sys/mman.h> 40# include <sys/mman.h>
29# ifndef MAP_ANONYMOUS 41# ifndef MAP_ANONYMOUS
30# ifdef MAP_ANON 42# ifdef MAP_ANON
31# define MAP_ANONYMOUS MAP_ANON 43# define MAP_ANONYMOUS MAP_ANON
51#endif 63#endif
52 64
53/* the maximum number of idle cctx that will be pooled */ 65/* the maximum number of idle cctx that will be pooled */
54static int cctx_max_idle = 4; 66static int cctx_max_idle = 4;
55 67
56#define PERL_VERSION_ATLEAST(a,b,c) \ 68#if defined(DEBUGGING) && PERL_VERSION_ATLEAST(5,12,0)
57 (PERL_REVISION > (a) \ 69# define HAS_SCOPESTACK_NAME 1
58 || (PERL_REVISION == (a) \
59 && (PERL_VERSION > (b) \
60 || (PERL_VERSION == (b) && PERL_SUBVERSION >= (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#ifndef CvISXSUB
104# define CvISXSUB(cv) (CvXSUB (cv) ? TRUE : FALSE)
105#endif
106#ifndef Newx
107# define Newx(ptr,nitems,type) New (0,ptr,nitems,type)
108#endif
109
110/* 5.8.7 */
111#ifndef SvRV_set
112# define SvRV_set(s,v) SvRV(s) = (v)
113#endif 70#endif
114 71
115#if !__i386 && !__x86_64 && !__powerpc && !__m68k && !__alpha && !__mips && !__sparc64 72#if !__i386 && !__x86_64 && !__powerpc && !__m68k && !__alpha && !__mips && !__sparc64
116# undef CORO_STACKGUARD 73# undef CORO_STACKGUARD
117#endif 74#endif
135# define STACKLEVEL ((void *)&stacklevel) 92# define STACKLEVEL ((void *)&stacklevel)
136#endif 93#endif
137 94
138#define IN_DESTRUCT PL_dirty 95#define IN_DESTRUCT PL_dirty
139 96
140#if __GNUC__ >= 3
141# define attribute(x) __attribute__(x)
142# define expect(expr,value) __builtin_expect ((expr), (value))
143# define INLINE static inline
144#else
145# define attribute(x)
146# define expect(expr,value) (expr)
147# define INLINE static
148#endif
149
150#define expect_false(expr) expect ((expr) != 0, 0)
151#define expect_true(expr) expect ((expr) != 0, 1)
152
153#define NOINLINE attribute ((noinline))
154
155#include "CoroAPI.h" 97#include "CoroAPI.h"
156#define GCoroAPI (&coroapi) /* very sneaky */ 98#define GCoroAPI (&coroapi) /* very sneaky */
157 99
158#ifdef USE_ITHREADS 100#ifdef USE_ITHREADS
159# if CORO_PTHREAD 101# if CORO_PTHREAD
160static void *coro_thx; 102static void *coro_thx;
161# endif 103# endif
162#endif 104#endif
105
106/* used in state.h */
107#define VAR(name,type) VARx(name, PL_ ## name, type)
163 108
164#ifdef __linux 109#ifdef __linux
165# include <time.h> /* for timespec */ 110# include <time.h> /* for timespec */
166# include <syscall.h> /* for SYS_* */ 111# include <syscall.h> /* for SYS_* */
167# ifdef SYS_clock_gettime 112# ifdef SYS_clock_gettime
175static void (*u2time)(pTHX_ UV ret[2]); 120static void (*u2time)(pTHX_ UV ret[2]);
176 121
177/* we hijack an hopefully unused CV flag for our purposes */ 122/* we hijack an hopefully unused CV flag for our purposes */
178#define CVf_SLF 0x4000 123#define CVf_SLF 0x4000
179static OP *pp_slf (pTHX); 124static OP *pp_slf (pTHX);
125static void slf_destroy (pTHX_ struct coro *coro);
180 126
181static U32 cctx_gen; 127static U32 cctx_gen;
182static size_t cctx_stacksize = CORO_STACKSIZE; 128static size_t cctx_stacksize = CORO_STACKSIZE;
183static struct CoroAPI coroapi; 129static struct CoroAPI coroapi;
184static AV *main_mainstack; /* used to differentiate between $main and others */ 130static AV *main_mainstack; /* used to differentiate between $main and others */
201static SV *sv_pool_size; 147static SV *sv_pool_size;
202static SV *sv_async_pool_idle; /* description string */ 148static SV *sv_async_pool_idle; /* description string */
203static AV *av_async_pool; /* idle pool */ 149static AV *av_async_pool; /* idle pool */
204static SV *sv_Coro; /* class string */ 150static SV *sv_Coro; /* class string */
205static CV *cv_pool_handler; 151static CV *cv_pool_handler;
206static CV *cv_coro_state_new;
207 152
208/* Coro::AnyEvent */ 153/* Coro::AnyEvent */
209static SV *sv_activity; 154static SV *sv_activity;
210 155
211/* enable processtime/realtime profiling */ 156/* enable processtime/realtime profiling */
215static char times_valid; 160static char times_valid;
216 161
217static struct coro_cctx *cctx_first; 162static struct coro_cctx *cctx_first;
218static int cctx_count, cctx_idle; 163static int cctx_count, cctx_idle;
219 164
220enum { 165enum
166{
221 CC_MAPPED = 0x01, 167 CC_MAPPED = 0x01,
222 CC_NOREUSE = 0x02, /* throw this away after tracing */ 168 CC_NOREUSE = 0x02, /* throw this away after tracing */
223 CC_TRACE = 0x04, 169 CC_TRACE = 0x04,
224 CC_TRACE_SUB = 0x08, /* trace sub calls */ 170 CC_TRACE_SUB = 0x08, /* trace sub calls */
225 CC_TRACE_LINE = 0x10, /* trace each statement */ 171 CC_TRACE_LINE = 0x10, /* trace each statement */
246 int valgrind_id; 192 int valgrind_id;
247#endif 193#endif
248 unsigned char flags; 194 unsigned char flags;
249} coro_cctx; 195} coro_cctx;
250 196
251coro_cctx *cctx_current; /* the currently running cctx */ 197static coro_cctx *cctx_current; /* the currently running cctx */
252 198
253/*****************************************************************************/ 199/*****************************************************************************/
254 200
201static MGVTBL coro_state_vtbl;
202
255enum { 203enum
204{
256 CF_RUNNING = 0x0001, /* coroutine is running */ 205 CF_RUNNING = 0x0001, /* coroutine is running */
257 CF_READY = 0x0002, /* coroutine is ready */ 206 CF_READY = 0x0002, /* coroutine is ready */
258 CF_NEW = 0x0004, /* has never been switched to */ 207 CF_NEW = 0x0004, /* has never been switched to */
259 CF_DESTROYED = 0x0008, /* coroutine data has been freed */ 208 CF_ZOMBIE = 0x0008, /* coroutine data has been freed */
260 CF_SUSPENDED = 0x0010, /* coroutine can't be scheduled */ 209 CF_SUSPENDED = 0x0010, /* coroutine can't be scheduled */
210 CF_NOCANCEL = 0x0020, /* cannot cancel, set slf_frame.data to 1 (hackish) */
261}; 211};
262 212
263/* the structure where most of the perl state is stored, overlaid on the cxstack */ 213/* the structure where most of the perl state is stored, overlaid on the cxstack */
264typedef struct 214typedef struct
265{ 215{
266 SV *defsv;
267 AV *defav;
268 SV *errsv;
269 SV *irsgv;
270 HV *hinthv;
271#define VAR(name,type) type name; 216#define VARx(name,expr,type) type name;
272# include "state.h" 217# include "state.h"
273#undef VAR 218#undef VARx
274} perl_slots; 219} perl_slots;
275 220
221/* how many context stack entries do we need for perl_slots */
276#define SLOT_COUNT ((sizeof (perl_slots) + sizeof (PERL_CONTEXT) - 1) / sizeof (PERL_CONTEXT)) 222#define SLOT_COUNT ((sizeof (perl_slots) + sizeof (PERL_CONTEXT) - 1) / sizeof (PERL_CONTEXT))
277 223
278/* this is a structure representing a perl-level coroutine */ 224/* this is a structure representing a perl-level coroutine */
279struct coro { 225struct coro
226{
280 /* the C coroutine allocated to this perl coroutine, if any */ 227 /* the C coroutine allocated to this perl coroutine, if any */
281 coro_cctx *cctx; 228 coro_cctx *cctx;
282 229
283 /* ready queue */ 230 /* ready queue */
284 struct coro *next_ready; 231 struct coro *next_ready;
286 /* state data */ 233 /* state data */
287 struct CoroSLF slf_frame; /* saved slf frame */ 234 struct CoroSLF slf_frame; /* saved slf frame */
288 AV *mainstack; 235 AV *mainstack;
289 perl_slots *slot; /* basically the saved sp */ 236 perl_slots *slot; /* basically the saved sp */
290 237
291 CV *startcv; /* the CV to execute */ 238 CV *startcv; /* the CV to execute */
292 AV *args; /* data associated with this coroutine (initial args) */ 239 AV *args; /* data associated with this coroutine (initial args) */
293 int refcnt; /* coroutines are refcounted, yes */
294 int flags; /* CF_ flags */ 240 int flags; /* CF_ flags */
295 HV *hv; /* the perl hash associated with this coro, if any */ 241 HV *hv; /* the perl hash associated with this coro, if any */
296 void (*on_destroy)(pTHX_ struct coro *coro);
297 242
298 /* statistics */ 243 /* statistics */
299 int usecount; /* number of transfers to this coro */ 244 int usecount; /* number of transfers to this coro */
300 245
301 /* coro process data */ 246 /* coro process data */
302 int prio; 247 int prio;
303 SV *except; /* exception to be thrown */ 248 SV *except; /* exception to be thrown */
304 SV *rouse_cb; 249 SV *rouse_cb; /* last rouse callback */
250 AV *on_destroy; /* callbacks or coros to notify on destroy */
251 AV *status; /* the exit status list */
305 252
306 /* async_pool */ 253 /* async_pool */
307 SV *saved_deffh; 254 SV *saved_deffh;
308 SV *invoke_cb; 255 SV *invoke_cb;
309 AV *invoke_av; 256 AV *invoke_av;
310 257
311 /* on_enter/on_leave */ 258 /* on_enter/on_leave */
312 AV *on_enter; 259 AV *on_enter;
313 AV *on_leave; 260 AV *on_leave;
314 261
262 /* swap_sv */
263 AV *swap_sv;
264
315 /* times */ 265 /* times */
316 coro_ts t_cpu, t_real; 266 coro_ts t_cpu, t_real;
317 267
318 /* linked list */ 268 /* linked list */
319 struct coro *next, *prev; 269 struct coro *next, *prev;
322typedef struct coro *Coro__State; 272typedef struct coro *Coro__State;
323typedef struct coro *Coro__State_or_hashref; 273typedef struct coro *Coro__State_or_hashref;
324 274
325/* the following variables are effectively part of the perl context */ 275/* the following variables are effectively part of the perl context */
326/* and get copied between struct coro and these variables */ 276/* and get copied between struct coro and these variables */
327/* the mainr easonw e don't support windows process emulation */ 277/* the main reason we don't support windows process emulation */
328static struct CoroSLF slf_frame; /* the current slf frame */ 278static struct CoroSLF slf_frame; /* the current slf frame */
329 279
330/** Coro ********************************************************************/ 280/** Coro ********************************************************************/
331 281
332#define CORO_PRIO_MAX 3 282#define CORO_PRIO_MAX 3
338 288
339/* for Coro.pm */ 289/* for Coro.pm */
340static SV *coro_current; 290static SV *coro_current;
341static SV *coro_readyhook; 291static SV *coro_readyhook;
342static struct coro *coro_ready [CORO_PRIO_MAX - CORO_PRIO_MIN + 1][2]; /* head|tail */ 292static struct coro *coro_ready [CORO_PRIO_MAX - CORO_PRIO_MIN + 1][2]; /* head|tail */
343static CV *cv_coro_run, *cv_coro_terminate; 293static CV *cv_coro_run;
344static struct coro *coro_first; 294static struct coro *coro_first;
345#define coro_nready coroapi.nready 295#define coro_nready coroapi.nready
346 296
297/** JIT *********************************************************************/
298
299#if CORO_JIT
300 /* APPLE doesn't have HAVE_MMAP though */
301 #define CORO_JIT_UNIXY (__linux || __FreeBSD__ || __OpenBSD__ || __NetBSD__ || __solaris || __APPLE__)
302 #ifndef CORO_JIT_TYPE
303 #if __x86_64 && CORO_JIT_UNIXY
304 #define CORO_JIT_TYPE "amd64-unix"
305 #elif __i386 && CORO_JIT_UNIXY
306 #define CORO_JIT_TYPE "x86-unix"
307 #endif
308 #endif
309#endif
310
311#if !defined(CORO_JIT_TYPE) || !HAVE_MMAP
312 #undef CORO_JIT
313#endif
314
315#if CORO_JIT
316 typedef void (*load_save_perl_slots_type)(perl_slots *);
317 static load_save_perl_slots_type load_perl_slots, save_perl_slots;
318#endif
319
320/** Coro::Select ************************************************************/
321
322static OP *(*coro_old_pp_sselect) (pTHX);
323static SV *coro_select_select;
324
325/* horrible hack, but if it works... */
326static OP *
327coro_pp_sselect (pTHX)
328{
329 dSP;
330 PUSHMARK (SP - 4); /* fake argument list */
331 XPUSHs (coro_select_select);
332 PUTBACK;
333
334 /* entersub is an UNOP, select a LISTOP... keep your fingers crossed */
335 PL_op->op_flags |= OPf_STACKED;
336 PL_op->op_private = 0;
337 return PL_ppaddr [OP_ENTERSUB](aTHX);
338}
339
340/** time stuff **************************************************************/
341
342#ifdef HAS_GETTIMEOFDAY
343
344ecb_inline void
345coro_u2time (pTHX_ UV ret[2])
346{
347 struct timeval tv;
348 gettimeofday (&tv, 0);
349
350 ret [0] = tv.tv_sec;
351 ret [1] = tv.tv_usec;
352}
353
354ecb_inline double
355coro_nvtime (void)
356{
357 struct timeval tv;
358 gettimeofday (&tv, 0);
359
360 return tv.tv_sec + tv.tv_usec * 1e-6;
361}
362
363ecb_inline void
364time_init (pTHX)
365{
366 nvtime = coro_nvtime;
367 u2time = coro_u2time;
368}
369
370#else
371
372ecb_inline void
373time_init (pTHX)
374{
375 SV **svp;
376
377 require_pv ("Time/HiRes.pm");
378
379 svp = hv_fetch (PL_modglobal, "Time::NVtime", 12, 0);
380
381 if (!svp) croak ("Time::HiRes is required, but missing. Caught");
382 if (!SvIOK (*svp)) croak ("Time::NVtime isn't a function pointer. Caught");
383
384 nvtime = INT2PTR (double (*)(), SvIV (*svp));
385
386 svp = hv_fetch (PL_modglobal, "Time::U2time", 12, 0);
387 u2time = INT2PTR (void (*)(pTHX_ UV ret[2]), SvIV (*svp));
388}
389
390#endif
391
347/** lowlevel stuff **********************************************************/ 392/** lowlevel stuff **********************************************************/
348 393
349static SV * 394static SV * ecb_noinline
350coro_get_sv (pTHX_ const char *name, int create) 395coro_get_sv (pTHX_ const char *name, int create)
351{ 396{
352#if PERL_VERSION_ATLEAST (5,10,0) 397#if PERL_VERSION_ATLEAST (5,10,0)
353 /* silence stupid and wrong 5.10 warning that I am unable to switch off */ 398 /* silence stupid and wrong 5.10 warning that I am unable to switch off */
354 get_sv (name, create); 399 get_sv (name, create);
355#endif 400#endif
356 return get_sv (name, create); 401 return get_sv (name, create);
357} 402}
358 403
359static AV * 404static AV * ecb_noinline
360coro_get_av (pTHX_ const char *name, int create) 405coro_get_av (pTHX_ const char *name, int create)
361{ 406{
362#if PERL_VERSION_ATLEAST (5,10,0) 407#if PERL_VERSION_ATLEAST (5,10,0)
363 /* silence stupid and wrong 5.10 warning that I am unable to switch off */ 408 /* silence stupid and wrong 5.10 warning that I am unable to switch off */
364 get_av (name, create); 409 get_av (name, create);
365#endif 410#endif
366 return get_av (name, create); 411 return get_av (name, create);
367} 412}
368 413
369static HV * 414static HV * ecb_noinline
370coro_get_hv (pTHX_ const char *name, int create) 415coro_get_hv (pTHX_ const char *name, int create)
371{ 416{
372#if PERL_VERSION_ATLEAST (5,10,0) 417#if PERL_VERSION_ATLEAST (5,10,0)
373 /* silence stupid and wrong 5.10 warning that I am unable to switch off */ 418 /* silence stupid and wrong 5.10 warning that I am unable to switch off */
374 get_hv (name, create); 419 get_hv (name, create);
375#endif 420#endif
376 return get_hv (name, create); 421 return get_hv (name, create);
377} 422}
378 423
379/* may croak */ 424ecb_inline void
380INLINE CV *
381coro_sv_2cv (pTHX_ SV *sv)
382{
383 HV *st;
384 GV *gvp;
385 CV *cv = sv_2cv (sv, &st, &gvp, 0);
386
387 if (!cv)
388 croak ("code reference expected");
389
390 return cv;
391}
392
393INLINE void
394coro_times_update () 425coro_times_update (void)
395{ 426{
396#ifdef coro_clock_gettime 427#ifdef coro_clock_gettime
397 struct timespec ts; 428 struct timespec ts;
398 429
399 ts.tv_sec = ts.tv_nsec = 0; 430 ts.tv_sec = ts.tv_nsec = 0;
411 time_real [0] = tv [0]; 442 time_real [0] = tv [0];
412 time_real [1] = tv [1] * 1000; 443 time_real [1] = tv [1] * 1000;
413#endif 444#endif
414} 445}
415 446
416INLINE void 447ecb_inline void
417coro_times_add (struct coro *c) 448coro_times_add (struct coro *c)
418{ 449{
419 c->t_real [1] += time_real [1]; 450 c->t_real [1] += time_real [1];
420 if (c->t_real [1] > 1000000000) { c->t_real [1] -= 1000000000; ++c->t_real [0]; } 451 if (c->t_real [1] > 1000000000) { c->t_real [1] -= 1000000000; ++c->t_real [0]; }
421 c->t_real [0] += time_real [0]; 452 c->t_real [0] += time_real [0];
423 c->t_cpu [1] += time_cpu [1]; 454 c->t_cpu [1] += time_cpu [1];
424 if (c->t_cpu [1] > 1000000000) { c->t_cpu [1] -= 1000000000; ++c->t_cpu [0]; } 455 if (c->t_cpu [1] > 1000000000) { c->t_cpu [1] -= 1000000000; ++c->t_cpu [0]; }
425 c->t_cpu [0] += time_cpu [0]; 456 c->t_cpu [0] += time_cpu [0];
426} 457}
427 458
428INLINE void 459ecb_inline void
429coro_times_sub (struct coro *c) 460coro_times_sub (struct coro *c)
430{ 461{
431 if (c->t_real [1] < time_real [1]) { c->t_real [1] += 1000000000; --c->t_real [0]; } 462 if (c->t_real [1] < time_real [1]) { c->t_real [1] += 1000000000; --c->t_real [0]; }
432 c->t_real [1] -= time_real [1]; 463 c->t_real [1] -= time_real [1];
433 c->t_real [0] -= time_real [0]; 464 c->t_real [0] -= time_real [0];
441/* magic glue */ 472/* magic glue */
442 473
443#define CORO_MAGIC_type_cv 26 474#define CORO_MAGIC_type_cv 26
444#define CORO_MAGIC_type_state PERL_MAGIC_ext 475#define CORO_MAGIC_type_state PERL_MAGIC_ext
445 476
446#define CORO_MAGIC_NN(sv, type) \ 477#define CORO_MAGIC_NN(sv, type) \
447 (expect_true (SvMAGIC (sv)->mg_type == type) \ 478 (ecb_expect_true (SvMAGIC (sv)->mg_type == type) \
448 ? SvMAGIC (sv) \ 479 ? SvMAGIC (sv) \
449 : mg_find (sv, type)) 480 : mg_find (sv, type))
450 481
451#define CORO_MAGIC(sv, type) \ 482#define CORO_MAGIC(sv, type) \
452 (expect_true (SvMAGIC (sv)) \ 483 (ecb_expect_true (SvMAGIC (sv)) \
453 ? CORO_MAGIC_NN (sv, type) \ 484 ? CORO_MAGIC_NN (sv, type) \
454 : 0) 485 : 0)
455 486
456#define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv) 487#define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv)
457#define CORO_MAGIC_state(sv) CORO_MAGIC_NN (((SV *)(sv)), CORO_MAGIC_type_state) 488#define CORO_MAGIC_state(sv) CORO_MAGIC_NN (((SV *)(sv)), CORO_MAGIC_type_state)
458 489
459INLINE struct coro * 490ecb_inline MAGIC *
491SvSTATEhv_p (pTHX_ SV *coro)
492{
493 MAGIC *mg;
494
495 if (ecb_expect_true (
496 SvTYPE (coro) == SVt_PVHV
497 && (mg = CORO_MAGIC_state (coro))
498 && mg->mg_virtual == &coro_state_vtbl
499 ))
500 return mg;
501
502 return 0;
503}
504
505ecb_inline struct coro *
460SvSTATE_ (pTHX_ SV *coro) 506SvSTATE_ (pTHX_ SV *coro)
461{ 507{
462 HV *stash;
463 MAGIC *mg; 508 MAGIC *mg;
464 509
465 if (SvROK (coro)) 510 if (SvROK (coro))
466 coro = SvRV (coro); 511 coro = SvRV (coro);
467 512
468 if (expect_false (SvTYPE (coro) != SVt_PVHV)) 513 mg = SvSTATEhv_p (aTHX_ coro);
514 if (!mg)
469 croak ("Coro::State object required"); 515 croak ("Coro::State object required");
470 516
471 stash = SvSTASH (coro);
472 if (expect_false (stash != coro_stash && stash != coro_state_stash))
473 {
474 /* very slow, but rare, check */
475 if (!sv_derived_from (sv_2mortal (newRV_inc (coro)), "Coro::State"))
476 croak ("Coro::State object required");
477 }
478
479 mg = CORO_MAGIC_state (coro);
480 return (struct coro *)mg->mg_ptr; 517 return (struct coro *)mg->mg_ptr;
481} 518}
482 519
483#define SvSTATE(sv) SvSTATE_ (aTHX_ (sv)) 520#define SvSTATE(sv) SvSTATE_ (aTHX_ (sv))
484 521
487#define SvSTATE_current SvSTATE_hv (SvRV (coro_current)) 524#define SvSTATE_current SvSTATE_hv (SvRV (coro_current))
488 525
489/*****************************************************************************/ 526/*****************************************************************************/
490/* padlist management and caching */ 527/* padlist management and caching */
491 528
492static AV * 529ecb_inline AV *
493coro_derive_padlist (pTHX_ CV *cv) 530coro_derive_padlist (pTHX_ CV *cv)
494{ 531{
495 AV *padlist = CvPADLIST (cv); 532 AV *padlist = CvPADLIST (cv);
496 AV *newpadlist, *newpad; 533 AV *newpadlist, *newpad;
497 534
509 av_store (newpadlist, 1, (SV *)newpad); 546 av_store (newpadlist, 1, (SV *)newpad);
510 547
511 return newpadlist; 548 return newpadlist;
512} 549}
513 550
514static void 551ecb_inline void
515free_padlist (pTHX_ AV *padlist) 552free_padlist (pTHX_ AV *padlist)
516{ 553{
517 /* may be during global destruction */ 554 /* may be during global destruction */
518 if (!IN_DESTRUCT) 555 if (!IN_DESTRUCT)
519 { 556 {
562 0, 0, 0, 0, 599 0, 0, 0, 0,
563 coro_cv_free 600 coro_cv_free
564}; 601};
565 602
566/* the next two functions merely cache the padlists */ 603/* the next two functions merely cache the padlists */
567static void 604ecb_inline void
568get_padlist (pTHX_ CV *cv) 605get_padlist (pTHX_ CV *cv)
569{ 606{
570 MAGIC *mg = CORO_MAGIC_cv (cv); 607 MAGIC *mg = CORO_MAGIC_cv (cv);
571 AV *av; 608 AV *av;
572 609
573 if (expect_true (mg && AvFILLp ((av = (AV *)mg->mg_obj)) >= 0)) 610 if (ecb_expect_true (mg && AvFILLp ((av = (AV *)mg->mg_obj)) >= 0))
574 CvPADLIST (cv) = (AV *)AvARRAY (av)[AvFILLp (av)--]; 611 CvPADLIST (cv) = (AV *)AvARRAY (av)[AvFILLp (av)--];
575 else 612 else
576 { 613 {
577#if CORO_PREFER_PERL_FUNCTIONS 614#if CORO_PREFER_PERL_FUNCTIONS
578 /* this is probably cleaner? but also slower! */ 615 /* this is probably cleaner? but also slower! */
585 CvPADLIST (cv) = coro_derive_padlist (aTHX_ cv); 622 CvPADLIST (cv) = coro_derive_padlist (aTHX_ cv);
586#endif 623#endif
587 } 624 }
588} 625}
589 626
590static void 627ecb_inline void
591put_padlist (pTHX_ CV *cv) 628put_padlist (pTHX_ CV *cv)
592{ 629{
593 MAGIC *mg = CORO_MAGIC_cv (cv); 630 MAGIC *mg = CORO_MAGIC_cv (cv);
594 AV *av; 631 AV *av;
595 632
596 if (expect_false (!mg)) 633 if (ecb_expect_false (!mg))
597 mg = sv_magicext ((SV *)cv, (SV *)newAV (), CORO_MAGIC_type_cv, &coro_cv_vtbl, 0, 0); 634 mg = sv_magicext ((SV *)cv, (SV *)newAV (), CORO_MAGIC_type_cv, &coro_cv_vtbl, 0, 0);
598 635
599 av = (AV *)mg->mg_obj; 636 av = (AV *)mg->mg_obj;
600 637
601 if (expect_false (AvFILLp (av) >= AvMAX (av))) 638 if (ecb_expect_false (AvFILLp (av) >= AvMAX (av)))
602 av_extend (av, AvFILLp (av) + 1); 639 av_extend (av, AvFILLp (av) + 1);
603 640
604 AvARRAY (av)[++AvFILLp (av)] = (SV *)CvPADLIST (cv); 641 AvARRAY (av)[++AvFILLp (av)] = (SV *)CvPADLIST (cv);
605} 642}
606 643
607/** load & save, init *******************************************************/ 644/** load & save, init *******************************************************/
645
646/* swap sv heads, at least logically */
647static void
648swap_svs (pTHX_ Coro__State c)
649{
650 int i;
651
652 for (i = 0; i <= AvFILLp (c->swap_sv); )
653 {
654 SV *a = AvARRAY (c->swap_sv)[i++];
655 SV *b = AvARRAY (c->swap_sv)[i++];
656
657 const U32 keep = SVs_PADSTALE | SVs_PADTMP | SVs_PADMY; /* keep these flags */
658 SV tmp;
659
660 /* swap sv_any */
661 SvANY (&tmp) = SvANY (a); SvANY (a) = SvANY (b); SvANY (b) = SvANY (&tmp);
662
663 /* swap sv_flags */
664 SvFLAGS (&tmp) = SvFLAGS (a);
665 SvFLAGS (a) = (SvFLAGS (a) & keep) | (SvFLAGS (b ) & ~keep);
666 SvFLAGS (b) = (SvFLAGS (b) & keep) | (SvFLAGS (&tmp) & ~keep);
667
668#if PERL_VERSION_ATLEAST (5,10,0)
669 /* perl 5.10 complicates this _quite_ a bit, but it also is
670 * much faster, so no quarrels here. alternatively, we could
671 * sv_upgrade to avoid this.
672 */
673 {
674 /* swap sv_u */
675 tmp.sv_u = a->sv_u; a->sv_u = b->sv_u; b->sv_u = tmp.sv_u;
676
677 /* if SvANY points to the head, we need to adjust the pointers,
678 * as the pointer for a still points to b, and maybe vice versa.
679 */
680 #define svany_in_head(type) \
681 (((1 << SVt_NULL) | (1 << SVt_BIND) | (1 << SVt_IV) | (1 << SVt_RV)) & (1 << (type)))
682
683 if (svany_in_head (SvTYPE (a)))
684 SvANY (a) = (void *)((PTRV)SvANY (a) - (PTRV)b + (PTRV)a);
685
686 if (svany_in_head (SvTYPE (b)))
687 SvANY (b) = (void *)((PTRV)SvANY (b) - (PTRV)a + (PTRV)b);
688 }
689#endif
690 }
691}
692
693#define SWAP_SVS(coro) \
694 if (ecb_expect_false ((coro)->swap_sv)) \
695 swap_svs (aTHX_ (coro))
608 696
609static void 697static void
610on_enterleave_call (pTHX_ SV *cb); 698on_enterleave_call (pTHX_ SV *cb);
611 699
612static void 700static void
615 perl_slots *slot = c->slot; 703 perl_slots *slot = c->slot;
616 c->slot = 0; 704 c->slot = 0;
617 705
618 PL_mainstack = c->mainstack; 706 PL_mainstack = c->mainstack;
619 707
620 GvSV (PL_defgv) = slot->defsv; 708#if CORO_JIT
621 GvAV (PL_defgv) = slot->defav; 709 load_perl_slots (slot);
622 GvSV (PL_errgv) = slot->errsv; 710#else
623 GvSV (irsgv) = slot->irsgv;
624 GvHV (PL_hintgv) = slot->hinthv;
625
626 #define VAR(name,type) PL_ ## name = slot->name; 711 #define VARx(name,expr,type) expr = slot->name;
627 # include "state.h" 712 # include "state.h"
628 #undef VAR 713 #undef VARx
714#endif
629 715
630 { 716 {
631 dSP; 717 dSP;
632 718
633 CV *cv; 719 CV *cv;
634 720
635 /* now do the ugly restore mess */ 721 /* now do the ugly restore mess */
636 while (expect_true (cv = (CV *)POPs)) 722 while (ecb_expect_true (cv = (CV *)POPs))
637 { 723 {
638 put_padlist (aTHX_ cv); /* mark this padlist as available */ 724 put_padlist (aTHX_ cv); /* mark this padlist as available */
639 CvDEPTH (cv) = PTR2IV (POPs); 725 CvDEPTH (cv) = PTR2IV (POPs);
640 CvPADLIST (cv) = (AV *)POPs; 726 CvPADLIST (cv) = (AV *)POPs;
641 } 727 }
644 } 730 }
645 731
646 slf_frame = c->slf_frame; 732 slf_frame = c->slf_frame;
647 CORO_THROW = c->except; 733 CORO_THROW = c->except;
648 734
649 if (expect_false (enable_times)) 735 if (ecb_expect_false (enable_times))
650 { 736 {
651 if (expect_false (!times_valid)) 737 if (ecb_expect_false (!times_valid))
652 coro_times_update (); 738 coro_times_update ();
653 739
654 coro_times_sub (c); 740 coro_times_sub (c);
655 } 741 }
656 742
657 if (expect_false (c->on_enter)) 743 if (ecb_expect_false (c->on_enter))
658 { 744 {
659 int i; 745 int i;
660 746
661 for (i = 0; i <= AvFILLp (c->on_enter); ++i) 747 for (i = 0; i <= AvFILLp (c->on_enter); ++i)
662 on_enterleave_call (aTHX_ AvARRAY (c->on_enter)[i]); 748 on_enterleave_call (aTHX_ AvARRAY (c->on_enter)[i]);
663 } 749 }
750
751 SWAP_SVS (c);
664} 752}
665 753
666static void 754static void
667save_perl (pTHX_ Coro__State c) 755save_perl (pTHX_ Coro__State c)
668{ 756{
757 SWAP_SVS (c);
758
669 if (expect_false (c->on_leave)) 759 if (ecb_expect_false (c->on_leave))
670 { 760 {
671 int i; 761 int i;
672 762
673 for (i = AvFILLp (c->on_leave); i >= 0; --i) 763 for (i = AvFILLp (c->on_leave); i >= 0; --i)
674 on_enterleave_call (aTHX_ AvARRAY (c->on_leave)[i]); 764 on_enterleave_call (aTHX_ AvARRAY (c->on_leave)[i]);
675 } 765 }
676 766
677 times_valid = 0; 767 times_valid = 0;
678 768
679 if (expect_false (enable_times)) 769 if (ecb_expect_false (enable_times))
680 { 770 {
681 coro_times_update (); times_valid = 1; 771 coro_times_update (); times_valid = 1;
682 coro_times_add (c); 772 coro_times_add (c);
683 } 773 }
684 774
698 788
699 XPUSHs (Nullsv); 789 XPUSHs (Nullsv);
700 /* this loop was inspired by pp_caller */ 790 /* this loop was inspired by pp_caller */
701 for (;;) 791 for (;;)
702 { 792 {
703 while (expect_true (cxix >= 0)) 793 while (ecb_expect_true (cxix >= 0))
704 { 794 {
705 PERL_CONTEXT *cx = &ccstk[cxix--]; 795 PERL_CONTEXT *cx = &ccstk[cxix--];
706 796
707 if (expect_true (CxTYPE (cx) == CXt_SUB) || expect_false (CxTYPE (cx) == CXt_FORMAT)) 797 if (ecb_expect_true (CxTYPE (cx) == CXt_SUB) || ecb_expect_false (CxTYPE (cx) == CXt_FORMAT))
708 { 798 {
709 CV *cv = cx->blk_sub.cv; 799 CV *cv = cx->blk_sub.cv;
710 800
711 if (expect_true (CvDEPTH (cv))) 801 if (ecb_expect_true (CvDEPTH (cv)))
712 { 802 {
713 EXTEND (SP, 3); 803 EXTEND (SP, 3);
714 PUSHs ((SV *)CvPADLIST (cv)); 804 PUSHs ((SV *)CvPADLIST (cv));
715 PUSHs (INT2PTR (SV *, (IV)CvDEPTH (cv))); 805 PUSHs (INT2PTR (SV *, (IV)CvDEPTH (cv)));
716 PUSHs ((SV *)cv); 806 PUSHs ((SV *)cv);
719 get_padlist (aTHX_ cv); 809 get_padlist (aTHX_ cv);
720 } 810 }
721 } 811 }
722 } 812 }
723 813
724 if (expect_true (top_si->si_type == PERLSI_MAIN)) 814 if (ecb_expect_true (top_si->si_type == PERLSI_MAIN))
725 break; 815 break;
726 816
727 top_si = top_si->si_prev; 817 top_si = top_si->si_prev;
728 ccstk = top_si->si_cxstack; 818 ccstk = top_si->si_cxstack;
729 cxix = top_si->si_cxix; 819 cxix = top_si->si_cxix;
731 821
732 PUTBACK; 822 PUTBACK;
733 } 823 }
734 824
735 /* allocate some space on the context stack for our purposes */ 825 /* allocate some space on the context stack for our purposes */
736 /* we manually unroll here, as usually 2 slots is enough */ 826 if (ecb_expect_false (cxstack_ix + (int)SLOT_COUNT >= cxstack_max))
737 if (SLOT_COUNT >= 1) CXINC;
738 if (SLOT_COUNT >= 2) CXINC;
739 if (SLOT_COUNT >= 3) CXINC;
740 { 827 {
741 unsigned int i; 828 unsigned int i;
829
742 for (i = 3; i < SLOT_COUNT; ++i) 830 for (i = 0; i < SLOT_COUNT; ++i)
743 CXINC; 831 CXINC;
744 } 832
745 cxstack_ix -= SLOT_COUNT; /* undo allocation */ 833 cxstack_ix -= SLOT_COUNT; /* undo allocation */
834 }
746 835
747 c->mainstack = PL_mainstack; 836 c->mainstack = PL_mainstack;
748 837
749 { 838 {
750 perl_slots *slot = c->slot = (perl_slots *)(cxstack + cxstack_ix + 1); 839 perl_slots *slot = c->slot = (perl_slots *)(cxstack + cxstack_ix + 1);
751 840
752 slot->defav = GvAV (PL_defgv); 841#if CORO_JIT
753 slot->defsv = DEFSV; 842 save_perl_slots (slot);
754 slot->errsv = ERRSV; 843#else
755 slot->irsgv = GvSV (irsgv);
756 slot->hinthv = GvHV (PL_hintgv);
757
758 #define VAR(name,type) slot->name = PL_ ## name; 844 #define VARx(name,expr,type) slot->name = expr;
759 # include "state.h" 845 # include "state.h"
760 #undef VAR 846 #undef VARx
847#endif
761 } 848 }
762} 849}
763 850
764/* 851/*
765 * allocate various perl stacks. This is almost an exact copy 852 * allocate various perl stacks. This is almost an exact copy
771# define coro_init_stacks(thx) init_stacks () 858# define coro_init_stacks(thx) init_stacks ()
772#else 859#else
773static void 860static void
774coro_init_stacks (pTHX) 861coro_init_stacks (pTHX)
775{ 862{
776 PL_curstackinfo = new_stackinfo(32, 8); 863 PL_curstackinfo = new_stackinfo(32, 4 + SLOT_COUNT); /* 3 is minimum due to perl rounding down in scope.c:GROW() */
777 PL_curstackinfo->si_type = PERLSI_MAIN; 864 PL_curstackinfo->si_type = PERLSI_MAIN;
778 PL_curstack = PL_curstackinfo->si_stack; 865 PL_curstack = PL_curstackinfo->si_stack;
779 PL_mainstack = PL_curstack; /* remember in case we switch stacks */ 866 PL_mainstack = PL_curstack; /* remember in case we switch stacks */
780 867
781 PL_stack_base = AvARRAY(PL_curstack); 868 PL_stack_base = AvARRAY(PL_curstack);
796#endif 883#endif
797 884
798 New(54,PL_scopestack,8,I32); 885 New(54,PL_scopestack,8,I32);
799 PL_scopestack_ix = 0; 886 PL_scopestack_ix = 0;
800 PL_scopestack_max = 8; 887 PL_scopestack_max = 8;
888#if HAS_SCOPESTACK_NAME
889 New(54,PL_scopestack_name,8,const char*);
890#endif
801 891
802 New(54,PL_savestack,24,ANY); 892 New(54,PL_savestack,24,ANY);
803 PL_savestack_ix = 0; 893 PL_savestack_ix = 0;
804 PL_savestack_max = 24; 894 PL_savestack_max = 24;
805 895
833 } 923 }
834 924
835 Safefree (PL_tmps_stack); 925 Safefree (PL_tmps_stack);
836 Safefree (PL_markstack); 926 Safefree (PL_markstack);
837 Safefree (PL_scopestack); 927 Safefree (PL_scopestack);
928#if HAS_SCOPESTACK_NAME
929 Safefree (PL_scopestack_name);
930#endif
838 Safefree (PL_savestack); 931 Safefree (PL_savestack);
839#if !PERL_VERSION_ATLEAST (5,10,0) 932#if !PERL_VERSION_ATLEAST (5,10,0)
840 Safefree (PL_retstack); 933 Safefree (PL_retstack);
841#endif 934#endif
842} 935}
888#endif 981#endif
889 982
890/* 983/*
891 * This overrides the default magic get method of %SIG elements. 984 * This overrides the default magic get method of %SIG elements.
892 * The original one doesn't provide for reading back of PL_diehook/PL_warnhook 985 * The original one doesn't provide for reading back of PL_diehook/PL_warnhook
893 * and instead of trying to save and restore the hash elements, we just provide 986 * and instead of trying to save and restore the hash elements (extremely slow),
894 * readback here. 987 * we just provide our own readback here.
895 */ 988 */
896static int 989static int ecb_cold
897coro_sigelem_get (pTHX_ SV *sv, MAGIC *mg) 990coro_sigelem_get (pTHX_ SV *sv, MAGIC *mg)
898{ 991{
899 const char *s = MgPV_nolen_const (mg); 992 const char *s = MgPV_nolen_const (mg);
900 993
901 if (*s == '_') 994 if (*s == '_')
913 } 1006 }
914 1007
915 return orig_sigelem_get ? orig_sigelem_get (aTHX_ sv, mg) : 0; 1008 return orig_sigelem_get ? orig_sigelem_get (aTHX_ sv, mg) : 0;
916} 1009}
917 1010
918static int 1011static int ecb_cold
919coro_sigelem_clr (pTHX_ SV *sv, MAGIC *mg) 1012coro_sigelem_clr (pTHX_ SV *sv, MAGIC *mg)
920{ 1013{
921 const char *s = MgPV_nolen_const (mg); 1014 const char *s = MgPV_nolen_const (mg);
922 1015
923 if (*s == '_') 1016 if (*s == '_')
937 } 1030 }
938 1031
939 return orig_sigelem_clr ? orig_sigelem_clr (aTHX_ sv, mg) : 0; 1032 return orig_sigelem_clr ? orig_sigelem_clr (aTHX_ sv, mg) : 0;
940} 1033}
941 1034
942static int 1035static int ecb_cold
943coro_sigelem_set (pTHX_ SV *sv, MAGIC *mg) 1036coro_sigelem_set (pTHX_ SV *sv, MAGIC *mg)
944{ 1037{
945 const char *s = MgPV_nolen_const (mg); 1038 const char *s = MgPV_nolen_const (mg);
946 1039
947 if (*s == '_') 1040 if (*s == '_')
980slf_check_repeat (pTHX_ struct CoroSLF *frame) 1073slf_check_repeat (pTHX_ struct CoroSLF *frame)
981{ 1074{
982 return 1; 1075 return 1;
983} 1076}
984 1077
985static UNOP coro_setup_op; 1078static UNOP init_perl_op;
986 1079
987static void NOINLINE /* noinline to keep it out of the transfer fast path */ 1080ecb_noinline static void /* noinline to keep it out of the transfer fast path */
988coro_setup (pTHX_ struct coro *coro) 1081init_perl (pTHX_ struct coro *coro)
989{ 1082{
990 /* 1083 /*
991 * emulate part of the perl startup here. 1084 * emulate part of the perl startup here.
992 */ 1085 */
993 coro_init_stacks (aTHX); 1086 coro_init_stacks (aTHX);
1000 PL_comppad_name_fill = 0; 1093 PL_comppad_name_fill = 0;
1001 PL_comppad_name_floor = 0; 1094 PL_comppad_name_floor = 0;
1002 PL_curpm = 0; 1095 PL_curpm = 0;
1003 PL_curpad = 0; 1096 PL_curpad = 0;
1004 PL_localizing = 0; 1097 PL_localizing = 0;
1005 PL_dirty = 0;
1006 PL_restartop = 0; 1098 PL_restartop = 0;
1007#if PERL_VERSION_ATLEAST (5,10,0) 1099#if PERL_VERSION_ATLEAST (5,10,0)
1008 PL_parser = 0; 1100 PL_parser = 0;
1009#endif 1101#endif
1010 PL_hints = 0; 1102 PL_hints = 0;
1011 1103
1012 /* recreate the die/warn hooks */ 1104 /* recreate the die/warn hooks */
1013 PL_diehook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__DIE__" , sizeof ("__DIE__" ) - 1, 1), rv_diehook ); 1105 PL_diehook = SvREFCNT_inc (rv_diehook);
1014 PL_warnhook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__WARN__", sizeof ("__WARN__") - 1, 1), rv_warnhook); 1106 PL_warnhook = SvREFCNT_inc (rv_warnhook);
1015 1107
1016 GvSV (PL_defgv) = newSV (0); 1108 GvSV (PL_defgv) = newSV (0);
1017 GvAV (PL_defgv) = coro->args; coro->args = 0; 1109 GvAV (PL_defgv) = coro->args; coro->args = 0;
1018 GvSV (PL_errgv) = newSV (0); 1110 GvSV (PL_errgv) = newSV (0);
1019 GvSV (irsgv) = newSVpvn ("\n", 1); sv_magic (GvSV (irsgv), (SV *)irsgv, PERL_MAGIC_sv, "/", 0); 1111 GvSV (irsgv) = newSVpvn ("\n", 1); sv_magic (GvSV (irsgv), (SV *)irsgv, PERL_MAGIC_sv, "/", 0);
1040 /* this newly created coroutine might be run on an existing cctx which most 1132 /* this newly created coroutine might be run on an existing cctx which most
1041 * likely was suspended in pp_slf, so we have to emulate entering pp_slf here. 1133 * likely was suspended in pp_slf, so we have to emulate entering pp_slf here.
1042 */ 1134 */
1043 slf_frame.prepare = prepare_nop; /* provide a nop function for an eventual pp_slf */ 1135 slf_frame.prepare = prepare_nop; /* provide a nop function for an eventual pp_slf */
1044 slf_frame.check = slf_check_nop; /* signal pp_slf to not repeat */ 1136 slf_frame.check = slf_check_nop; /* signal pp_slf to not repeat */
1137 slf_frame.destroy = 0;
1045 1138
1046 /* and we have to provide the pp_slf op in any case, so pp_slf can skip it */ 1139 /* and we have to provide the pp_slf op in any case, so pp_slf can skip it */
1047 coro_setup_op.op_next = PL_op; 1140 init_perl_op.op_next = PL_op;
1048 coro_setup_op.op_type = OP_ENTERSUB; 1141 init_perl_op.op_type = OP_ENTERSUB;
1049 coro_setup_op.op_ppaddr = pp_slf; 1142 init_perl_op.op_ppaddr = pp_slf;
1050 /* no flags etc. required, as an init function won't be called */ 1143 /* no flags etc. required, as an init function won't be called */
1051 1144
1052 PL_op = (OP *)&coro_setup_op; 1145 PL_op = (OP *)&init_perl_op;
1053 1146
1054 /* copy throw, in case it was set before coro_setup */ 1147 /* copy throw, in case it was set before init_perl */
1055 CORO_THROW = coro->except; 1148 CORO_THROW = coro->except;
1056 1149
1150 SWAP_SVS (coro);
1151
1057 if (expect_false (enable_times)) 1152 if (ecb_expect_false (enable_times))
1058 { 1153 {
1059 coro_times_update (); 1154 coro_times_update ();
1060 coro_times_sub (coro); 1155 coro_times_sub (coro);
1061 } 1156 }
1062} 1157}
1081 dounwind (-1); 1176 dounwind (-1);
1082 } 1177 }
1083} 1178}
1084 1179
1085static void 1180static void
1086coro_destruct_perl (pTHX_ struct coro *coro) 1181destroy_perl (pTHX_ struct coro *coro)
1087{ 1182{
1088 SV *svf [9]; 1183 SV *svf [9];
1089 1184
1090 { 1185 {
1186 SV *old_current = SvRV (coro_current);
1091 struct coro *current = SvSTATE_current; 1187 struct coro *current = SvSTATE (old_current);
1092 1188
1093 assert (("FATAL: tried to destroy currently running coroutine", coro->mainstack != PL_mainstack)); 1189 assert (("FATAL: tried to destroy currently running coroutine", coro->mainstack != PL_mainstack));
1094 1190
1095 save_perl (aTHX_ current); 1191 save_perl (aTHX_ current);
1192
1193 /* this will cause transfer_check to croak on block*/
1194 SvRV_set (coro_current, (SV *)coro->hv);
1195
1096 load_perl (aTHX_ coro); 1196 load_perl (aTHX_ coro);
1097 1197
1098 coro_unwind_stacks (aTHX); 1198 coro_unwind_stacks (aTHX);
1199
1200 /* restore swapped sv's */
1201 SWAP_SVS (coro);
1202
1099 coro_destruct_stacks (aTHX); 1203 coro_destruct_stacks (aTHX);
1100 1204
1101 // now save some sv's to be free'd later 1205 /* now save some sv's to be free'd later */
1102 svf [0] = GvSV (PL_defgv); 1206 svf [0] = GvSV (PL_defgv);
1103 svf [1] = (SV *)GvAV (PL_defgv); 1207 svf [1] = (SV *)GvAV (PL_defgv);
1104 svf [2] = GvSV (PL_errgv); 1208 svf [2] = GvSV (PL_errgv);
1105 svf [3] = (SV *)PL_defoutgv; 1209 svf [3] = (SV *)PL_defoutgv;
1106 svf [4] = PL_rs; 1210 svf [4] = PL_rs;
1108 svf [6] = (SV *)GvHV (PL_hintgv); 1212 svf [6] = (SV *)GvHV (PL_hintgv);
1109 svf [7] = PL_diehook; 1213 svf [7] = PL_diehook;
1110 svf [8] = PL_warnhook; 1214 svf [8] = PL_warnhook;
1111 assert (9 == sizeof (svf) / sizeof (*svf)); 1215 assert (9 == sizeof (svf) / sizeof (*svf));
1112 1216
1217 SvRV_set (coro_current, old_current);
1218
1113 load_perl (aTHX_ current); 1219 load_perl (aTHX_ current);
1114 } 1220 }
1115 1221
1116 { 1222 {
1117 unsigned int i; 1223 unsigned int i;
1124 SvREFCNT_dec (coro->invoke_cb); 1230 SvREFCNT_dec (coro->invoke_cb);
1125 SvREFCNT_dec (coro->invoke_av); 1231 SvREFCNT_dec (coro->invoke_av);
1126 } 1232 }
1127} 1233}
1128 1234
1129INLINE void 1235ecb_inline void
1130free_coro_mortal (pTHX) 1236free_coro_mortal (pTHX)
1131{ 1237{
1132 if (expect_true (coro_mortal)) 1238 if (ecb_expect_true (coro_mortal))
1133 { 1239 {
1134 SvREFCNT_dec (coro_mortal); 1240 SvREFCNT_dec ((SV *)coro_mortal);
1135 coro_mortal = 0; 1241 coro_mortal = 0;
1136 } 1242 }
1137} 1243}
1138 1244
1139static int 1245static int
1272 1378
1273 return frame->check (aTHX_ frame); /* execute the restored frame - there must be one */ 1379 return frame->check (aTHX_ frame); /* execute the restored frame - there must be one */
1274} 1380}
1275 1381
1276/* initialises PL_top_env and injects a pseudo-slf-call to set the stacklevel */ 1382/* initialises PL_top_env and injects a pseudo-slf-call to set the stacklevel */
1277static void NOINLINE 1383static void ecb_noinline
1278cctx_prepare (pTHX) 1384cctx_prepare (pTHX)
1279{ 1385{
1280 PL_top_env = &PL_start_env; 1386 PL_top_env = &PL_start_env;
1281 1387
1282 if (cctx_current->flags & CC_TRACE) 1388 if (cctx_current->flags & CC_TRACE)
1293 slf_frame.prepare = slf_prepare_set_stacklevel; 1399 slf_frame.prepare = slf_prepare_set_stacklevel;
1294 slf_frame.check = slf_check_set_stacklevel; 1400 slf_frame.check = slf_check_set_stacklevel;
1295} 1401}
1296 1402
1297/* the tail of transfer: execute stuff we can only do after a transfer */ 1403/* the tail of transfer: execute stuff we can only do after a transfer */
1298INLINE void 1404ecb_inline void
1299transfer_tail (pTHX) 1405transfer_tail (pTHX)
1300{ 1406{
1301 free_coro_mortal (aTHX); 1407 free_coro_mortal (aTHX);
1302} 1408}
1303 1409
1328 /* somebody or something will hit me for both perl_run and PL_restartop */ 1434 /* somebody or something will hit me for both perl_run and PL_restartop */
1329 PL_restartop = PL_op; 1435 PL_restartop = PL_op;
1330 perl_run (PL_curinterp); 1436 perl_run (PL_curinterp);
1331 /* 1437 /*
1332 * Unfortunately, there is no way to get at the return values of the 1438 * Unfortunately, there is no way to get at the return values of the
1333 * coro body here, as perl_run destroys these 1439 * coro body here, as perl_run destroys these. Likewise, we cannot catch
1440 * runtime errors here, as this is just a random interpreter, not a thread.
1334 */ 1441 */
1335 1442
1336 /* 1443 /*
1337 * If perl-run returns we assume exit() was being called or the coro 1444 * If perl-run returns we assume exit() was being called or the coro
1338 * fell off the end, which seems to be the only valid (non-bug) 1445 * fell off the end, which seems to be the only valid (non-bug)
1346 JMPENV_JUMP (2); /* I do not feel well about the hardcoded 2 at all */ 1453 JMPENV_JUMP (2); /* I do not feel well about the hardcoded 2 at all */
1347 } 1454 }
1348} 1455}
1349 1456
1350static coro_cctx * 1457static coro_cctx *
1351cctx_new () 1458cctx_new (void)
1352{ 1459{
1353 coro_cctx *cctx; 1460 coro_cctx *cctx;
1354 1461
1355 ++cctx_count; 1462 ++cctx_count;
1356 New (0, cctx, 1, coro_cctx); 1463 New (0, cctx, 1, coro_cctx);
1362 return cctx; 1469 return cctx;
1363} 1470}
1364 1471
1365/* create a new cctx only suitable as source */ 1472/* create a new cctx only suitable as source */
1366static coro_cctx * 1473static coro_cctx *
1367cctx_new_empty () 1474cctx_new_empty (void)
1368{ 1475{
1369 coro_cctx *cctx = cctx_new (); 1476 coro_cctx *cctx = cctx_new ();
1370 1477
1371 cctx->sptr = 0; 1478 cctx->sptr = 0;
1372 coro_create (&cctx->cctx, 0, 0, 0, 0); 1479 coro_create (&cctx->cctx, 0, 0, 0, 0);
1374 return cctx; 1481 return cctx;
1375} 1482}
1376 1483
1377/* create a new cctx suitable as destination/running a perl interpreter */ 1484/* create a new cctx suitable as destination/running a perl interpreter */
1378static coro_cctx * 1485static coro_cctx *
1379cctx_new_run () 1486cctx_new_run (void)
1380{ 1487{
1381 coro_cctx *cctx = cctx_new (); 1488 coro_cctx *cctx = cctx_new ();
1382 void *stack_start; 1489 void *stack_start;
1383 size_t stack_size; 1490 size_t stack_size;
1384 1491
1385#if HAVE_MMAP 1492#if HAVE_MMAP
1386 cctx->ssize = ((cctx_stacksize * sizeof (long) + PAGESIZE - 1) / PAGESIZE + CORO_STACKGUARD) * PAGESIZE; 1493 cctx->ssize = ((cctx_stacksize * sizeof (long) + PAGESIZE - 1) / PAGESIZE + CORO_STACKGUARD) * PAGESIZE;
1387 /* mmap supposedly does allocate-on-write for us */ 1494 /* mmap supposedly does allocate-on-write for us */
1388 cctx->sptr = mmap (0, cctx->ssize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0); 1495 cctx->sptr = mmap (0, cctx->ssize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANONYMOUS, 0, 0);
1389 1496
1390 if (cctx->sptr != (void *)-1) 1497 if (cctx->sptr != (void *)-1)
1391 { 1498 {
1392 #if CORO_STACKGUARD 1499 #if CORO_STACKGUARD
1393 mprotect (cctx->sptr, CORO_STACKGUARD * PAGESIZE, PROT_NONE); 1500 mprotect (cctx->sptr, CORO_STACKGUARD * PAGESIZE, PROT_NONE);
1425cctx_destroy (coro_cctx *cctx) 1532cctx_destroy (coro_cctx *cctx)
1426{ 1533{
1427 if (!cctx) 1534 if (!cctx)
1428 return; 1535 return;
1429 1536
1430 assert (("FATAL: tried to destroy current cctx", cctx != cctx_current));//D temporary? 1537 assert (("FATAL: tried to destroy current cctx", cctx != cctx_current));
1431 1538
1432 --cctx_count; 1539 --cctx_count;
1433 coro_destroy (&cctx->cctx); 1540 coro_destroy (&cctx->cctx);
1434 1541
1435 /* coro_transfer creates new, empty cctx's */ 1542 /* coro_transfer creates new, empty cctx's */
1454#define CCTX_EXPIRED(cctx) ((cctx)->gen != cctx_gen || ((cctx)->flags & CC_NOREUSE)) 1561#define CCTX_EXPIRED(cctx) ((cctx)->gen != cctx_gen || ((cctx)->flags & CC_NOREUSE))
1455 1562
1456static coro_cctx * 1563static coro_cctx *
1457cctx_get (pTHX) 1564cctx_get (pTHX)
1458{ 1565{
1459 while (expect_true (cctx_first)) 1566 while (ecb_expect_true (cctx_first))
1460 { 1567 {
1461 coro_cctx *cctx = cctx_first; 1568 coro_cctx *cctx = cctx_first;
1462 cctx_first = cctx->next; 1569 cctx_first = cctx->next;
1463 --cctx_idle; 1570 --cctx_idle;
1464 1571
1465 if (expect_true (!CCTX_EXPIRED (cctx))) 1572 if (ecb_expect_true (!CCTX_EXPIRED (cctx)))
1466 return cctx; 1573 return cctx;
1467 1574
1468 cctx_destroy (cctx); 1575 cctx_destroy (cctx);
1469 } 1576 }
1470 1577
1475cctx_put (coro_cctx *cctx) 1582cctx_put (coro_cctx *cctx)
1476{ 1583{
1477 assert (("FATAL: cctx_put called on non-initialised cctx in Coro (please report)", cctx->sptr)); 1584 assert (("FATAL: cctx_put called on non-initialised cctx in Coro (please report)", cctx->sptr));
1478 1585
1479 /* free another cctx if overlimit */ 1586 /* free another cctx if overlimit */
1480 if (expect_false (cctx_idle >= cctx_max_idle)) 1587 if (ecb_expect_false (cctx_idle >= cctx_max_idle))
1481 { 1588 {
1482 coro_cctx *first = cctx_first; 1589 coro_cctx *first = cctx_first;
1483 cctx_first = first->next; 1590 cctx_first = first->next;
1484 --cctx_idle; 1591 --cctx_idle;
1485 1592
1496static void 1603static void
1497transfer_check (pTHX_ struct coro *prev, struct coro *next) 1604transfer_check (pTHX_ struct coro *prev, struct coro *next)
1498{ 1605{
1499 /* TODO: throwing up here is considered harmful */ 1606 /* TODO: throwing up here is considered harmful */
1500 1607
1501 if (expect_true (prev != next)) 1608 if (ecb_expect_true (prev != next))
1502 { 1609 {
1503 if (expect_false (!(prev->flags & (CF_RUNNING | CF_NEW)))) 1610 if (ecb_expect_false (!(prev->flags & (CF_RUNNING | CF_NEW))))
1504 croak ("Coro::State::transfer called with a blocked prev Coro::State, but can only transfer from running or new states,"); 1611 croak ("Coro::State::transfer called with a blocked prev Coro::State, but can only transfer from running or new states,");
1505 1612
1506 if (expect_false (next->flags & (CF_RUNNING | CF_DESTROYED | CF_SUSPENDED))) 1613 if (ecb_expect_false (next->flags & (CF_RUNNING | CF_ZOMBIE | CF_SUSPENDED)))
1507 croak ("Coro::State::transfer called with running, destroyed or suspended next Coro::State, but can only transfer to inactive states,"); 1614 croak ("Coro::State::transfer called with running, destroyed or suspended next Coro::State, but can only transfer to inactive states,");
1508 1615
1509#if !PERL_VERSION_ATLEAST (5,10,0) 1616#if !PERL_VERSION_ATLEAST (5,10,0)
1510 if (expect_false (PL_lex_state != LEX_NOTPARSING)) 1617 if (ecb_expect_false (PL_lex_state != LEX_NOTPARSING))
1511 croak ("Coro::State::transfer called while parsing, but this is not supported in your perl version,"); 1618 croak ("Coro::State::transfer called while parsing, but this is not supported in your perl version,");
1512#endif 1619#endif
1513 } 1620 }
1514} 1621}
1515 1622
1516/* always use the TRANSFER macro */ 1623/* always use the TRANSFER macro */
1517static void NOINLINE /* noinline so we have a fixed stackframe */ 1624static void ecb_noinline /* noinline so we have a fixed stackframe */
1518transfer (pTHX_ struct coro *prev, struct coro *next, int force_cctx) 1625transfer (pTHX_ struct coro *prev, struct coro *next, int force_cctx)
1519{ 1626{
1520 dSTACKLEVEL; 1627 dSTACKLEVEL;
1521 1628
1522 /* sometimes transfer is only called to set idle_sp */ 1629 /* sometimes transfer is only called to set idle_sp */
1523 if (expect_false (!prev)) 1630 if (ecb_expect_false (!prev))
1524 { 1631 {
1525 cctx_current->idle_sp = STACKLEVEL; 1632 cctx_current->idle_sp = STACKLEVEL;
1526 assert (cctx_current->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */ 1633 assert (cctx_current->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */
1527 } 1634 }
1528 else if (expect_true (prev != next)) 1635 else if (ecb_expect_true (prev != next))
1529 { 1636 {
1530 coro_cctx *cctx_prev; 1637 coro_cctx *cctx_prev;
1531 1638
1532 if (expect_false (prev->flags & CF_NEW)) 1639 if (ecb_expect_false (prev->flags & CF_NEW))
1533 { 1640 {
1534 /* create a new empty/source context */ 1641 /* create a new empty/source context */
1535 prev->flags &= ~CF_NEW; 1642 prev->flags &= ~CF_NEW;
1536 prev->flags |= CF_RUNNING; 1643 prev->flags |= CF_RUNNING;
1537 } 1644 }
1540 next->flags |= CF_RUNNING; 1647 next->flags |= CF_RUNNING;
1541 1648
1542 /* first get rid of the old state */ 1649 /* first get rid of the old state */
1543 save_perl (aTHX_ prev); 1650 save_perl (aTHX_ prev);
1544 1651
1545 if (expect_false (next->flags & CF_NEW)) 1652 if (ecb_expect_false (next->flags & CF_NEW))
1546 { 1653 {
1547 /* need to start coroutine */ 1654 /* need to start coroutine */
1548 next->flags &= ~CF_NEW; 1655 next->flags &= ~CF_NEW;
1549 /* setup coroutine call */ 1656 /* setup coroutine call */
1550 coro_setup (aTHX_ next); 1657 init_perl (aTHX_ next);
1551 } 1658 }
1552 else 1659 else
1553 load_perl (aTHX_ next); 1660 load_perl (aTHX_ next);
1554 1661
1555 /* possibly untie and reuse the cctx */ 1662 /* possibly untie and reuse the cctx */
1556 if (expect_true ( 1663 if (ecb_expect_true (
1557 cctx_current->idle_sp == STACKLEVEL 1664 cctx_current->idle_sp == STACKLEVEL
1558 && !(cctx_current->flags & CC_TRACE) 1665 && !(cctx_current->flags & CC_TRACE)
1559 && !force_cctx 1666 && !force_cctx
1560 )) 1667 ))
1561 { 1668 {
1562 /* I assume that stacklevel is a stronger indicator than PL_top_env changes */ 1669 /* I assume that stacklevel is a stronger indicator than PL_top_env changes */
1563 assert (("FATAL: current top_env must equal previous top_env in Coro (please report)", PL_top_env == cctx_current->idle_te)); 1670 assert (("FATAL: current top_env must equal previous top_env in Coro (please report)", PL_top_env == cctx_current->idle_te));
1564 1671
1565 /* if the cctx is about to be destroyed we need to make sure we won't see it in cctx_get. */ 1672 /* if the cctx is about to be destroyed we need to make sure we won't see it in cctx_get. */
1566 /* without this the next cctx_get might destroy the running cctx while still in use */ 1673 /* without this the next cctx_get might destroy the running cctx while still in use */
1567 if (expect_false (CCTX_EXPIRED (cctx_current))) 1674 if (ecb_expect_false (CCTX_EXPIRED (cctx_current)))
1568 if (expect_true (!next->cctx)) 1675 if (ecb_expect_true (!next->cctx))
1569 next->cctx = cctx_get (aTHX); 1676 next->cctx = cctx_get (aTHX);
1570 1677
1571 cctx_put (cctx_current); 1678 cctx_put (cctx_current);
1572 } 1679 }
1573 else 1680 else
1574 prev->cctx = cctx_current; 1681 prev->cctx = cctx_current;
1575 1682
1576 ++next->usecount; 1683 ++next->usecount;
1577 1684
1578 cctx_prev = cctx_current; 1685 cctx_prev = cctx_current;
1579 cctx_current = expect_false (next->cctx) ? next->cctx : cctx_get (aTHX); 1686 cctx_current = ecb_expect_false (next->cctx) ? next->cctx : cctx_get (aTHX);
1580 1687
1581 next->cctx = 0; 1688 next->cctx = 0;
1582 1689
1583 if (expect_false (cctx_prev != cctx_current)) 1690 if (ecb_expect_false (cctx_prev != cctx_current))
1584 { 1691 {
1585 cctx_prev->top_env = PL_top_env; 1692 cctx_prev->top_env = PL_top_env;
1586 PL_top_env = cctx_current->top_env; 1693 PL_top_env = cctx_current->top_env;
1587 coro_transfer (&cctx_prev->cctx, &cctx_current->cctx); 1694 coro_transfer (&cctx_prev->cctx, &cctx_current->cctx);
1588 } 1695 }
1594#define TRANSFER(ta, force_cctx) transfer (aTHX_ (ta).prev, (ta).next, (force_cctx)) 1701#define TRANSFER(ta, force_cctx) transfer (aTHX_ (ta).prev, (ta).next, (force_cctx))
1595#define TRANSFER_CHECK(ta) transfer_check (aTHX_ (ta).prev, (ta).next) 1702#define TRANSFER_CHECK(ta) transfer_check (aTHX_ (ta).prev, (ta).next)
1596 1703
1597/** high level stuff ********************************************************/ 1704/** high level stuff ********************************************************/
1598 1705
1706/* this function is actually Coro, not Coro::State, but we call it from here */
1707/* because it is convenient - but it hasn't been declared yet for that reason */
1599static int 1708static void
1709coro_call_on_destroy (pTHX_ struct coro *coro);
1710
1711static void
1600coro_state_destroy (pTHX_ struct coro *coro) 1712coro_state_destroy (pTHX_ struct coro *coro)
1601{ 1713{
1602 if (coro->flags & CF_DESTROYED) 1714 if (coro->flags & CF_ZOMBIE)
1603 return 0; 1715 return;
1604 1716
1605 if (coro->on_destroy && !PL_dirty)
1606 coro->on_destroy (aTHX_ coro); 1717 slf_destroy (aTHX_ coro);
1607 1718
1608 coro->flags |= CF_DESTROYED; 1719 coro->flags |= CF_ZOMBIE;
1609 1720
1610 if (coro->flags & CF_READY) 1721 if (coro->flags & CF_READY)
1611 { 1722 {
1612 /* reduce nready, as destroying a ready coro effectively unreadies it */ 1723 /* reduce nready, as destroying a ready coro effectively unreadies it */
1613 /* alternative: look through all ready queues and remove the coro */ 1724 /* alternative: look through all ready queues and remove the coro */
1614 --coro_nready; 1725 --coro_nready;
1615 } 1726 }
1616 else 1727 else
1617 coro->flags |= CF_READY; /* make sure it is NOT put into the readyqueue */ 1728 coro->flags |= CF_READY; /* make sure it is NOT put into the readyqueue */
1729
1730 if (coro->next) coro->next->prev = coro->prev;
1731 if (coro->prev) coro->prev->next = coro->next;
1732 if (coro == coro_first) coro_first = coro->next;
1618 1733
1619 if (coro->mainstack 1734 if (coro->mainstack
1620 && coro->mainstack != main_mainstack 1735 && coro->mainstack != main_mainstack
1621 && coro->slot 1736 && coro->slot
1622 && !PL_dirty) 1737 && !PL_dirty)
1623 coro_destruct_perl (aTHX_ coro); 1738 destroy_perl (aTHX_ coro);
1624 1739
1625 cctx_destroy (coro->cctx); 1740 cctx_destroy (coro->cctx);
1626 SvREFCNT_dec (coro->startcv); 1741 SvREFCNT_dec (coro->startcv);
1627 SvREFCNT_dec (coro->args); 1742 SvREFCNT_dec (coro->args);
1743 SvREFCNT_dec (coro->swap_sv);
1628 SvREFCNT_dec (CORO_THROW); 1744 SvREFCNT_dec (CORO_THROW);
1629 1745
1630 if (coro->next) coro->next->prev = coro->prev; 1746 coro_call_on_destroy (aTHX_ coro);
1631 if (coro->prev) coro->prev->next = coro->next;
1632 if (coro == coro_first) coro_first = coro->next;
1633 1747
1634 return 1; 1748 /* more destruction mayhem in coro_state_free */
1635} 1749}
1636 1750
1637static int 1751static int
1638coro_state_free (pTHX_ SV *sv, MAGIC *mg) 1752coro_state_free (pTHX_ SV *sv, MAGIC *mg)
1639{ 1753{
1640 struct coro *coro = (struct coro *)mg->mg_ptr; 1754 struct coro *coro = (struct coro *)mg->mg_ptr;
1641 mg->mg_ptr = 0; 1755 mg->mg_ptr = 0;
1642 1756
1643 coro->hv = 0;
1644
1645 if (--coro->refcnt < 0)
1646 {
1647 coro_state_destroy (aTHX_ coro); 1757 coro_state_destroy (aTHX_ coro);
1758 SvREFCNT_dec (coro->on_destroy);
1759 SvREFCNT_dec (coro->status);
1760
1648 Safefree (coro); 1761 Safefree (coro);
1649 }
1650 1762
1651 return 0; 1763 return 0;
1652} 1764}
1653 1765
1654static int 1766static int ecb_cold
1655coro_state_dup (pTHX_ MAGIC *mg, CLONE_PARAMS *params) 1767coro_state_dup (pTHX_ MAGIC *mg, CLONE_PARAMS *params)
1656{ 1768{
1657 struct coro *coro = (struct coro *)mg->mg_ptr; 1769 /* called when perl clones the current process the slow way (windows process emulation) */
1658 1770 /* WE SIMply nuke the pointers in the copy, causing perl to croak */
1659 ++coro->refcnt; 1771 mg->mg_ptr = 0;
1772 mg->mg_virtual = 0;
1660 1773
1661 return 0; 1774 return 0;
1662} 1775}
1663 1776
1664static MGVTBL coro_state_vtbl = { 1777static MGVTBL coro_state_vtbl = {
1687 1800
1688 prepare_transfer (aTHX_ &ta, prev_sv, next_sv); 1801 prepare_transfer (aTHX_ &ta, prev_sv, next_sv);
1689 TRANSFER (ta, 1); 1802 TRANSFER (ta, 1);
1690} 1803}
1691 1804
1692/*****************************************************************************/
1693/* gensub: simple closure generation utility */
1694
1695#define GENSUB_ARG CvXSUBANY (cv).any_ptr
1696
1697/* create a closure from XS, returns a code reference */
1698/* the arg can be accessed via GENSUB_ARG from the callback */
1699/* the callback must use dXSARGS/XSRETURN */
1700static SV *
1701gensub (pTHX_ void (*xsub)(pTHX_ CV *), void *arg)
1702{
1703 CV *cv = (CV *)newSV (0);
1704
1705 sv_upgrade ((SV *)cv, SVt_PVCV);
1706
1707 CvANON_on (cv);
1708 CvISXSUB_on (cv);
1709 CvXSUB (cv) = xsub;
1710 GENSUB_ARG = arg;
1711
1712 return newRV_noinc ((SV *)cv);
1713}
1714
1715/** Coro ********************************************************************/ 1805/** Coro ********************************************************************/
1716 1806
1717INLINE void 1807ecb_inline void
1718coro_enq (pTHX_ struct coro *coro) 1808coro_enq (pTHX_ struct coro *coro)
1719{ 1809{
1720 struct coro **ready = coro_ready [coro->prio - CORO_PRIO_MIN]; 1810 struct coro **ready = coro_ready [coro->prio - CORO_PRIO_MIN];
1721 1811
1722 SvREFCNT_inc_NN (coro->hv); 1812 SvREFCNT_inc_NN (coro->hv);
1724 coro->next_ready = 0; 1814 coro->next_ready = 0;
1725 *(ready [0] ? &ready [1]->next_ready : &ready [0]) = coro; 1815 *(ready [0] ? &ready [1]->next_ready : &ready [0]) = coro;
1726 ready [1] = coro; 1816 ready [1] = coro;
1727} 1817}
1728 1818
1729INLINE struct coro * 1819ecb_inline struct coro *
1730coro_deq (pTHX) 1820coro_deq (pTHX)
1731{ 1821{
1732 int prio; 1822 int prio;
1733 1823
1734 for (prio = CORO_PRIO_MAX - CORO_PRIO_MIN + 1; --prio >= 0; ) 1824 for (prio = CORO_PRIO_MAX - CORO_PRIO_MIN + 1; --prio >= 0; )
1744 } 1834 }
1745 1835
1746 return 0; 1836 return 0;
1747} 1837}
1748 1838
1839static void
1840invoke_sv_ready_hook_helper (void)
1841{
1842 dTHX;
1843 dSP;
1844
1845 ENTER;
1846 SAVETMPS;
1847
1848 PUSHMARK (SP);
1849 PUTBACK;
1850 call_sv (coro_readyhook, G_VOID | G_DISCARD);
1851
1852 FREETMPS;
1853 LEAVE;
1854}
1855
1749static int 1856static int
1750api_ready (pTHX_ SV *coro_sv) 1857api_ready (pTHX_ SV *coro_sv)
1751{ 1858{
1752 struct coro *coro;
1753 SV *sv_hook;
1754 void (*xs_hook)(void);
1755
1756 coro = SvSTATE (coro_sv); 1859 struct coro *coro = SvSTATE (coro_sv);
1757 1860
1758 if (coro->flags & CF_READY) 1861 if (coro->flags & CF_READY)
1759 return 0; 1862 return 0;
1760 1863
1761 coro->flags |= CF_READY; 1864 coro->flags |= CF_READY;
1762 1865
1763 sv_hook = coro_nready ? 0 : coro_readyhook;
1764 xs_hook = coro_nready ? 0 : coroapi.readyhook;
1765
1766 coro_enq (aTHX_ coro); 1866 coro_enq (aTHX_ coro);
1767 ++coro_nready;
1768 1867
1769 if (sv_hook) 1868 if (!coro_nready++)
1770 { 1869 if (coroapi.readyhook)
1771 dSP; 1870 coroapi.readyhook ();
1772
1773 ENTER;
1774 SAVETMPS;
1775
1776 PUSHMARK (SP);
1777 PUTBACK;
1778 call_sv (sv_hook, G_VOID | G_DISCARD);
1779
1780 FREETMPS;
1781 LEAVE;
1782 }
1783
1784 if (xs_hook)
1785 xs_hook ();
1786 1871
1787 return 1; 1872 return 1;
1788} 1873}
1789 1874
1790static int 1875static int
1792{ 1877{
1793 return !!(SvSTATE (coro_sv)->flags & CF_READY); 1878 return !!(SvSTATE (coro_sv)->flags & CF_READY);
1794} 1879}
1795 1880
1796/* expects to own a reference to next->hv */ 1881/* expects to own a reference to next->hv */
1797INLINE void 1882ecb_inline void
1798prepare_schedule_to (pTHX_ struct coro_transfer_args *ta, struct coro *next) 1883prepare_schedule_to (pTHX_ struct coro_transfer_args *ta, struct coro *next)
1799{ 1884{
1800 SV *prev_sv = SvRV (coro_current); 1885 SV *prev_sv = SvRV (coro_current);
1801 1886
1802 ta->prev = SvSTATE_hv (prev_sv); 1887 ta->prev = SvSTATE_hv (prev_sv);
1815{ 1900{
1816 for (;;) 1901 for (;;)
1817 { 1902 {
1818 struct coro *next = coro_deq (aTHX); 1903 struct coro *next = coro_deq (aTHX);
1819 1904
1820 if (expect_true (next)) 1905 if (ecb_expect_true (next))
1821 { 1906 {
1822 /* cannot transfer to destroyed coros, skip and look for next */ 1907 /* cannot transfer to destroyed coros, skip and look for next */
1823 if (expect_false (next->flags & (CF_DESTROYED | CF_SUSPENDED))) 1908 if (ecb_expect_false (next->flags & (CF_ZOMBIE | CF_SUSPENDED)))
1824 SvREFCNT_dec (next->hv); /* coro_nready has already been taken care of by destroy */ 1909 SvREFCNT_dec (next->hv); /* coro_nready has already been taken care of by destroy */
1825 else 1910 else
1826 { 1911 {
1827 next->flags &= ~CF_READY; 1912 next->flags &= ~CF_READY;
1828 --coro_nready; 1913 --coro_nready;
1835 { 1920 {
1836 /* nothing to schedule: call the idle handler */ 1921 /* nothing to schedule: call the idle handler */
1837 if (SvROK (sv_idle) 1922 if (SvROK (sv_idle)
1838 && SvOBJECT (SvRV (sv_idle))) 1923 && SvOBJECT (SvRV (sv_idle)))
1839 { 1924 {
1925 if (SvRV (sv_idle) == SvRV (coro_current))
1926 croak ("FATAL: $Coro::IDLE blocked itself - did you try to block inside an event loop callback? Caught");
1927
1840 ++coro_nready; /* hack so that api_ready doesn't invoke ready hook */ 1928 ++coro_nready; /* hack so that api_ready doesn't invoke ready hook */
1841 api_ready (aTHX_ SvRV (sv_idle)); 1929 api_ready (aTHX_ SvRV (sv_idle));
1842 --coro_nready; 1930 --coro_nready;
1843 } 1931 }
1844 else 1932 else
1845 { 1933 {
1934 /* TODO: deprecated, remove, cannot work reliably *//*D*/
1846 dSP; 1935 dSP;
1847 1936
1848 ENTER; 1937 ENTER;
1849 SAVETMPS; 1938 SAVETMPS;
1850 1939
1857 } 1946 }
1858 } 1947 }
1859 } 1948 }
1860} 1949}
1861 1950
1862INLINE void 1951ecb_inline void
1863prepare_cede (pTHX_ struct coro_transfer_args *ta) 1952prepare_cede (pTHX_ struct coro_transfer_args *ta)
1864{ 1953{
1865 api_ready (aTHX_ coro_current); 1954 api_ready (aTHX_ coro_current);
1866 prepare_schedule (aTHX_ ta); 1955 prepare_schedule (aTHX_ ta);
1867} 1956}
1868 1957
1869INLINE void 1958ecb_inline void
1870prepare_cede_notself (pTHX_ struct coro_transfer_args *ta) 1959prepare_cede_notself (pTHX_ struct coro_transfer_args *ta)
1871{ 1960{
1872 SV *prev = SvRV (coro_current); 1961 SV *prev = SvRV (coro_current);
1873 1962
1874 if (coro_nready) 1963 if (coro_nready)
1904{ 1993{
1905 struct coro_transfer_args ta; 1994 struct coro_transfer_args ta;
1906 1995
1907 prepare_cede (aTHX_ &ta); 1996 prepare_cede (aTHX_ &ta);
1908 1997
1909 if (expect_true (ta.prev != ta.next)) 1998 if (ecb_expect_true (ta.prev != ta.next))
1910 { 1999 {
1911 TRANSFER (ta, 1); 2000 TRANSFER (ta, 1);
1912 return 1; 2001 return 1;
1913 } 2002 }
1914 else 2003 else
1957 coro->slot->runops = RUNOPS_DEFAULT; 2046 coro->slot->runops = RUNOPS_DEFAULT;
1958 } 2047 }
1959} 2048}
1960 2049
1961static void 2050static void
2051coro_push_av (pTHX_ AV *av, I32 gimme_v)
2052{
2053 if (AvFILLp (av) >= 0 && gimme_v != G_VOID)
2054 {
2055 dSP;
2056
2057 if (gimme_v == G_SCALAR)
2058 XPUSHs (AvARRAY (av)[AvFILLp (av)]);
2059 else
2060 {
2061 int i;
2062 EXTEND (SP, AvFILLp (av) + 1);
2063
2064 for (i = 0; i <= AvFILLp (av); ++i)
2065 PUSHs (AvARRAY (av)[i]);
2066 }
2067
2068 PUTBACK;
2069 }
2070}
2071
2072static void
2073coro_push_on_destroy (pTHX_ struct coro *coro, SV *cb)
2074{
2075 if (!coro->on_destroy)
2076 coro->on_destroy = newAV ();
2077
2078 av_push (coro->on_destroy, cb);
2079}
2080
2081static void
2082slf_destroy_join (pTHX_ struct CoroSLF *frame)
2083{
2084 SvREFCNT_dec ((SV *)((struct coro *)frame->data)->hv);
2085}
2086
2087static int
2088slf_check_join (pTHX_ struct CoroSLF *frame)
2089{
2090 struct coro *coro = (struct coro *)frame->data;
2091
2092 if (!coro->status)
2093 return 1;
2094
2095 frame->destroy = 0;
2096
2097 coro_push_av (aTHX_ coro->status, GIMME_V);
2098
2099 SvREFCNT_dec ((SV *)coro->hv);
2100
2101 return 0;
2102}
2103
2104static void
2105slf_init_join (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2106{
2107 struct coro *coro = SvSTATE (items > 0 ? arg [0] : &PL_sv_undef);
2108
2109 if (items > 1)
2110 croak ("join called with too many arguments");
2111
2112 if (coro->status)
2113 frame->prepare = prepare_nop;
2114 else
2115 {
2116 coro_push_on_destroy (aTHX_ coro, SvREFCNT_inc_NN (SvRV (coro_current)));
2117 frame->prepare = prepare_schedule;
2118 }
2119
2120 frame->check = slf_check_join;
2121 frame->destroy = slf_destroy_join;
2122 frame->data = (void *)coro;
2123 SvREFCNT_inc (coro->hv);
2124}
2125
2126static void
1962coro_call_on_destroy (pTHX_ struct coro *coro) 2127coro_call_on_destroy (pTHX_ struct coro *coro)
1963{ 2128{
1964 SV **on_destroyp = hv_fetch (coro->hv, "_on_destroy", sizeof ("_on_destroy") - 1, 0); 2129 AV *od = coro->on_destroy;
1965 SV **statusp = hv_fetch (coro->hv, "_status", sizeof ("_status") - 1, 0);
1966 2130
1967 if (on_destroyp) 2131 if (!od)
1968 { 2132 return;
1969 AV *on_destroy = (AV *)SvRV (*on_destroyp);
1970 2133
1971 while (AvFILLp (on_destroy) >= 0) 2134 while (AvFILLp (od) >= 0)
2135 {
2136 SV *cb = sv_2mortal (av_pop (od));
2137
2138 /* coro hv's (and only hv's at the moment) are supported as well */
2139 if (SvSTATEhv_p (aTHX_ cb))
2140 api_ready (aTHX_ cb);
2141 else
1972 { 2142 {
1973 dSP; /* don't disturb outer sp */ 2143 dSP; /* don't disturb outer sp */
1974 SV *cb = av_pop (on_destroy);
1975
1976 PUSHMARK (SP); 2144 PUSHMARK (SP);
1977 2145
1978 if (statusp) 2146 if (coro->status)
1979 { 2147 {
1980 int i; 2148 PUTBACK;
1981 AV *status = (AV *)SvRV (*statusp); 2149 coro_push_av (aTHX_ coro->status, G_ARRAY);
1982 EXTEND (SP, AvFILLp (status) + 1); 2150 SPAGAIN;
1983
1984 for (i = 0; i <= AvFILLp (status); ++i)
1985 PUSHs (AvARRAY (status)[i]);
1986 } 2151 }
1987 2152
1988 PUTBACK; 2153 PUTBACK;
1989 call_sv (sv_2mortal (cb), G_VOID | G_DISCARD); 2154 call_sv (cb, G_VOID | G_DISCARD);
1990 } 2155 }
1991 } 2156 }
1992} 2157}
1993 2158
1994static void 2159static void
1995slf_init_terminate (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) 2160coro_set_status (pTHX_ struct coro *coro, SV **arg, int items)
1996{ 2161{
2162 AV *av;
2163
2164 if (coro->status)
2165 {
2166 av = coro->status;
2167 av_clear (av);
2168 }
2169 else
2170 av = coro->status = newAV ();
2171
2172 /* items are actually not so common, so optimise for this case */
2173 if (items)
2174 {
1997 int i; 2175 int i;
1998 HV *hv = (HV *)SvRV (coro_current);
1999 AV *av = newAV ();
2000 2176
2001 av_extend (av, items - 1); 2177 av_extend (av, items - 1);
2178
2002 for (i = 0; i < items; ++i) 2179 for (i = 0; i < items; ++i)
2003 av_push (av, SvREFCNT_inc_NN (arg [i])); 2180 av_push (av, SvREFCNT_inc_NN (arg [i]));
2181 }
2182}
2004 2183
2005 hv_store (hv, "_status", sizeof ("_status") - 1, newRV_noinc ((SV *)av), 0); 2184static void
2006 2185slf_init_terminate_cancel_common (pTHX_ struct CoroSLF *frame, HV *coro_hv)
2186{
2007 av_push (av_destroy, (SV *)newRV_inc ((SV *)hv)); /* RVinc for perl */ 2187 av_push (av_destroy, (SV *)newRV_inc ((SV *)coro_hv)); /* RVinc for perl */
2008 api_ready (aTHX_ sv_manager); 2188 api_ready (aTHX_ sv_manager);
2009 2189
2010 frame->prepare = prepare_schedule; 2190 frame->prepare = prepare_schedule;
2011 frame->check = slf_check_repeat; 2191 frame->check = slf_check_repeat;
2012 2192
2013 /* as a minor optimisation, we could unwind all stacks here */ 2193 /* as a minor optimisation, we could unwind all stacks here */
2014 /* but that puts extra pressure on pp_slf, and is not worth much */ 2194 /* but that puts extra pressure on pp_slf, and is not worth much */
2015 /*coro_unwind_stacks (aTHX);*/ 2195 /*coro_unwind_stacks (aTHX);*/
2196}
2197
2198static void
2199slf_init_terminate (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2200{
2201 HV *coro_hv = (HV *)SvRV (coro_current);
2202
2203 coro_set_status (aTHX_ SvSTATE ((SV *)coro_hv), arg, items);
2204 slf_init_terminate_cancel_common (aTHX_ frame, coro_hv);
2205}
2206
2207static void
2208slf_init_cancel (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2209{
2210 HV *coro_hv;
2211 struct coro *coro;
2212
2213 if (items <= 0)
2214 croak ("Coro::cancel called without coro object,");
2215
2216 coro = SvSTATE (arg [0]);
2217 coro_hv = coro->hv;
2218
2219 coro_set_status (aTHX_ coro, arg + 1, items - 1);
2220
2221 if (ecb_expect_false (coro->flags & CF_NOCANCEL))
2222 {
2223 /* coro currently busy cancelling something, so just notify it */
2224 coro->slf_frame.data = (void *)coro;
2225
2226 frame->prepare = prepare_nop;
2227 frame->check = slf_check_nop;
2228 }
2229 else if (coro_hv == (HV *)SvRV (coro_current))
2230 {
2231 /* cancelling the current coro is allowed, and equals terminate */
2232 slf_init_terminate_cancel_common (aTHX_ frame, coro_hv);
2233 }
2234 else
2235 {
2236 struct coro *self = SvSTATE_current;
2237
2238 /* otherwise we cancel directly, purely for speed reasons
2239 * unfortunately, this requires some magic trickery, as
2240 * somebody else could cancel us, so we have to fight the cancellation.
2241 * this is ugly, and hopefully fully worth the extra speed.
2242 * besides, I can't get the slow-but-safe version working...
2243 */
2244 slf_frame.data = 0;
2245 self->flags |= CF_NOCANCEL;
2246 coro_state_destroy (aTHX_ coro);
2247 self->flags &= ~CF_NOCANCEL;
2248
2249 if (slf_frame.data)
2250 {
2251 /* while we were busy we have been cancelled, so terminate */
2252 slf_init_terminate_cancel_common (aTHX_ frame, self->hv);
2253 }
2254 else
2255 {
2256 frame->prepare = prepare_nop;
2257 frame->check = slf_check_nop;
2258 }
2259 }
2260}
2261
2262static int
2263slf_check_safe_cancel (pTHX_ struct CoroSLF *frame)
2264{
2265 frame->prepare = 0;
2266 coro_unwind_stacks (aTHX);
2267
2268 slf_init_terminate_cancel_common (aTHX_ frame, (HV *)SvRV (coro_current));
2269
2270 return 1;
2271}
2272
2273static int
2274safe_cancel (pTHX_ struct coro *coro, SV **arg, int items)
2275{
2276 if (coro->cctx)
2277 croak ("coro inside C callback, unable to cancel at this time, caught");
2278
2279 if (coro->flags & CF_NEW)
2280 {
2281 coro_set_status (aTHX_ coro, arg, items);
2282 coro_state_destroy (aTHX_ coro);
2283 }
2284 else
2285 {
2286 if (!coro->slf_frame.prepare)
2287 croak ("coro outside an SLF function, unable to cancel at this time, caught");
2288
2289 slf_destroy (aTHX_ coro);
2290
2291 coro_set_status (aTHX_ coro, arg, items);
2292 coro->slf_frame.prepare = prepare_nop;
2293 coro->slf_frame.check = slf_check_safe_cancel;
2294
2295 api_ready (aTHX_ (SV *)coro->hv);
2296 }
2297
2298 return 1;
2016} 2299}
2017 2300
2018/*****************************************************************************/ 2301/*****************************************************************************/
2019/* async pool handler */ 2302/* async pool handler */
2020 2303
2051slf_init_pool_handler (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) 2334slf_init_pool_handler (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2052{ 2335{
2053 HV *hv = (HV *)SvRV (coro_current); 2336 HV *hv = (HV *)SvRV (coro_current);
2054 struct coro *coro = SvSTATE_hv ((SV *)hv); 2337 struct coro *coro = SvSTATE_hv ((SV *)hv);
2055 2338
2056 if (expect_true (coro->saved_deffh)) 2339 if (ecb_expect_true (coro->saved_deffh))
2057 { 2340 {
2058 /* subsequent iteration */ 2341 /* subsequent iteration */
2059 SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh; 2342 SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh;
2060 coro->saved_deffh = 0; 2343 coro->saved_deffh = 0;
2061 2344
2062 if (coro_rss (aTHX_ coro) > SvUV (sv_pool_rss) 2345 if (coro_rss (aTHX_ coro) > SvUV (sv_pool_rss)
2063 || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size)) 2346 || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size))
2064 { 2347 {
2065 coro->invoke_cb = SvREFCNT_inc_NN ((SV *)cv_coro_terminate); 2348 slf_init_terminate_cancel_common (aTHX_ frame, hv);
2066 coro->invoke_av = newAV (); 2349 return;
2067
2068 frame->prepare = prepare_nop;
2069 } 2350 }
2070 else 2351 else
2071 { 2352 {
2072 av_clear (GvAV (PL_defgv)); 2353 av_clear (GvAV (PL_defgv));
2073 hv_store (hv, "desc", sizeof ("desc") - 1, SvREFCNT_inc_NN (sv_async_pool_idle), 0); 2354 hv_store (hv, "desc", sizeof ("desc") - 1, SvREFCNT_inc_NN (sv_async_pool_idle), 0);
2098 2379
2099static void 2380static void
2100coro_rouse_callback (pTHX_ CV *cv) 2381coro_rouse_callback (pTHX_ CV *cv)
2101{ 2382{
2102 dXSARGS; 2383 dXSARGS;
2103 SV *data = (SV *)GENSUB_ARG; 2384 SV *data = (SV *)S_GENSUB_ARG;
2104 2385
2105 if (SvTYPE (SvRV (data)) != SVt_PVAV) 2386 if (SvTYPE (SvRV (data)) != SVt_PVAV)
2106 { 2387 {
2107 /* first call, set args */ 2388 /* first call, set args */
2108 SV *coro = SvRV (data); 2389 SV *coro = SvRV (data);
2174 || SvTYPE (SvRV (cb)) != SVt_PVCV 2455 || SvTYPE (SvRV (cb)) != SVt_PVCV
2175 || CvXSUB ((CV *)SvRV (cb)) != coro_rouse_callback) 2456 || CvXSUB ((CV *)SvRV (cb)) != coro_rouse_callback)
2176 croak ("Coro::rouse_wait called with illegal callback argument,"); 2457 croak ("Coro::rouse_wait called with illegal callback argument,");
2177 2458
2178 { 2459 {
2179 CV *cv = (CV *)SvRV (cb); /* for GENSUB_ARG */ 2460 CV *cv = (CV *)SvRV (cb); /* for S_GENSUB_ARG */
2180 SV *data = (SV *)GENSUB_ARG; 2461 SV *data = (SV *)S_GENSUB_ARG;
2181 2462
2182 frame->data = (void *)data; 2463 frame->data = (void *)data;
2183 frame->prepare = SvTYPE (SvRV (data)) == SVt_PVAV ? prepare_nop : prepare_schedule; 2464 frame->prepare = SvTYPE (SvRV (data)) == SVt_PVAV ? prepare_nop : prepare_schedule;
2184 frame->check = slf_check_rouse_wait; 2465 frame->check = slf_check_rouse_wait;
2185 } 2466 }
2189coro_new_rouse_cb (pTHX) 2470coro_new_rouse_cb (pTHX)
2190{ 2471{
2191 HV *hv = (HV *)SvRV (coro_current); 2472 HV *hv = (HV *)SvRV (coro_current);
2192 struct coro *coro = SvSTATE_hv (hv); 2473 struct coro *coro = SvSTATE_hv (hv);
2193 SV *data = newRV_inc ((SV *)hv); 2474 SV *data = newRV_inc ((SV *)hv);
2194 SV *cb = gensub (aTHX_ coro_rouse_callback, (void *)data); 2475 SV *cb = s_gensub (aTHX_ coro_rouse_callback, (void *)data);
2195 2476
2196 sv_magicext (SvRV (cb), data, CORO_MAGIC_type_rouse, 0, 0, 0); 2477 sv_magicext (SvRV (cb), data, CORO_MAGIC_type_rouse, 0, 0, 0);
2197 SvREFCNT_dec (data); /* magicext increases the refcount */ 2478 SvREFCNT_dec (data); /* magicext increases the refcount */
2198 2479
2199 SvREFCNT_dec (coro->rouse_cb); 2480 SvREFCNT_dec (coro->rouse_cb);
2296static void 2577static void
2297slf_init_cede_notself (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) 2578slf_init_cede_notself (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2298{ 2579{
2299 frame->prepare = prepare_cede_notself; 2580 frame->prepare = prepare_cede_notself;
2300 frame->check = slf_check_nop; 2581 frame->check = slf_check_nop;
2582}
2583
2584/* "undo"/cancel a running slf call - used when cancelling a coro, mainly */
2585static void
2586slf_destroy (pTHX_ struct coro *coro)
2587{
2588 /* this callback is reserved for slf functions needing to do cleanup */
2589 if (coro->slf_frame.destroy && coro->slf_frame.prepare && !PL_dirty)
2590 coro->slf_frame.destroy (aTHX_ &coro->slf_frame);
2591
2592 /*
2593 * The on_destroy above most likely is from an SLF call.
2594 * Since by definition the SLF call will not finish when we destroy
2595 * the coro, we will have to force-finish it here, otherwise
2596 * cleanup functions cannot call SLF functions.
2597 */
2598 coro->slf_frame.prepare = 0;
2301} 2599}
2302 2600
2303/* 2601/*
2304 * these not obviously related functions are all rolled into one 2602 * these not obviously related functions are all rolled into one
2305 * function to increase chances that they all will call transfer with the same 2603 * function to increase chances that they all will call transfer with the same
2312 I32 checkmark; /* mark SP to see how many elements check has pushed */ 2610 I32 checkmark; /* mark SP to see how many elements check has pushed */
2313 2611
2314 /* set up the slf frame, unless it has already been set-up */ 2612 /* set up the slf frame, unless it has already been set-up */
2315 /* the latter happens when a new coro has been started */ 2613 /* the latter happens when a new coro has been started */
2316 /* or when a new cctx was attached to an existing coroutine */ 2614 /* or when a new cctx was attached to an existing coroutine */
2317 if (expect_true (!slf_frame.prepare)) 2615 if (ecb_expect_true (!slf_frame.prepare))
2318 { 2616 {
2319 /* first iteration */ 2617 /* first iteration */
2320 dSP; 2618 dSP;
2321 SV **arg = PL_stack_base + TOPMARK + 1; 2619 SV **arg = PL_stack_base + TOPMARK + 1;
2322 int items = SP - arg; /* args without function object */ 2620 int items = SP - arg; /* args without function object */
2363 while (slf_frame.check (aTHX_ &slf_frame)); 2661 while (slf_frame.check (aTHX_ &slf_frame));
2364 2662
2365 slf_frame.prepare = 0; /* invalidate the frame, we are done processing it */ 2663 slf_frame.prepare = 0; /* invalidate the frame, we are done processing it */
2366 2664
2367 /* exception handling */ 2665 /* exception handling */
2368 if (expect_false (CORO_THROW)) 2666 if (ecb_expect_false (CORO_THROW))
2369 { 2667 {
2370 SV *exception = sv_2mortal (CORO_THROW); 2668 SV *exception = sv_2mortal (CORO_THROW);
2371 2669
2372 CORO_THROW = 0; 2670 CORO_THROW = 0;
2373 sv_setsv (ERRSV, exception); 2671 sv_setsv (ERRSV, exception);
2374 croak (0); 2672 croak (0);
2375 } 2673 }
2376 2674
2377 /* return value handling - mostly like entersub */ 2675 /* return value handling - mostly like entersub */
2378 /* make sure we put something on the stack in scalar context */ 2676 /* make sure we put something on the stack in scalar context */
2379 if (GIMME_V == G_SCALAR) 2677 if (GIMME_V == G_SCALAR
2678 && ecb_expect_false (PL_stack_sp != PL_stack_base + checkmark + 1))
2380 { 2679 {
2381 dSP; 2680 dSP;
2382 SV **bot = PL_stack_base + checkmark; 2681 SV **bot = PL_stack_base + checkmark;
2383 2682
2384 if (sp == bot) /* too few, push undef */ 2683 if (sp == bot) /* too few, push undef */
2385 bot [1] = &PL_sv_undef; 2684 bot [1] = &PL_sv_undef;
2386 else if (sp != bot + 1) /* too many, take last one */ 2685 else /* too many, take last one */
2387 bot [1] = *sp; 2686 bot [1] = *sp;
2388 2687
2389 SP = bot + 1; 2688 SP = bot + 1;
2390 2689
2391 PUTBACK; 2690 PUTBACK;
2424 if (PL_op->op_flags & OPf_STACKED) 2723 if (PL_op->op_flags & OPf_STACKED)
2425 { 2724 {
2426 if (items > slf_arga) 2725 if (items > slf_arga)
2427 { 2726 {
2428 slf_arga = items; 2727 slf_arga = items;
2429 free (slf_argv); 2728 Safefree (slf_argv);
2430 slf_argv = malloc (slf_arga * sizeof (SV *)); 2729 New (0, slf_argv, slf_arga, SV *);
2431 } 2730 }
2432 2731
2433 slf_argc = items; 2732 slf_argc = items;
2434 2733
2435 for (i = 0; i < items; ++i) 2734 for (i = 0; i < items; ++i)
2498{ 2797{
2499 PerlIOBuf base; 2798 PerlIOBuf base;
2500 NV next, every; 2799 NV next, every;
2501} PerlIOCede; 2800} PerlIOCede;
2502 2801
2503static IV 2802static IV ecb_cold
2504PerlIOCede_pushed (pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab) 2803PerlIOCede_pushed (pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
2505{ 2804{
2506 PerlIOCede *self = PerlIOSelf (f, PerlIOCede); 2805 PerlIOCede *self = PerlIOSelf (f, PerlIOCede);
2507 2806
2508 self->every = SvCUR (arg) ? SvNV (arg) : 0.01; 2807 self->every = SvCUR (arg) ? SvNV (arg) : 0.01;
2509 self->next = nvtime () + self->every; 2808 self->next = nvtime () + self->every;
2510 2809
2511 return PerlIOBuf_pushed (aTHX_ f, mode, Nullsv, tab); 2810 return PerlIOBuf_pushed (aTHX_ f, mode, Nullsv, tab);
2512} 2811}
2513 2812
2514static SV * 2813static SV * ecb_cold
2515PerlIOCede_getarg (pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags) 2814PerlIOCede_getarg (pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
2516{ 2815{
2517 PerlIOCede *self = PerlIOSelf (f, PerlIOCede); 2816 PerlIOCede *self = PerlIOSelf (f, PerlIOCede);
2518 2817
2519 return newSVnv (self->every); 2818 return newSVnv (self->every);
2631 SvREFCNT_dec (cb); 2930 SvREFCNT_dec (cb);
2632 } 2931 }
2633} 2932}
2634 2933
2635static void 2934static void
2636coro_semaphore_on_destroy (pTHX_ struct coro *coro) 2935coro_semaphore_destroy (pTHX_ struct CoroSLF *frame)
2637{ 2936{
2638 /* call $sem->adjust (0) to possibly wake up some other waiters */ 2937 /* call $sem->adjust (0) to possibly wake up some other waiters */
2639 coro_semaphore_adjust (aTHX_ (AV *)coro->slf_frame.data, 0); 2938 coro_semaphore_adjust (aTHX_ (AV *)frame->data, 0);
2640} 2939}
2641 2940
2642static int 2941static int
2643slf_check_semaphore_down_or_wait (pTHX_ struct CoroSLF *frame, int acquire) 2942slf_check_semaphore_down_or_wait (pTHX_ struct CoroSLF *frame, int acquire)
2644{ 2943{
2645 AV *av = (AV *)frame->data; 2944 AV *av = (AV *)frame->data;
2646 SV *count_sv = AvARRAY (av)[0]; 2945 SV *count_sv = AvARRAY (av)[0];
2946 SV *coro_hv = SvRV (coro_current);
2647 2947
2648 /* if we are about to throw, don't actually acquire the lock, just throw */ 2948 /* if we are about to throw, don't actually acquire the lock, just throw */
2649 if (CORO_THROW) 2949 if (CORO_THROW)
2650 return 0; 2950 return 0;
2651 else if (SvIVX (count_sv) > 0) 2951 else if (SvIVX (count_sv) > 0)
2652 { 2952 {
2653 SvSTATE_current->on_destroy = 0; 2953 frame->destroy = 0;
2654 2954
2655 if (acquire) 2955 if (acquire)
2656 SvIVX (count_sv) = SvIVX (count_sv) - 1; 2956 SvIVX (count_sv) = SvIVX (count_sv) - 1;
2657 else 2957 else
2658 coro_semaphore_adjust (aTHX_ av, 0); 2958 coro_semaphore_adjust (aTHX_ av, 0);
2663 { 2963 {
2664 int i; 2964 int i;
2665 /* if we were woken up but can't down, we look through the whole */ 2965 /* if we were woken up but can't down, we look through the whole */
2666 /* waiters list and only add us if we aren't in there already */ 2966 /* waiters list and only add us if we aren't in there already */
2667 /* this avoids some degenerate memory usage cases */ 2967 /* this avoids some degenerate memory usage cases */
2668 2968 for (i = AvFILLp (av); i > 0; --i) /* i > 0 is not an off-by-one bug */
2669 for (i = 1; i <= AvFILLp (av); ++i)
2670 if (AvARRAY (av)[i] == SvRV (coro_current)) 2969 if (AvARRAY (av)[i] == coro_hv)
2671 return 1; 2970 return 1;
2672 2971
2673 av_push (av, SvREFCNT_inc (SvRV (coro_current))); 2972 av_push (av, SvREFCNT_inc (coro_hv));
2674 return 1; 2973 return 1;
2675 } 2974 }
2676} 2975}
2677 2976
2678static int 2977static int
2701 { 3000 {
2702 av_push (av, SvREFCNT_inc (SvRV (coro_current))); 3001 av_push (av, SvREFCNT_inc (SvRV (coro_current)));
2703 3002
2704 frame->data = (void *)sv_2mortal (SvREFCNT_inc ((SV *)av)); 3003 frame->data = (void *)sv_2mortal (SvREFCNT_inc ((SV *)av));
2705 frame->prepare = prepare_schedule; 3004 frame->prepare = prepare_schedule;
2706
2707 /* to avoid race conditions when a woken-up coro gets terminated */ 3005 /* to avoid race conditions when a woken-up coro gets terminated */
2708 /* we arrange for a temporary on_destroy that calls adjust (0) */ 3006 /* we arrange for a temporary on_destroy that calls adjust (0) */
2709 SvSTATE_current->on_destroy = coro_semaphore_on_destroy; 3007 frame->destroy = coro_semaphore_destroy;
2710 } 3008 }
2711} 3009}
2712 3010
2713static void 3011static void
2714slf_init_semaphore_down (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) 3012slf_init_semaphore_down (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2722{ 3020{
2723 if (items >= 2) 3021 if (items >= 2)
2724 { 3022 {
2725 /* callback form */ 3023 /* callback form */
2726 AV *av = (AV *)SvRV (arg [0]); 3024 AV *av = (AV *)SvRV (arg [0]);
2727 CV *cb_cv = coro_sv_2cv (aTHX_ arg [1]); 3025 SV *cb_cv = s_get_cv_croak (arg [1]);
2728 3026
2729 av_push (av, SvREFCNT_inc_NN (cb_cv)); 3027 av_push (av, SvREFCNT_inc_NN (cb_cv));
2730 3028
2731 if (SvIVX (AvARRAY (av)[0]) > 0) 3029 if (SvIVX (AvARRAY (av)[0]) > 0)
2732 coro_semaphore_adjust (aTHX_ av, 0); 3030 coro_semaphore_adjust (aTHX_ av, 0);
2792{ 3090{
2793 AV *av = (AV *)SvRV (arg [0]); 3091 AV *av = (AV *)SvRV (arg [0]);
2794 3092
2795 if (items >= 2) 3093 if (items >= 2)
2796 { 3094 {
2797 CV *cb_cv = coro_sv_2cv (aTHX_ arg [1]); 3095 SV *cb_cv = s_get_cv_croak (arg [1]);
2798 av_push (av, SvREFCNT_inc_NN (cb_cv)); 3096 av_push (av, SvREFCNT_inc_NN (cb_cv));
2799 3097
2800 if (SvIVX (AvARRAY (av)[0])) 3098 if (SvIVX (AvARRAY (av)[0]))
2801 coro_signal_wake (aTHX_ av, 1); /* ust be the only waiter */ 3099 coro_signal_wake (aTHX_ av, 1); /* must be the only waiter */
2802 3100
2803 frame->prepare = prepare_nop; 3101 frame->prepare = prepare_nop;
2804 frame->check = slf_check_nop; 3102 frame->check = slf_check_nop;
2805 } 3103 }
2806 else if (SvIVX (AvARRAY (av)[0])) 3104 else if (SvIVX (AvARRAY (av)[0]))
2837 3135
2838static void 3136static void
2839coro_aio_callback (pTHX_ CV *cv) 3137coro_aio_callback (pTHX_ CV *cv)
2840{ 3138{
2841 dXSARGS; 3139 dXSARGS;
2842 AV *state = (AV *)GENSUB_ARG; 3140 AV *state = (AV *)S_GENSUB_ARG;
2843 SV *coro = av_pop (state); 3141 SV *coro = av_pop (state);
2844 SV *data_sv = newSV (sizeof (struct io_state)); 3142 SV *data_sv = newSV (sizeof (struct io_state));
2845 3143
2846 av_extend (state, items - 1); 3144 av_extend (state, items - 1);
2847 3145
2932 dSP; 3230 dSP;
2933 3231
2934 static SV *prio_cv; 3232 static SV *prio_cv;
2935 static SV *prio_sv; 3233 static SV *prio_sv;
2936 3234
2937 if (expect_false (!prio_cv)) 3235 if (ecb_expect_false (!prio_cv))
2938 { 3236 {
2939 prio_cv = (SV *)get_cv ("IO::AIO::aioreq_pri", 0); 3237 prio_cv = (SV *)get_cv ("IO::AIO::aioreq_pri", 0);
2940 prio_sv = newSViv (0); 3238 prio_sv = newSViv (0);
2941 } 3239 }
2942 3240
2961 3259
2962 for (i = 0; i < items; ++i) 3260 for (i = 0; i < items; ++i)
2963 PUSHs (arg [i]); 3261 PUSHs (arg [i]);
2964 3262
2965 /* now push the callback closure */ 3263 /* now push the callback closure */
2966 PUSHs (sv_2mortal (gensub (aTHX_ coro_aio_callback, (void *)SvREFCNT_inc_NN ((SV *)state)))); 3264 PUSHs (sv_2mortal (s_gensub (aTHX_ coro_aio_callback, (void *)SvREFCNT_inc_NN ((SV *)state))));
2967 3265
2968 /* now call the AIO function - we assume our request is uncancelable */ 3266 /* now call the AIO function - we assume our request is uncancelable */
2969 PUTBACK; 3267 PUTBACK;
2970 call_sv ((SV *)req, G_VOID | G_DISCARD); 3268 call_sv ((SV *)req, G_VOID | G_DISCARD);
2971 } 3269 }
2972 3270
2973 /* now that the requets is going, we loop toll we have a result */ 3271 /* now that the request is going, we loop till we have a result */
2974 frame->data = (void *)state; 3272 frame->data = (void *)state;
2975 frame->prepare = prepare_schedule; 3273 frame->prepare = prepare_schedule;
2976 frame->check = slf_check_aio_req; 3274 frame->check = slf_check_aio_req;
2977} 3275}
2978 3276
2988 3286
2989/*****************************************************************************/ 3287/*****************************************************************************/
2990 3288
2991#if CORO_CLONE 3289#if CORO_CLONE
2992# include "clone.c" 3290# include "clone.c"
3291#endif
3292
3293/*****************************************************************************/
3294
3295static SV *
3296coro_new (pTHX_ HV *stash, SV **argv, int argc, int is_coro)
3297{
3298 SV *coro_sv;
3299 struct coro *coro;
3300 MAGIC *mg;
3301 HV *hv;
3302 SV *cb;
3303 int i;
3304
3305 if (argc > 0)
3306 {
3307 cb = s_get_cv_croak (argv [0]);
3308
3309 if (!is_coro)
3310 {
3311 if (CvISXSUB (cb))
3312 croak ("Coro::State doesn't support XS functions as coroutine start, caught");
3313
3314 if (!CvROOT (cb))
3315 croak ("Coro::State doesn't support autoloaded or undefined functions as coroutine start, caught");
3316 }
3317 }
3318
3319 Newz (0, coro, 1, struct coro);
3320 coro->args = newAV ();
3321 coro->flags = CF_NEW;
3322
3323 if (coro_first) coro_first->prev = coro;
3324 coro->next = coro_first;
3325 coro_first = coro;
3326
3327 coro->hv = hv = newHV ();
3328 mg = sv_magicext ((SV *)hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)coro, 0);
3329 mg->mg_flags |= MGf_DUP;
3330 coro_sv = sv_bless (newRV_noinc ((SV *)hv), stash);
3331
3332 if (argc > 0)
3333 {
3334 av_extend (coro->args, argc + is_coro - 1);
3335
3336 if (is_coro)
3337 {
3338 av_push (coro->args, SvREFCNT_inc_NN ((SV *)cb));
3339 cb = (SV *)cv_coro_run;
3340 }
3341
3342 coro->startcv = (CV *)SvREFCNT_inc_NN ((SV *)cb);
3343
3344 for (i = 1; i < argc; i++)
3345 av_push (coro->args, newSVsv (argv [i]));
3346 }
3347
3348 return coro_sv;
3349}
3350
3351#ifndef __cplusplus
3352ecb_cold XS(boot_Coro__State);
3353#endif
3354
3355#if CORO_JIT
3356
3357static void ecb_noinline ecb_cold
3358pushav_4uv (pTHX_ UV a, UV b, UV c, UV d)
3359{
3360 dSP;
3361 AV *av = newAV ();
3362
3363 av_store (av, 3, newSVuv (d));
3364 av_store (av, 2, newSVuv (c));
3365 av_store (av, 1, newSVuv (b));
3366 av_store (av, 0, newSVuv (a));
3367
3368 XPUSHs (sv_2mortal (newRV_noinc ((SV *)av)));
3369
3370 PUTBACK;
3371}
3372
3373static void ecb_noinline ecb_cold
3374jit_init (pTHX)
3375{
3376 dSP;
3377 SV *load, *save;
3378 char *map_base;
3379 char *load_ptr, *save_ptr;
3380 STRLEN load_len, save_len, map_len;
3381 int count;
3382
3383 eval_pv ("require 'Coro/jit-" CORO_JIT_TYPE ".pl'", 1);
3384
3385 PUSHMARK (SP);
3386#define VARx(name,expr,type) pushav_4uv (aTHX_ (UV)&(expr), sizeof (expr), offsetof (perl_slots, name), sizeof (type));
3387# include "state.h"
3388#undef VARx
3389 count = call_pv ("Coro::State::_jit", G_ARRAY);
3390 SPAGAIN;
3391
3392 save = POPs; save_ptr = SvPVbyte (save, save_len);
3393 load = POPs; load_ptr = SvPVbyte (load, load_len);
3394
3395 map_len = load_len + save_len + 16;
3396
3397 map_base = mmap (0, map_len, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
3398
3399 assert (("Coro: unable to mmap jit code page, cannot continue.", map_base != (char *)MAP_FAILED));
3400
3401 load_perl_slots = (load_save_perl_slots_type)map_base;
3402 memcpy (map_base, load_ptr, load_len);
3403
3404 map_base += (load_len + 15) & ~15;
3405
3406 save_perl_slots = (load_save_perl_slots_type)map_base;
3407 memcpy (map_base, save_ptr, save_len);
3408
3409 /* we are good citizens and try to make the page read-only, so the evil evil */
3410 /* hackers might have it a bit more difficult */
3411 mprotect (map_base, map_len, PROT_READ | PROT_EXEC);
3412
3413 PUTBACK;
3414 eval_pv ("undef &Coro::State::_jit", 1);
3415}
3416
2993#endif 3417#endif
2994 3418
2995MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_ 3419MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_
2996 3420
2997PROTOTYPES: DISABLE 3421PROTOTYPES: DISABLE
3002# if CORO_PTHREAD 3426# if CORO_PTHREAD
3003 coro_thx = PERL_GET_CONTEXT; 3427 coro_thx = PERL_GET_CONTEXT;
3004# endif 3428# endif
3005#endif 3429#endif
3006 BOOT_PAGESIZE; 3430 BOOT_PAGESIZE;
3431
3432 /* perl defines these to check for existance first, but why it doesn't */
3433 /* just create them one at init time is not clear to me, except for */
3434 /* programs trying to delete them, but... */
3435 /* anyway, we declare this as invalid and make sure they are initialised here */
3436 DEFSV;
3437 ERRSV;
3007 3438
3008 cctx_current = cctx_new_empty (); 3439 cctx_current = cctx_new_empty ();
3009 3440
3010 irsgv = gv_fetchpv ("/" , GV_ADD|GV_NOTQUAL, SVt_PV); 3441 irsgv = gv_fetchpv ("/" , GV_ADD|GV_NOTQUAL, SVt_PV);
3011 stdoutgv = gv_fetchpv ("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO); 3442 stdoutgv = gv_fetchpv ("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO);
3051 coroapi.prepare_nop = prepare_nop; 3482 coroapi.prepare_nop = prepare_nop;
3052 coroapi.prepare_schedule = prepare_schedule; 3483 coroapi.prepare_schedule = prepare_schedule;
3053 coroapi.prepare_cede = prepare_cede; 3484 coroapi.prepare_cede = prepare_cede;
3054 coroapi.prepare_cede_notself = prepare_cede_notself; 3485 coroapi.prepare_cede_notself = prepare_cede_notself;
3055 3486
3056 { 3487 time_init (aTHX);
3057 SV **svp = hv_fetch (PL_modglobal, "Time::NVtime", 12, 0);
3058
3059 if (!svp) croak ("Time::HiRes is required");
3060 if (!SvIOK (*svp)) croak ("Time::NVtime isn't a function pointer");
3061
3062 nvtime = INT2PTR (double (*)(), SvIV (*svp));
3063
3064 svp = hv_fetch (PL_modglobal, "Time::U2time", 12, 0);
3065 u2time = INT2PTR (void (*)(pTHX_ UV ret[2]), SvIV (*svp));
3066 }
3067 3488
3068 assert (("PRIO_NORMAL must be 0", !CORO_PRIO_NORMAL)); 3489 assert (("PRIO_NORMAL must be 0", !CORO_PRIO_NORMAL));
3490#if CORO_JIT
3491 PUTBACK;
3492 jit_init (aTHX);
3493 SPAGAIN;
3494#endif
3069} 3495}
3070 3496
3071SV * 3497SV *
3072new (char *klass, ...) 3498new (SV *klass, ...)
3073 ALIAS: 3499 ALIAS:
3074 Coro::new = 1 3500 Coro::new = 1
3075 CODE: 3501 CODE:
3076{ 3502 RETVAL = coro_new (aTHX_ ix ? coro_stash : coro_state_stash, &ST (1), items - 1, ix);
3077 struct coro *coro; 3503 OUTPUT:
3078 MAGIC *mg;
3079 HV *hv;
3080 CV *cb;
3081 int i;
3082
3083 if (items > 1)
3084 {
3085 cb = coro_sv_2cv (aTHX_ ST (1));
3086
3087 if (!ix)
3088 {
3089 if (CvISXSUB (cb))
3090 croak ("Coro::State doesn't support XS functions as coroutine start, caught");
3091
3092 if (!CvROOT (cb))
3093 croak ("Coro::State doesn't support autoloaded or undefined functions as coroutine start, caught");
3094 }
3095 }
3096
3097 Newz (0, coro, 1, struct coro);
3098 coro->args = newAV ();
3099 coro->flags = CF_NEW;
3100
3101 if (coro_first) coro_first->prev = coro;
3102 coro->next = coro_first;
3103 coro_first = coro;
3104
3105 coro->hv = hv = newHV ();
3106 mg = sv_magicext ((SV *)hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)coro, 0);
3107 mg->mg_flags |= MGf_DUP;
3108 RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1));
3109
3110 if (items > 1)
3111 {
3112 av_extend (coro->args, items - 1 + ix - 1);
3113
3114 if (ix)
3115 {
3116 av_push (coro->args, SvREFCNT_inc_NN ((SV *)cb));
3117 cb = cv_coro_run;
3118 }
3119
3120 coro->startcv = (CV *)SvREFCNT_inc_NN ((SV *)cb);
3121
3122 for (i = 2; i < items; i++)
3123 av_push (coro->args, newSVsv (ST (i)));
3124 }
3125}
3126 OUTPUT:
3127 RETVAL 3504 RETVAL
3128 3505
3129void 3506void
3130transfer (...) 3507transfer (...)
3131 PROTOTYPE: $$ 3508 PROTOTYPE: $$
3132 CODE: 3509 CODE:
3133 CORO_EXECUTE_SLF_XS (slf_init_transfer); 3510 CORO_EXECUTE_SLF_XS (slf_init_transfer);
3134
3135bool
3136_destroy (SV *coro_sv)
3137 CODE:
3138 RETVAL = coro_state_destroy (aTHX_ SvSTATE (coro_sv));
3139 OUTPUT:
3140 RETVAL
3141 3511
3142void 3512void
3143_exit (int code) 3513_exit (int code)
3144 PROTOTYPE: $ 3514 PROTOTYPE: $
3145 CODE: 3515 CODE:
3221 CODE: 3591 CODE:
3222{ 3592{
3223 if (coro->mainstack && ((coro->flags & CF_RUNNING) || coro->slot)) 3593 if (coro->mainstack && ((coro->flags & CF_RUNNING) || coro->slot))
3224 { 3594 {
3225 struct coro *current = SvSTATE_current; 3595 struct coro *current = SvSTATE_current;
3596 struct CoroSLF slf_save;
3226 3597
3227 if (current != coro) 3598 if (current != coro)
3228 { 3599 {
3229 PUTBACK; 3600 PUTBACK;
3230 save_perl (aTHX_ current); 3601 save_perl (aTHX_ current);
3231 load_perl (aTHX_ coro); 3602 load_perl (aTHX_ coro);
3603 /* the coro is most likely in an active SLF call.
3604 * while not strictly required (the code we execute is
3605 * not allowed to call any SLF functions), it's cleaner
3606 * to reinitialise the slf_frame and restore it later.
3607 * This might one day allow us to actually do SLF calls
3608 * from code executed here.
3609 */
3610 slf_save = slf_frame;
3611 slf_frame.prepare = 0;
3232 SPAGAIN; 3612 SPAGAIN;
3233 } 3613 }
3234 3614
3235 PUSHSTACK; 3615 PUSHSTACK;
3236 3616
3246 SPAGAIN; 3626 SPAGAIN;
3247 3627
3248 if (current != coro) 3628 if (current != coro)
3249 { 3629 {
3250 PUTBACK; 3630 PUTBACK;
3631 slf_frame = slf_save;
3251 save_perl (aTHX_ coro); 3632 save_perl (aTHX_ coro);
3252 load_perl (aTHX_ current); 3633 load_perl (aTHX_ current);
3253 SPAGAIN; 3634 SPAGAIN;
3254 } 3635 }
3255 } 3636 }
3260 PROTOTYPE: $ 3641 PROTOTYPE: $
3261 ALIAS: 3642 ALIAS:
3262 is_ready = CF_READY 3643 is_ready = CF_READY
3263 is_running = CF_RUNNING 3644 is_running = CF_RUNNING
3264 is_new = CF_NEW 3645 is_new = CF_NEW
3265 is_destroyed = CF_DESTROYED 3646 is_destroyed = CF_ZOMBIE
3647 is_zombie = CF_ZOMBIE
3266 is_suspended = CF_SUSPENDED 3648 is_suspended = CF_SUSPENDED
3267 CODE: 3649 CODE:
3268 RETVAL = boolSV (coro->flags & ix); 3650 RETVAL = boolSV (coro->flags & ix);
3269 OUTPUT: 3651 OUTPUT:
3270 RETVAL 3652 RETVAL
3271 3653
3272void 3654void
3273throw (Coro::State self, SV *throw = &PL_sv_undef) 3655throw (Coro::State self, SV *exception = &PL_sv_undef)
3274 PROTOTYPE: $;$ 3656 PROTOTYPE: $;$
3275 CODE: 3657 CODE:
3276{ 3658{
3277 struct coro *current = SvSTATE_current; 3659 struct coro *current = SvSTATE_current;
3278 SV **throwp = self == current ? &CORO_THROW : &self->except; 3660 SV **exceptionp = self == current ? &CORO_THROW : &self->except;
3279 SvREFCNT_dec (*throwp); 3661 SvREFCNT_dec (*exceptionp);
3280 SvGETMAGIC (throw); 3662 SvGETMAGIC (exception);
3281 *throwp = SvOK (throw) ? newSVsv (throw) : 0; 3663 *exceptionp = SvOK (exception) ? newSVsv (exception) : 0;
3282} 3664}
3283 3665
3284void 3666void
3285api_trace (SV *coro, int flags = CC_TRACE | CC_TRACE_SUB) 3667api_trace (SV *coro, int flags = CC_TRACE | CC_TRACE_SUB)
3286 PROTOTYPE: $;$ 3668 PROTOTYPE: $;$
3341 3723
3342void 3724void
3343cancel (Coro::State self) 3725cancel (Coro::State self)
3344 CODE: 3726 CODE:
3345 coro_state_destroy (aTHX_ self); 3727 coro_state_destroy (aTHX_ self);
3346 coro_call_on_destroy (aTHX_ self); /* actually only for Coro objects */
3347
3348 3728
3349SV * 3729SV *
3350enable_times (int enabled = enable_times) 3730enable_times (int enabled = enable_times)
3351 CODE: 3731 CODE:
3352{ 3732{
3367times (Coro::State self) 3747times (Coro::State self)
3368 PPCODE: 3748 PPCODE:
3369{ 3749{
3370 struct coro *current = SvSTATE (coro_current); 3750 struct coro *current = SvSTATE (coro_current);
3371 3751
3372 if (expect_false (current == self)) 3752 if (ecb_expect_false (current == self))
3373 { 3753 {
3374 coro_times_update (); 3754 coro_times_update ();
3375 coro_times_add (SvSTATE (coro_current)); 3755 coro_times_add (SvSTATE (coro_current));
3376 } 3756 }
3377 3757
3378 EXTEND (SP, 2); 3758 EXTEND (SP, 2);
3379 PUSHs (sv_2mortal (newSVnv (self->t_real [0] + self->t_real [1] * 1e-9))); 3759 PUSHs (sv_2mortal (newSVnv (self->t_real [0] + self->t_real [1] * 1e-9)));
3380 PUSHs (sv_2mortal (newSVnv (self->t_cpu [0] + self->t_cpu [1] * 1e-9))); 3760 PUSHs (sv_2mortal (newSVnv (self->t_cpu [0] + self->t_cpu [1] * 1e-9)));
3381 3761
3382 if (expect_false (current == self)) 3762 if (ecb_expect_false (current == self))
3383 coro_times_sub (SvSTATE (coro_current)); 3763 coro_times_sub (SvSTATE (coro_current));
3384} 3764}
3765
3766void
3767swap_sv (Coro::State coro, SV *sv, SV *swapsv)
3768 CODE:
3769{
3770 struct coro *current = SvSTATE_current;
3771
3772 if (current == coro)
3773 SWAP_SVS (current);
3774
3775 if (!coro->swap_sv)
3776 coro->swap_sv = newAV ();
3777
3778 av_push (coro->swap_sv, SvREFCNT_inc_NN (SvRV (sv )));
3779 av_push (coro->swap_sv, SvREFCNT_inc_NN (SvRV (swapsv)));
3780
3781 if (current == coro)
3782 SWAP_SVS (current);
3783}
3784
3385 3785
3386MODULE = Coro::State PACKAGE = Coro 3786MODULE = Coro::State PACKAGE = Coro
3387 3787
3388BOOT: 3788BOOT:
3389{ 3789{
3390 sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE); 3790 sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE);
3391 sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE); 3791 sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE);
3392 cv_coro_run = get_cv ( "Coro::_coro_run" , GV_ADD); 3792 cv_coro_run = get_cv ( "Coro::_coro_run" , GV_ADD);
3393 cv_coro_terminate = get_cv ( "Coro::terminate" , GV_ADD);
3394 coro_current = coro_get_sv (aTHX_ "Coro::current" , FALSE); SvREADONLY_on (coro_current); 3793 coro_current = coro_get_sv (aTHX_ "Coro::current" , FALSE); SvREADONLY_on (coro_current);
3395 av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE); 3794 av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE);
3396 av_destroy = coro_get_av (aTHX_ "Coro::destroy" , TRUE); 3795 av_destroy = coro_get_av (aTHX_ "Coro::destroy" , TRUE);
3397 sv_manager = coro_get_sv (aTHX_ "Coro::manager" , TRUE); 3796 sv_manager = coro_get_sv (aTHX_ "Coro::manager" , TRUE);
3398 sv_idle = coro_get_sv (aTHX_ "Coro::idle" , TRUE); 3797 sv_idle = coro_get_sv (aTHX_ "Coro::idle" , TRUE);
3399 3798
3400 sv_async_pool_idle = newSVpv ("[async pool idle]", 0); SvREADONLY_on (sv_async_pool_idle); 3799 sv_async_pool_idle = newSVpv ("[async pool idle]", 0); SvREADONLY_on (sv_async_pool_idle);
3401 sv_Coro = newSVpv ("Coro", 0); SvREADONLY_on (sv_Coro); 3800 sv_Coro = newSVpv ("Coro", 0); SvREADONLY_on (sv_Coro);
3402 cv_pool_handler = get_cv ("Coro::pool_handler", GV_ADD); SvREADONLY_on (cv_pool_handler); 3801 cv_pool_handler = get_cv ("Coro::pool_handler", GV_ADD); SvREADONLY_on (cv_pool_handler);
3403 cv_coro_state_new = get_cv ("Coro::State::new", 0); SvREADONLY_on (cv_coro_state_new); 3802 CvNODEBUG_on (get_cv ("Coro::_pool_handler", 0)); /* work around a debugger bug */
3404 3803
3405 coro_stash = gv_stashpv ("Coro", TRUE); 3804 coro_stash = gv_stashpv ("Coro", TRUE);
3406 3805
3407 newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (CORO_PRIO_MAX)); 3806 newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (CORO_PRIO_MAX));
3408 newCONSTSUB (coro_stash, "PRIO_HIGH", newSViv (CORO_PRIO_HIGH)); 3807 newCONSTSUB (coro_stash, "PRIO_HIGH", newSViv (CORO_PRIO_HIGH));
3409 newCONSTSUB (coro_stash, "PRIO_NORMAL", newSViv (CORO_PRIO_NORMAL)); 3808 newCONSTSUB (coro_stash, "PRIO_NORMAL", newSViv (CORO_PRIO_NORMAL));
3427 sv_setiv (sv, (IV)&coroapi); 3826 sv_setiv (sv, (IV)&coroapi);
3428 SvREADONLY_on (sv); 3827 SvREADONLY_on (sv);
3429 } 3828 }
3430} 3829}
3431 3830
3831SV *
3832async (...)
3833 PROTOTYPE: &@
3834 CODE:
3835 RETVAL = coro_new (aTHX_ coro_stash, &ST (0), items, 1);
3836 api_ready (aTHX_ RETVAL);
3837 OUTPUT:
3838 RETVAL
3839
3840void
3841_destroy (Coro::State coro)
3842 CODE:
3843 /* used by the manager thread */
3844 coro_state_destroy (aTHX_ coro);
3845
3846void
3847on_destroy (Coro::State coro, SV *cb)
3848 CODE:
3849 coro_push_on_destroy (aTHX_ coro, newSVsv (cb));
3850
3851void
3852join (...)
3853 CODE:
3854 CORO_EXECUTE_SLF_XS (slf_init_join);
3855
3432void 3856void
3433terminate (...) 3857terminate (...)
3434 CODE: 3858 CODE:
3435 CORO_EXECUTE_SLF_XS (slf_init_terminate); 3859 CORO_EXECUTE_SLF_XS (slf_init_terminate);
3860
3861void
3862cancel (...)
3863 CODE:
3864 CORO_EXECUTE_SLF_XS (slf_init_cancel);
3865
3866int
3867safe_cancel (Coro::State self, ...)
3868 C_ARGS: aTHX_ self, &ST (1), items - 1
3436 3869
3437void 3870void
3438schedule (...) 3871schedule (...)
3439 CODE: 3872 CODE:
3440 CORO_EXECUTE_SLF_XS (slf_init_schedule); 3873 CORO_EXECUTE_SLF_XS (slf_init_schedule);
3470_set_readyhook (SV *hook) 3903_set_readyhook (SV *hook)
3471 PROTOTYPE: $ 3904 PROTOTYPE: $
3472 CODE: 3905 CODE:
3473 SvREFCNT_dec (coro_readyhook); 3906 SvREFCNT_dec (coro_readyhook);
3474 SvGETMAGIC (hook); 3907 SvGETMAGIC (hook);
3908 if (SvOK (hook))
3909 {
3475 coro_readyhook = SvOK (hook) ? newSVsv (hook) : 0; 3910 coro_readyhook = newSVsv (hook);
3911 CORO_READYHOOK = invoke_sv_ready_hook_helper;
3912 }
3913 else
3914 {
3915 coro_readyhook = 0;
3916 CORO_READYHOOK = 0;
3917 }
3476 3918
3477int 3919int
3478prio (Coro::State coro, int newprio = 0) 3920prio (Coro::State coro, int newprio = 0)
3479 PROTOTYPE: $;$ 3921 PROTOTYPE: $;$
3480 ALIAS: 3922 ALIAS:
3544 for (i = 1; i < items; ++i) 3986 for (i = 1; i < items; ++i)
3545 av_push (av, SvREFCNT_inc_NN (ST (i))); 3987 av_push (av, SvREFCNT_inc_NN (ST (i)));
3546 3988
3547 if ((SV *)hv == &PL_sv_undef) 3989 if ((SV *)hv == &PL_sv_undef)
3548 { 3990 {
3549 PUSHMARK (SP); 3991 SV *sv = coro_new (aTHX_ coro_stash, (SV **)&cv_pool_handler, 1, 1);
3550 EXTEND (SP, 2);
3551 PUSHs (sv_Coro);
3552 PUSHs ((SV *)cv_pool_handler);
3553 PUTBACK;
3554 call_sv ((SV *)cv_coro_state_new, G_SCALAR);
3555 SPAGAIN;
3556
3557 hv = (HV *)SvREFCNT_inc_NN (SvRV (POPs)); 3992 hv = (HV *)SvREFCNT_inc_NN (SvRV (sv));
3993 SvREFCNT_dec (sv);
3558 } 3994 }
3559 3995
3560 { 3996 {
3561 struct coro *coro = SvSTATE_hv (hv); 3997 struct coro *coro = SvSTATE_hv (hv);
3562 3998
3596 CODE: 4032 CODE:
3597{ 4033{
3598 struct coro *coro = SvSTATE_current; 4034 struct coro *coro = SvSTATE_current;
3599 AV **avp = ix ? &coro->on_leave : &coro->on_enter; 4035 AV **avp = ix ? &coro->on_leave : &coro->on_enter;
3600 4036
3601 block = (SV *)coro_sv_2cv (aTHX_ block); 4037 block = s_get_cv_croak (block);
3602 4038
3603 if (!*avp) 4039 if (!*avp)
3604 *avp = newAV (); 4040 *avp = newAV ();
3605 4041
3606 av_push (*avp, SvREFCNT_inc (block)); 4042 av_push (*avp, SvREFCNT_inc (block));
3713} 4149}
3714 4150
3715MODULE = Coro::State PACKAGE = Coro::SemaphoreSet 4151MODULE = Coro::State PACKAGE = Coro::SemaphoreSet
3716 4152
3717void 4153void
3718_may_delete (SV *sem, int count, int extra_refs) 4154_may_delete (SV *sem, int count, unsigned int extra_refs)
3719 PPCODE: 4155 PPCODE:
3720{ 4156{
3721 AV *av = (AV *)SvRV (sem); 4157 AV *av = (AV *)SvRV (sem);
3722 4158
3723 if (SvREFCNT ((SV *)av) == 1 + extra_refs 4159 if (SvREFCNT ((SV *)av) == 1 + extra_refs
3806 4242
3807void 4243void
3808_register (char *target, char *proto, SV *req) 4244_register (char *target, char *proto, SV *req)
3809 CODE: 4245 CODE:
3810{ 4246{
3811 CV *req_cv = coro_sv_2cv (aTHX_ req); 4247 SV *req_cv = s_get_cv_croak (req);
3812 /* newXSproto doesn't return the CV on 5.8 */ 4248 /* newXSproto doesn't return the CV on 5.8 */
3813 CV *slf_cv = newXS (target, coro_aio_req_xs, __FILE__); 4249 CV *slf_cv = newXS (target, coro_aio_req_xs, __FILE__);
3814 sv_setpv ((SV *)slf_cv, proto); 4250 sv_setpv ((SV *)slf_cv, proto);
3815 sv_magicext ((SV *)slf_cv, (SV *)req_cv, CORO_MAGIC_type_aio, 0, 0, 0); 4251 sv_magicext ((SV *)slf_cv, (SV *)req_cv, CORO_MAGIC_type_aio, 0, 0, 0);
3816} 4252}
3817 4253
4254MODULE = Coro::State PACKAGE = Coro::Select
4255
4256void
4257patch_pp_sselect ()
4258 CODE:
4259 if (!coro_old_pp_sselect)
4260 {
4261 coro_select_select = (SV *)get_cv ("Coro::Select::select", 0);
4262 coro_old_pp_sselect = PL_ppaddr [OP_SSELECT];
4263 PL_ppaddr [OP_SSELECT] = coro_pp_sselect;
4264 }
4265
4266void
4267unpatch_pp_sselect ()
4268 CODE:
4269 if (coro_old_pp_sselect)
4270 {
4271 PL_ppaddr [OP_SSELECT] = coro_old_pp_sselect;
4272 coro_old_pp_sselect = 0;
4273 }
4274

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines