]> git.vpit.fr Git - perl/modules/indirect.git/blob - indirect.xs
Also test no indirect fatal and compilation errors in require
[perl/modules/indirect.git] / indirect.xs
1 /* This file is part of the indirect Perl module.
2  * See http://search.cpan.org/dist/indirect/ */
3
4 #define PERL_NO_GET_CONTEXT
5 #include "EXTERN.h"
6 #include "perl.h"
7 #include "XSUB.h"
8
9 #define __PACKAGE__     "indirect"
10 #define __PACKAGE_LEN__ (sizeof(__PACKAGE__)-1)
11
12 /* --- Compatibility wrappers ---------------------------------------------- */
13
14 #ifndef NOOP
15 # define NOOP
16 #endif
17
18 #ifndef dNOOP
19 # define dNOOP
20 #endif
21
22 #ifndef Newx
23 # define Newx(v, n, c) New(0, v, n, c)
24 #endif
25
26 #ifndef SvPV_const
27 # define SvPV_const SvPV
28 #endif
29
30 #ifndef SvPV_nolen_const
31 # define SvPV_nolen_const SvPV_nolen
32 #endif
33
34 #ifndef SvPVX_const
35 # define SvPVX_const SvPVX
36 #endif
37
38 #ifndef SvREFCNT_inc_simple_void_NN
39 # ifdef SvREFCNT_inc_simple_NN
40 #  define SvREFCNT_inc_simple_void_NN SvREFCNT_inc_simple_NN
41 # else
42 #  define SvREFCNT_inc_simple_void_NN SvREFCNT_inc
43 # endif
44 #endif
45
46 #ifndef sv_catpvn_nomg
47 # define sv_catpvn_nomg sv_catpvn
48 #endif
49
50 #ifndef mPUSHp
51 # define mPUSHp(P, L) PUSHs(sv_2mortal(newSVpvn((P), (L))))
52 #endif
53
54 #ifndef mPUSHu
55 # define mPUSHu(U) PUSHs(sv_2mortal(newSVuv(U)))
56 #endif
57
58 #ifndef HvNAME_get
59 # define HvNAME_get(H) HvNAME(H)
60 #endif
61
62 #ifndef HvNAMELEN_get
63 # define HvNAMELEN_get(H) strlen(HvNAME_get(H))
64 #endif
65
66 #ifndef OpSIBLING
67 # ifdef OP_SIBLING
68 #  define OpSIBLING(O) OP_SIBLING(O)
69 # else
70 #  define OpSIBLING(O) ((O)->op_sibling)
71 # endif
72 #endif
73
74 #define I_HAS_PERL(R, V, S) (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S))))))
75
76 #if I_HAS_PERL(5, 10, 0) || defined(PL_parser)
77 # ifndef PL_linestr
78 #  define PL_linestr PL_parser->linestr
79 # endif
80 # ifndef PL_bufptr
81 #  define PL_bufptr PL_parser->bufptr
82 # endif
83 # ifndef PL_oldbufptr
84 #  define PL_oldbufptr PL_parser->oldbufptr
85 # endif
86 # ifndef PL_lex_inwhat
87 #  define PL_lex_inwhat PL_parser->lex_inwhat
88 # endif
89 #else
90 # ifndef PL_linestr
91 #  define PL_linestr PL_Ilinestr
92 # endif
93 # ifndef PL_bufptr
94 #  define PL_bufptr PL_Ibufptr
95 # endif
96 # ifndef PL_oldbufptr
97 #  define PL_oldbufptr PL_Ioldbufptr
98 # endif
99 # ifndef PL_lex_inwhat
100 #  define PL_lex_inwhat PL_Ilex_inwhat
101 # endif
102 #endif
103
104 #ifndef I_WORKAROUND_REQUIRE_PROPAGATION
105 # define I_WORKAROUND_REQUIRE_PROPAGATION !I_HAS_PERL(5, 10, 1)
106 #endif
107
108 /* ... Thread safety and multiplicity ...................................... */
109
110 /* Safe unless stated otherwise in Makefile.PL */
111 #ifndef I_FORKSAFE
112 # define I_FORKSAFE 1
113 #endif
114
115 #ifndef I_MULTIPLICITY
116 # if defined(MULTIPLICITY)
117 #  define I_MULTIPLICITY 1
118 # else
119 #  define I_MULTIPLICITY 0
120 # endif
121 #endif
122 #if I_MULTIPLICITY
123 # ifndef PERL_IMPLICIT_CONTEXT
124 #  error MULTIPLICITY builds must set PERL_IMPLICIT_CONTEXT
125 # endif
126 #endif
127 #if I_MULTIPLICITY && !defined(tTHX)
128 # define tTHX PerlInterpreter*
129 #endif
130
131 #if I_MULTIPLICITY && defined(USE_ITHREADS) && defined(dMY_CXT) && defined(MY_CXT) && defined(START_MY_CXT) && defined(MY_CXT_INIT) && (defined(MY_CXT_CLONE) || defined(dMY_CXT_SV))
132 # define I_THREADSAFE 1
133 # ifndef MY_CXT_CLONE
134 #  define MY_CXT_CLONE \
135     dMY_CXT_SV;                                                      \
136     my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1)); \
137     Copy(INT2PTR(my_cxt_t*, SvUV(my_cxt_sv)), my_cxtp, 1, my_cxt_t); \
138     sv_setuv(my_cxt_sv, PTR2UV(my_cxtp))
139 # endif
140 #else
141 # define I_THREADSAFE 0
142 # undef  dMY_CXT
143 # define dMY_CXT      dNOOP
144 # undef  MY_CXT
145 # define MY_CXT       indirect_globaldata
146 # undef  START_MY_CXT
147 # define START_MY_CXT static my_cxt_t MY_CXT;
148 # undef  MY_CXT_INIT
149 # define MY_CXT_INIT  NOOP
150 # undef  MY_CXT_CLONE
151 # define MY_CXT_CLONE NOOP
152 #endif
153
154 #if I_THREADSAFE
155 /* We must use preexistent global mutexes or we will never be able to destroy
156  * them. */
157 # if I_HAS_PERL(5, 9, 3)
158 #  define I_LOADED_LOCK   MUTEX_LOCK(&PL_my_ctx_mutex)
159 #  define I_LOADED_UNLOCK MUTEX_UNLOCK(&PL_my_ctx_mutex)
160 # else
161 #  define I_LOADED_LOCK   OP_REFCNT_LOCK
162 #  define I_LOADED_UNLOCK OP_REFCNT_UNLOCK
163 # endif
164 #else
165 # define I_LOADED_LOCK   NOOP
166 # define I_LOADED_UNLOCK NOOP
167 #endif
168
169 #if defined(OP_CHECK_MUTEX_LOCK) && defined(OP_CHECK_MUTEX_UNLOCK)
170 # define I_CHECK_LOCK   OP_CHECK_MUTEX_LOCK
171 # define I_CHECK_UNLOCK OP_CHECK_MUTEX_UNLOCK
172 #elif I_HAS_PERL(5, 9, 3)
173 # define I_CHECK_LOCK   OP_REFCNT_LOCK
174 # define I_CHECK_UNLOCK OP_REFCNT_UNLOCK
175 #else
176 /* Before perl 5.9.3, indirect_ck_*() calls are already protected by the
177  * I_LOADED mutex, which falls back to the OP_REFCNT mutex. Make sure we don't
178  * lock it twice. */
179 # define I_CHECK_LOCK   NOOP
180 # define I_CHECK_UNLOCK NOOP
181 #endif
182
183 typedef OP *(*indirect_ck_t)(pTHX_ OP *);
184
185 #ifdef wrap_op_checker
186
187 # define indirect_ck_replace(T, NC, OCP) wrap_op_checker((T), (NC), (OCP))
188
189 #else
190
191 static void indirect_ck_replace(pTHX_ OPCODE type, indirect_ck_t new_ck, indirect_ck_t *old_ck_p) {
192 #define indirect_ck_replace(T, NC, OCP) indirect_ck_replace(aTHX_ (T), (NC), (OCP))
193  I_CHECK_LOCK;
194  if (!*old_ck_p) {
195   *old_ck_p      = PL_check[type];
196   PL_check[type] = new_ck;
197  }
198  I_CHECK_UNLOCK;
199 }
200
201 #endif
202
203 static void indirect_ck_restore(pTHX_ OPCODE type, indirect_ck_t *old_ck_p) {
204 #define indirect_ck_restore(T, OCP) indirect_ck_restore(aTHX_ (T), (OCP))
205  I_CHECK_LOCK;
206  if (*old_ck_p) {
207   PL_check[type] = *old_ck_p;
208   *old_ck_p      = 0;
209  }
210  I_CHECK_UNLOCK;
211 }
212
213 /* --- Helpers ------------------------------------------------------------- */
214
215 /* ... Check if the module is loaded ....................................... */
216
217 static I32 indirect_loaded = 0;
218
219 #if I_THREADSAFE
220
221 #define PTABLE_NAME        ptable_loaded
222 #define PTABLE_NEED_DELETE 1
223 #define PTABLE_NEED_WALK   0
224
225 #include "ptable.h"
226
227 #define ptable_loaded_store(T, K, V) ptable_loaded_store(aPTBLMS_ (T), (K), (V))
228 #define ptable_loaded_delete(T, K)   ptable_loaded_delete(aPTBLMS_ (T), (K))
229 #define ptable_loaded_free(T)        ptable_loaded_free(aPTBLMS_ (T))
230
231 static ptable *indirect_loaded_cxts = NULL;
232
233 static int indirect_is_loaded(pTHX_ void *cxt) {
234 #define indirect_is_loaded(C) indirect_is_loaded(aTHX_ (C))
235  int res = 0;
236
237  I_LOADED_LOCK;
238  if (indirect_loaded_cxts && ptable_fetch(indirect_loaded_cxts, cxt))
239   res = 1;
240  I_LOADED_UNLOCK;
241
242  return res;
243 }
244
245 static int indirect_set_loaded_locked(pTHX_ void *cxt) {
246 #define indirect_set_loaded_locked(C) indirect_set_loaded_locked(aTHX_ (C))
247  int global_setup = 0;
248
249  if (indirect_loaded <= 0) {
250   assert(indirect_loaded == 0);
251   assert(!indirect_loaded_cxts);
252   indirect_loaded_cxts = ptable_new();
253   global_setup         = 1;
254  }
255  ++indirect_loaded;
256  assert(indirect_loaded_cxts);
257  ptable_loaded_store(indirect_loaded_cxts, cxt, cxt);
258
259  return global_setup;
260 }
261
262 static int indirect_clear_loaded_locked(pTHX_ void *cxt) {
263 #define indirect_clear_loaded_locked(C) indirect_clear_loaded_locked(aTHX_ (C))
264  int global_teardown = 0;
265
266  if (indirect_loaded > 1) {
267   assert(indirect_loaded_cxts);
268   ptable_loaded_delete(indirect_loaded_cxts, cxt);
269   --indirect_loaded;
270  } else if (indirect_loaded_cxts) {
271   assert(indirect_loaded == 1);
272   ptable_loaded_free(indirect_loaded_cxts);
273   indirect_loaded_cxts = NULL;
274   indirect_loaded      = 0;
275   global_teardown      = 1;
276  }
277
278  return global_teardown;
279 }
280
281 #else
282
283 #define indirect_is_loaded(C)           (indirect_loaded > 0)
284 #define indirect_set_loaded_locked(C)   ((indirect_loaded++ <= 0) ? 1 : 0)
285 #define indirect_clear_loaded_locked(C) ((--indirect_loaded <= 0) ? 1 : 0)
286
287 #endif
288
289 /* ... Thread-safe hints ................................................... */
290
291 #if I_WORKAROUND_REQUIRE_PROPAGATION
292
293 typedef struct {
294  SV *code;
295  IV  require_tag;
296 } indirect_hint_t;
297
298 #define I_HINT_STRUCT 1
299
300 #define I_HINT_CODE(H) ((H)->code)
301
302 #define I_HINT_FREE(H) {   \
303  indirect_hint_t *h = (H); \
304  SvREFCNT_dec(h->code);    \
305  PerlMemShared_free(h);    \
306 }
307
308 #else  /*  I_WORKAROUND_REQUIRE_PROPAGATION */
309
310 typedef SV indirect_hint_t;
311
312 #define I_HINT_STRUCT 0
313
314 #define I_HINT_CODE(H) (H)
315
316 #define I_HINT_FREE(H) SvREFCNT_dec(H);
317
318 #endif /* !I_WORKAROUND_REQUIRE_PROPAGATION */
319
320 #if I_THREADSAFE
321
322 #define PTABLE_NAME        ptable_hints
323 #define PTABLE_VAL_FREE(V) I_HINT_FREE(V)
324 #define PTABLE_NEED_DELETE 0
325 #define PTABLE_NEED_WALK   1
326
327 #define pPTBL  pTHX
328 #define pPTBL_ pTHX_
329 #define aPTBL  aTHX
330 #define aPTBL_ aTHX_
331
332 #include "ptable.h"
333
334 #define ptable_hints_store(T, K, V) ptable_hints_store(aTHX_ (T), (K), (V))
335 #define ptable_hints_free(T)        ptable_hints_free(aTHX_ (T))
336
337 #endif /* I_THREADSAFE */
338
339 /* Define the op->str ptable here because we need to be able to clean it during
340  * thread cleanup. */
341
342 typedef struct {
343  char   *buf;
344  STRLEN  pos;
345  STRLEN  size;
346  STRLEN  len;
347  line_t  line;
348 } indirect_op_info_t;
349
350 #define PTABLE_NAME        ptable
351 #define PTABLE_VAL_FREE(V) if (V) { Safefree(((indirect_op_info_t *) (V))->buf); Safefree(V); }
352 #define PTABLE_NEED_DELETE 1
353 #define PTABLE_NEED_WALK   0
354
355 #define pPTBL  pTHX
356 #define pPTBL_ pTHX_
357 #define aPTBL  aTHX
358 #define aPTBL_ aTHX_
359
360 #include "ptable.h"
361
362 #define ptable_store(T, K, V) ptable_store(aTHX_ (T), (K), (V))
363 #define ptable_delete(T, K)   ptable_delete(aTHX_ (T), (K))
364 #define ptable_clear(T)       ptable_clear(aTHX_ (T))
365 #define ptable_free(T)        ptable_free(aTHX_ (T))
366
367 #define MY_CXT_KEY __PACKAGE__ "::_guts" XS_VERSION
368
369 typedef struct {
370 #if I_THREADSAFE
371  ptable *tbl; /* It really is a ptable_hints */
372  tTHX    owner;
373 #endif
374  ptable *map;
375  SV     *global_code;
376 } my_cxt_t;
377
378 START_MY_CXT
379
380 #if I_THREADSAFE
381
382 typedef struct {
383  ptable *tbl;
384 #if I_HAS_PERL(5, 13, 2)
385  CLONE_PARAMS *params;
386 #else
387  CLONE_PARAMS params;
388 #endif
389 } indirect_ptable_clone_ud;
390
391 #if I_HAS_PERL(5, 13, 2)
392 # define indirect_ptable_clone_ud_init(U, T, O) \
393    (U).tbl    = (T); \
394    (U).params = Perl_clone_params_new((O), aTHX)
395 # define indirect_ptable_clone_ud_deinit(U) Perl_clone_params_del((U).params)
396 # define indirect_dup_inc(S, U)             SvREFCNT_inc(sv_dup((S), (U)->params))
397 #else
398 # define indirect_ptable_clone_ud_init(U, T, O) \
399    (U).tbl               = (T);     \
400    (U).params.stashes    = newAV(); \
401    (U).params.flags      = 0;       \
402    (U).params.proto_perl = (O)
403 # define indirect_ptable_clone_ud_deinit(U) SvREFCNT_dec((U).params.stashes)
404 # define indirect_dup_inc(S, U)             SvREFCNT_inc(sv_dup((S), &((U)->params)))
405 #endif
406
407 static void indirect_ptable_clone(pTHX_ ptable_ent *ent, void *ud_) {
408  indirect_ptable_clone_ud *ud = ud_;
409  indirect_hint_t          *h1 = ent->val;
410  indirect_hint_t          *h2;
411
412 #if I_HINT_STRUCT
413
414  h2              = PerlMemShared_malloc(sizeof *h2);
415  h2->code        = indirect_dup_inc(h1->code, ud);
416 #if I_WORKAROUND_REQUIRE_PROPAGATION
417  h2->require_tag = PTR2IV(indirect_dup_inc(INT2PTR(SV *, h1->require_tag), ud));
418 #endif
419
420 #else  /*  I_HINT_STRUCT */
421
422  h2 = indirect_dup_inc(h1, ud);
423
424 #endif /* !I_HINT_STRUCT */
425
426  ptable_hints_store(ud->tbl, ent->key, h2);
427 }
428
429 #endif /* I_THREADSAFE */
430
431 #if I_WORKAROUND_REQUIRE_PROPAGATION
432
433 static IV indirect_require_tag(pTHX) {
434 #define indirect_require_tag() indirect_require_tag(aTHX)
435  const CV *cv, *outside;
436
437  cv = PL_compcv;
438
439  if (!cv) {
440   /* If for some reason the pragma is operational at run-time, try to discover
441    * the current cv in use. */
442   const PERL_SI *si;
443
444   for (si = PL_curstackinfo; si; si = si->si_prev) {
445    I32 cxix;
446
447    for (cxix = si->si_cxix; cxix >= 0; --cxix) {
448     const PERL_CONTEXT *cx = si->si_cxstack + cxix;
449
450     switch (CxTYPE(cx)) {
451      case CXt_SUB:
452      case CXt_FORMAT:
453       /* The propagation workaround is only needed up to 5.10.0 and at that
454        * time format and sub contexts were still identical. And even later the
455        * cv members offsets should have been kept the same. */
456       cv = cx->blk_sub.cv;
457       goto get_enclosing_cv;
458      case CXt_EVAL:
459       cv = cx->blk_eval.cv;
460       goto get_enclosing_cv;
461      default:
462       break;
463     }
464    }
465   }
466
467   cv = PL_main_cv;
468  }
469
470 get_enclosing_cv:
471  for (outside = CvOUTSIDE(cv); outside; outside = CvOUTSIDE(cv))
472   cv = outside;
473
474  return PTR2IV(cv);
475 }
476
477 #endif /* I_WORKAROUND_REQUIRE_PROPAGATION */
478
479 static SV *indirect_tag(pTHX_ SV *value) {
480 #define indirect_tag(V) indirect_tag(aTHX_ (V))
481  indirect_hint_t *h;
482  SV              *code = NULL;
483 #if I_THREADSAFE
484  dMY_CXT;
485
486  if (!MY_CXT.tbl)
487   return newSViv(0);
488 #endif /* I_THREADSAFE */
489
490  if (SvROK(value)) {
491   value = SvRV(value);
492   if (SvTYPE(value) >= SVt_PVCV) {
493    code = value;
494    SvREFCNT_inc_simple_void_NN(code);
495   }
496  }
497
498 #if I_HINT_STRUCT
499  h = PerlMemShared_malloc(sizeof *h);
500  h->code        = code;
501 # if I_WORKAROUND_REQUIRE_PROPAGATION
502  h->require_tag = indirect_require_tag();
503 # endif /* I_WORKAROUND_REQUIRE_PROPAGATION */
504 #else  /*  I_HINT_STRUCT */
505  h = code;
506 #endif /* !I_HINT_STRUCT */
507
508 #if I_THREADSAFE
509  /* We only need for the key to be an unique tag for looking up the value later
510   * Allocated memory provides convenient unique identifiers, so that's why we
511   * use the hint as the key itself. */
512  ptable_hints_store(MY_CXT.tbl, h, h);
513 #endif /* I_THREADSAFE */
514
515  return newSViv(PTR2IV(h));
516 }
517
518 static SV *indirect_detag(pTHX_ const SV *hint) {
519 #define indirect_detag(H) indirect_detag(aTHX_ (H))
520  indirect_hint_t *h;
521 #if I_THREADSAFE || I_WORKAROUND_REQUIRE_PROPAGATION
522  dMY_CXT;
523 #endif
524
525 #if I_THREADSAFE
526  if (!MY_CXT.tbl)
527   return NULL;
528 #endif /* I_THREADSAFE */
529
530  h = INT2PTR(indirect_hint_t *, SvIVX(hint));
531 #if I_THREADSAFE
532  h = ptable_fetch(MY_CXT.tbl, h);
533 #endif /* I_THREADSAFE */
534
535 #if I_WORKAROUND_REQUIRE_PROPAGATION
536  if (indirect_require_tag() != h->require_tag)
537   return MY_CXT.global_code;
538 #endif /* I_WORKAROUND_REQUIRE_PROPAGATION */
539
540  return I_HINT_CODE(h);
541 }
542
543 static VOL U32 indirect_hash = 0;
544
545 static SV *indirect_hint(pTHX) {
546 #define indirect_hint() indirect_hint(aTHX)
547  SV *hint = NULL;
548
549  if (IN_PERL_RUNTIME)
550   return NULL;
551
552 #if I_HAS_PERL(5, 10, 0) || defined(PL_parser)
553  if (!PL_parser)
554   return NULL;
555 #endif
556
557 #ifdef cop_hints_fetch_pvn
558  hint = cop_hints_fetch_pvn(PL_curcop, __PACKAGE__, __PACKAGE_LEN__,
559                                                               indirect_hash, 0);
560 #elif I_HAS_PERL(5, 9, 5)
561  hint = Perl_refcounted_he_fetch(aTHX_ PL_curcop->cop_hints_hash,
562                                        NULL,
563                                        __PACKAGE__, __PACKAGE_LEN__,
564                                        0,
565                                        indirect_hash);
566 #else
567  {
568   SV **val = hv_fetch(GvHV(PL_hintgv), __PACKAGE__, __PACKAGE_LEN__, 0);
569   if (val)
570    hint = *val;
571  }
572 #endif
573
574  if (hint && SvIOK(hint)) {
575   return indirect_detag(hint);
576  } else {
577   dMY_CXT;
578   if (indirect_is_loaded(&MY_CXT))
579    return MY_CXT.global_code;
580   else
581    return NULL;
582  }
583 }
584
585 /* ... op -> source position ............................................... */
586
587 static void indirect_map_store(pTHX_ const OP *o, STRLEN pos, SV *sv, line_t line) {
588 #define indirect_map_store(O, P, N, L) indirect_map_store(aTHX_ (O), (P), (N), (L))
589  indirect_op_info_t *oi;
590  const char *s;
591  STRLEN len;
592  dMY_CXT;
593
594  /* No need to check for MY_CXT.map != NULL because this code path is always
595   * guarded by indirect_hint(). */
596
597  if (!(oi = ptable_fetch(MY_CXT.map, o))) {
598   Newx(oi, 1, indirect_op_info_t);
599   ptable_store(MY_CXT.map, o, oi);
600   oi->buf  = NULL;
601   oi->size = 0;
602  }
603
604  if (sv) {
605   s = SvPV_const(sv, len);
606  } else {
607   s   = "{";
608   len = 1;
609  }
610
611  if (len > oi->size) {
612   Safefree(oi->buf);
613   Newx(oi->buf, len, char);
614   oi->size = len;
615  }
616  Copy(s, oi->buf, len, char);
617
618  oi->len  = len;
619  oi->pos  = pos;
620  oi->line = line;
621 }
622
623 static const indirect_op_info_t *indirect_map_fetch(pTHX_ const OP *o) {
624 #define indirect_map_fetch(O) indirect_map_fetch(aTHX_ (O))
625  dMY_CXT;
626
627  /* No need to check for MY_CXT.map != NULL because this code path is always
628   * guarded by indirect_hint(). */
629
630  return ptable_fetch(MY_CXT.map, o);
631 }
632
633 static void indirect_map_delete(pTHX_ const OP *o) {
634 #define indirect_map_delete(O) indirect_map_delete(aTHX_ (O))
635  dMY_CXT;
636
637  if (indirect_is_loaded(&MY_CXT) && MY_CXT.map)
638   ptable_delete(MY_CXT.map, o);
639 }
640
641 /* --- Safe version of call_sv() ------------------------------------------- */
642
643 static I32 indirect_call_sv(pTHX_ SV *sv, I32 flags) {
644 #define indirect_call_sv(S, F) indirect_call_sv(aTHX_ (S), (F))
645  I32          ret, cxix;
646  PERL_CONTEXT saved_cx;
647  SV          *saved_errsv = NULL;
648
649  if (SvTRUE(ERRSV)) {
650   if (IN_PERL_COMPILETIME && PL_errors)
651    sv_catsv(PL_errors, ERRSV);
652   else
653    saved_errsv = newSVsv(ERRSV);
654   SvCUR_set(ERRSV, 0);
655  }
656
657  cxix     = (cxstack_ix < cxstack_max) ? (cxstack_ix + 1) : Perl_cxinc(aTHX);
658  /* The last popped context will be reused by call_sv(), but our callers may
659   * still need its previous value. Back it up so that it isn't clobbered. */
660  saved_cx = cxstack[cxix];
661
662  ret = call_sv(sv, flags | G_EVAL);
663
664  cxstack[cxix] = saved_cx;
665
666  if (SvTRUE(ERRSV)) {
667   /* Discard the old ERRSV, and reuse the variable to temporarily store the
668    * new one. */
669   if (saved_errsv)
670    sv_setsv(saved_errsv, ERRSV);
671   else
672    saved_errsv = newSVsv(ERRSV);
673   SvCUR_set(ERRSV, 0);
674   /* Immediately flush all errors. */
675   if (IN_PERL_COMPILETIME) {
676 #if I_HAS_PERL(5, 10, 0) || defined(PL_parser)
677    if (PL_parser)
678     ++PL_parser->error_count;
679 #elif defined(PL_error_count)
680    ++PL_error_count;
681 #else
682    ++PL_Ierror_count;
683 #endif
684    if (PL_errors) {
685     sv_setsv(ERRSV, PL_errors);
686     SvCUR_set(PL_errors, 0);
687    }
688   }
689   sv_catsv(ERRSV, saved_errsv);
690   SvREFCNT_dec(saved_errsv);
691   croak(NULL);
692  } else if (saved_errsv) {
693   /* If IN_PERL_COMPILETIME && PL_errors, then the old ERRSV has already been
694    * added to PL_errors. Otherwise, just restore it to ERRSV, as if no eval
695    * block has ever been executed. */
696   sv_setsv(ERRSV, saved_errsv);
697   SvREFCNT_dec(saved_errsv);
698  }
699
700  return ret;
701 }
702
703 /* --- Check functions ----------------------------------------------------- */
704
705 static int indirect_find(pTHX_ SV *name_sv, const char *line_bufptr, STRLEN *name_pos) {
706 #define indirect_find(NSV, LBP, NP) indirect_find(aTHX_ (NSV), (LBP), (NP))
707  STRLEN      name_len, line_len;
708  const char *name, *name_end;
709  const char *line, *line_end;
710  const char *p;
711
712  line     = SvPV_const(PL_linestr, line_len);
713  line_end = line + line_len;
714
715  name = SvPV_const(name_sv, name_len);
716  if (name_len >= 1 && *name == '$') {
717   ++name;
718   --name_len;
719   while (line_bufptr < line_end && *line_bufptr != '$')
720    ++line_bufptr;
721   if (line_bufptr >= line_end)
722    return 0;
723  }
724  name_end = name + name_len;
725
726  p = line_bufptr;
727  while (1) {
728   p = ninstr(p, line_end, name, name_end);
729   if (!p)
730    return 0;
731   if (!isALNUM(p[name_len]))
732    break;
733   /* p points to a word that has name as prefix, skip the rest of the word */
734   p += name_len + 1;
735   while (isALNUM(*p))
736    ++p;
737  }
738
739  *name_pos = p - line;
740
741  return 1;
742 }
743
744 /* ... ck_const ............................................................ */
745
746 static OP *(*indirect_old_ck_const)(pTHX_ OP *) = 0;
747
748 static OP *indirect_ck_const(pTHX_ OP *o) {
749  o = indirect_old_ck_const(aTHX_ o);
750
751  if (indirect_hint()) {
752   SV *sv = cSVOPo_sv;
753
754   if (SvPOK(sv) && (SvTYPE(sv) >= SVt_PV)) {
755    STRLEN pos;
756
757    if (indirect_find(sv, PL_oldbufptr, &pos)) {
758     STRLEN len;
759
760     /* If the constant is equal to the current package name, try to look for
761      * a "__PACKAGE__" coming before what we got. We only need to check this
762      * when we already had a match because __PACKAGE__ can only appear in
763      * direct method calls ("new __PACKAGE__" is a syntax error). */
764     len = SvCUR(sv);
765     if (PL_curstash
766         && len == (STRLEN) HvNAMELEN_get(PL_curstash)
767         && memcmp(SvPVX(sv), HvNAME_get(PL_curstash), len) == 0) {
768      STRLEN pos_pkg;
769      SV    *pkg = sv_newmortal();
770      sv_setpvn(pkg, "__PACKAGE__", sizeof("__PACKAGE__")-1);
771
772      if (indirect_find(pkg, PL_oldbufptr, &pos_pkg) && pos_pkg < pos) {
773       sv  = pkg;
774       pos = pos_pkg;
775      }
776     }
777
778     indirect_map_store(o, pos, sv, CopLINE(&PL_compiling));
779     return o;
780    }
781   }
782  }
783
784  indirect_map_delete(o);
785  return o;
786 }
787
788 /* ... ck_rv2sv ............................................................ */
789
790 static OP *(*indirect_old_ck_rv2sv)(pTHX_ OP *) = 0;
791
792 static OP *indirect_ck_rv2sv(pTHX_ OP *o) {
793  if (indirect_hint()) {
794   OP *op = cUNOPo->op_first;
795   SV *sv;
796   const char *name = NULL;
797   STRLEN pos, len;
798   OPCODE type = (OPCODE) op->op_type;
799
800   switch (type) {
801    case OP_GV:
802    case OP_GVSV: {
803     GV *gv = cGVOPx_gv(op);
804     name = GvNAME(gv);
805     len  = GvNAMELEN(gv);
806     break;
807    }
808    default:
809     if ((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP) {
810      SV *nsv = cSVOPx_sv(op);
811      if (SvPOK(nsv) && (SvTYPE(nsv) >= SVt_PV))
812       name = SvPV_const(nsv, len);
813     }
814   }
815   if (!name)
816    goto done;
817
818   sv = sv_2mortal(newSVpvn("$", 1));
819   sv_catpvn_nomg(sv, name, len);
820   if (!indirect_find(sv, PL_oldbufptr, &pos)) {
821    /* If it failed, retry without the current stash */
822    const char *stash = HvNAME_get(PL_curstash);
823    STRLEN stashlen = HvNAMELEN_get(PL_curstash);
824
825    if ((len < stashlen + 2) || strnNE(name, stash, stashlen)
826        || name[stashlen] != ':' || name[stashlen+1] != ':') {
827     /* Failed again ? Try to remove main */
828     stash = "main";
829     stashlen = 4;
830     if ((len < stashlen + 2) || strnNE(name, stash, stashlen)
831         || name[stashlen] != ':' || name[stashlen+1] != ':')
832      goto done;
833    }
834
835    sv_setpvn(sv, "$", 1);
836    stashlen += 2;
837    sv_catpvn_nomg(sv, name + stashlen, len - stashlen);
838    if (!indirect_find(sv, PL_oldbufptr, &pos))
839     goto done;
840   }
841
842   o = indirect_old_ck_rv2sv(aTHX_ o);
843
844   indirect_map_store(o, pos, sv, CopLINE(&PL_compiling));
845   return o;
846  }
847
848 done:
849  o = indirect_old_ck_rv2sv(aTHX_ o);
850
851  indirect_map_delete(o);
852  return o;
853 }
854
855 /* ... ck_padany ........................................................... */
856
857 static OP *(*indirect_old_ck_padany)(pTHX_ OP *) = 0;
858
859 static OP *indirect_ck_padany(pTHX_ OP *o) {
860  o = indirect_old_ck_padany(aTHX_ o);
861
862  if (indirect_hint()) {
863   SV *sv;
864   const char *s = PL_oldbufptr, *t = PL_bufptr - 1;
865
866   while (s < t && isSPACE(*s)) ++s;
867   if (*s == '$' && ++s <= t) {
868    while (s < t && isSPACE(*s)) ++s;
869    while (s < t && isSPACE(*t)) --t;
870    sv = sv_2mortal(newSVpvn("$", 1));
871    sv_catpvn_nomg(sv, s, t - s + 1);
872    indirect_map_store(o, s - SvPVX_const(PL_linestr),
873                          sv, CopLINE(&PL_compiling));
874    return o;
875   }
876  }
877
878  indirect_map_delete(o);
879  return o;
880 }
881
882 /* ... ck_scope ............................................................ */
883
884 static OP *(*indirect_old_ck_scope)  (pTHX_ OP *) = 0;
885 static OP *(*indirect_old_ck_lineseq)(pTHX_ OP *) = 0;
886
887 static OP *indirect_ck_scope(pTHX_ OP *o) {
888  OP *(*old_ck)(pTHX_ OP *) = 0;
889
890  switch (o->op_type) {
891   case OP_SCOPE:   old_ck = indirect_old_ck_scope;   break;
892   case OP_LINESEQ: old_ck = indirect_old_ck_lineseq; break;
893  }
894  o = old_ck(aTHX_ o);
895
896  if (indirect_hint()) {
897   indirect_map_store(o, PL_oldbufptr - SvPVX_const(PL_linestr),
898                         NULL, CopLINE(&PL_compiling));
899   return o;
900  }
901
902  indirect_map_delete(o);
903  return o;
904 }
905
906 /* We don't need to clean the map entries for leave ops because they can only
907  * be created by mutating from a lineseq. */
908
909 /* ... ck_method ........................................................... */
910
911 static OP *(*indirect_old_ck_method)(pTHX_ OP *) = 0;
912
913 static OP *indirect_ck_method(pTHX_ OP *o) {
914  if (indirect_hint()) {
915   OP *op = cUNOPo->op_first;
916
917   /* Indirect method call is only possible when the method is a bareword, so
918    * don't trip up on $obj->$meth. */
919   if (op && op->op_type == OP_CONST) {
920    const indirect_op_info_t *oi = indirect_map_fetch(op);
921    STRLEN pos;
922    line_t line;
923    SV *sv;
924
925    if (!oi)
926     goto done;
927
928    sv   = sv_2mortal(newSVpvn(oi->buf, oi->len));
929    pos  = oi->pos;
930    /* Keep the old line so that we really point to the first line of the
931     * expression. */
932    line = oi->line;
933
934    o = indirect_old_ck_method(aTHX_ o);
935    /* o may now be a method_named */
936
937    indirect_map_store(o, pos, sv, line);
938    return o;
939   }
940  }
941
942 done:
943  o = indirect_old_ck_method(aTHX_ o);
944
945  indirect_map_delete(o);
946  return o;
947 }
948
949 /* ... ck_method_named ..................................................... */
950
951 /* "use foo/no foo" compiles its call to import/unimport directly to a
952  * method_named op. */
953
954 static OP *(*indirect_old_ck_method_named)(pTHX_ OP *) = 0;
955
956 static OP *indirect_ck_method_named(pTHX_ OP *o) {
957  if (indirect_hint()) {
958   STRLEN pos;
959   line_t line;
960   SV *sv;
961
962   sv = cSVOPo_sv;
963   if (!SvPOK(sv) || (SvTYPE(sv) < SVt_PV))
964    goto done;
965   sv = sv_mortalcopy(sv);
966
967   if (!indirect_find(sv, PL_oldbufptr, &pos))
968    goto done;
969   line = CopLINE(&PL_compiling);
970
971   o = indirect_old_ck_method_named(aTHX_ o);
972
973   indirect_map_store(o, pos, sv, line);
974   return o;
975  }
976
977 done:
978  o = indirect_old_ck_method_named(aTHX_ o);
979
980  indirect_map_delete(o);
981  return o;
982 }
983
984 /* ... ck_entersub ......................................................... */
985
986 static OP *(*indirect_old_ck_entersub)(pTHX_ OP *) = 0;
987
988 static OP *indirect_ck_entersub(pTHX_ OP *o) {
989  SV *code = indirect_hint();
990
991  o = indirect_old_ck_entersub(aTHX_ o);
992
993  if (code) {
994   const indirect_op_info_t *moi, *ooi;
995   OP     *mop, *oop;
996   LISTOP *lop;
997
998   oop = o;
999   do {
1000    lop = (LISTOP *) oop;
1001    if (!(lop->op_flags & OPf_KIDS))
1002     goto done;
1003    oop = lop->op_first;
1004   } while (oop->op_type != OP_PUSHMARK);
1005   oop = OpSIBLING(oop);
1006   mop = lop->op_last;
1007
1008   if (!oop)
1009    goto done;
1010
1011   switch (oop->op_type) {
1012    case OP_CONST:
1013    case OP_RV2SV:
1014    case OP_PADSV:
1015    case OP_SCOPE:
1016    case OP_LEAVE:
1017     break;
1018    default:
1019     goto done;
1020   }
1021
1022   if (mop->op_type == OP_METHOD)
1023    mop = cUNOPx(mop)->op_first;
1024   else if (mop->op_type != OP_METHOD_NAMED)
1025    goto done;
1026
1027   moi = indirect_map_fetch(mop);
1028   if (!moi)
1029    goto done;
1030
1031   ooi = indirect_map_fetch(oop);
1032   if (!ooi)
1033    goto done;
1034
1035   /* When positions are identical, the method and the object must have the
1036    * same name. But it also means that it is an indirect call, as "foo->foo"
1037    * results in different positions. */
1038   if (   moi->line < ooi->line
1039       || (moi->line == ooi->line && moi->pos <= ooi->pos)) {
1040    SV *file;
1041    dSP;
1042
1043    ENTER;
1044    SAVETMPS;
1045
1046 #ifdef USE_ITHREADS
1047    file = sv_2mortal(newSVpv(CopFILE(&PL_compiling), 0));
1048 #else
1049    file = sv_mortalcopy(CopFILESV(&PL_compiling));
1050 #endif
1051
1052    PUSHMARK(SP);
1053    EXTEND(SP, 4);
1054    mPUSHp(ooi->buf, ooi->len);
1055    mPUSHp(moi->buf, moi->len);
1056    PUSHs(file);
1057    mPUSHu(moi->line);
1058    PUTBACK;
1059
1060    indirect_call_sv(code, G_VOID);
1061
1062    PUTBACK;
1063
1064    FREETMPS;
1065    LEAVE;
1066   }
1067  }
1068
1069 done:
1070  return o;
1071 }
1072
1073 /* --- Module setup/teardown ----------------------------------------------- */
1074
1075 static void indirect_teardown(pTHX_ void *interp) {
1076  dMY_CXT;
1077
1078  I_LOADED_LOCK;
1079
1080  if (indirect_clear_loaded_locked(&MY_CXT)) {
1081   indirect_ck_restore(OP_CONST,   &indirect_old_ck_const);
1082   indirect_ck_restore(OP_RV2SV,   &indirect_old_ck_rv2sv);
1083   indirect_ck_restore(OP_PADANY,  &indirect_old_ck_padany);
1084   indirect_ck_restore(OP_SCOPE,   &indirect_old_ck_scope);
1085   indirect_ck_restore(OP_LINESEQ, &indirect_old_ck_lineseq);
1086
1087   indirect_ck_restore(OP_METHOD,       &indirect_old_ck_method);
1088   indirect_ck_restore(OP_METHOD_NAMED, &indirect_old_ck_method_named);
1089   indirect_ck_restore(OP_ENTERSUB,     &indirect_old_ck_entersub);
1090  }
1091
1092  I_LOADED_UNLOCK;
1093
1094  SvREFCNT_dec(MY_CXT.global_code);
1095  MY_CXT.global_code = NULL;
1096
1097  ptable_free(MY_CXT.map);
1098  MY_CXT.map = NULL;
1099
1100 #if I_THREADSAFE
1101  ptable_hints_free(MY_CXT.tbl);
1102  MY_CXT.tbl = NULL;
1103 #endif
1104
1105  return;
1106 }
1107
1108 static void indirect_setup(pTHX) {
1109 #define indirect_setup() indirect_setup(aTHX)
1110  MY_CXT_INIT; /* Takes/release PL_my_ctx_mutex */
1111
1112  I_LOADED_LOCK;
1113
1114  if (indirect_set_loaded_locked(&MY_CXT)) {
1115   PERL_HASH(indirect_hash, __PACKAGE__, __PACKAGE_LEN__);
1116
1117   indirect_ck_replace(OP_CONST,   indirect_ck_const,  &indirect_old_ck_const);
1118   indirect_ck_replace(OP_RV2SV,   indirect_ck_rv2sv,  &indirect_old_ck_rv2sv);
1119   indirect_ck_replace(OP_PADANY,  indirect_ck_padany, &indirect_old_ck_padany);
1120   indirect_ck_replace(OP_SCOPE,   indirect_ck_scope,  &indirect_old_ck_scope);
1121   indirect_ck_replace(OP_LINESEQ, indirect_ck_scope,  &indirect_old_ck_lineseq);
1122
1123   indirect_ck_replace(OP_METHOD,       indirect_ck_method,
1124                                        &indirect_old_ck_method);
1125   indirect_ck_replace(OP_METHOD_NAMED, indirect_ck_method_named,
1126                                        &indirect_old_ck_method_named);
1127   indirect_ck_replace(OP_ENTERSUB,     indirect_ck_entersub,
1128                                        &indirect_old_ck_entersub);
1129  }
1130
1131  I_LOADED_UNLOCK;
1132
1133  {
1134   HV *stash;
1135
1136   stash = gv_stashpvn(__PACKAGE__, __PACKAGE_LEN__, 1);
1137   newCONSTSUB(stash, "I_THREADSAFE", newSVuv(I_THREADSAFE));
1138   newCONSTSUB(stash, "I_FORKSAFE",   newSVuv(I_FORKSAFE));
1139
1140 #if I_THREADSAFE
1141   MY_CXT.tbl         = ptable_new();
1142   MY_CXT.owner       = aTHX;
1143 #endif
1144
1145   MY_CXT.map         = ptable_new();
1146   MY_CXT.global_code = NULL;
1147  }
1148
1149  call_atexit(indirect_teardown, NULL);
1150
1151  return;
1152 }
1153
1154 /* --- XS ------------------------------------------------------------------ */
1155
1156 MODULE = indirect      PACKAGE = indirect
1157
1158 PROTOTYPES: ENABLE
1159
1160 BOOT:
1161 {
1162  indirect_setup();
1163 }
1164
1165 #if I_THREADSAFE
1166
1167 void
1168 CLONE(...)
1169 PROTOTYPE: DISABLE
1170 PREINIT:
1171  ptable *t;
1172  SV     *global_code_dup;
1173 PPCODE:
1174  {
1175   indirect_ptable_clone_ud ud;
1176   dMY_CXT;
1177   t = ptable_new();
1178   indirect_ptable_clone_ud_init(ud, t, MY_CXT.owner);
1179   ptable_walk(MY_CXT.tbl, indirect_ptable_clone, &ud);
1180   global_code_dup = indirect_dup_inc(MY_CXT.global_code, &ud);
1181   indirect_ptable_clone_ud_deinit(ud);
1182  }
1183  {
1184   MY_CXT_CLONE;
1185   MY_CXT.map         = ptable_new();
1186   MY_CXT.tbl         = t;
1187   MY_CXT.owner       = aTHX;
1188   MY_CXT.global_code = global_code_dup;
1189   {
1190    int global_setup;
1191    I_LOADED_LOCK;
1192    global_setup = indirect_set_loaded_locked(&MY_CXT);
1193    assert(!global_setup);
1194    I_LOADED_UNLOCK;
1195   }
1196  }
1197  XSRETURN(0);
1198
1199 #endif /* I_THREADSAFE */
1200
1201 SV *
1202 _tag(SV *value)
1203 PROTOTYPE: $
1204 CODE:
1205  RETVAL = indirect_tag(value);
1206 OUTPUT:
1207  RETVAL
1208
1209 void
1210 _global(SV *code)
1211 PROTOTYPE: $
1212 PPCODE:
1213  if (!SvOK(code))
1214   code = NULL;
1215  else if (SvROK(code))
1216   code = SvRV(code);
1217  {
1218   dMY_CXT;
1219   SvREFCNT_dec(MY_CXT.global_code);
1220   MY_CXT.global_code = SvREFCNT_inc(code);
1221  }
1222  XSRETURN(0);