Make sure MULTIPLICITY builds set PERL_IMPLICIT_CONTEXT
[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 defined(OP_CHECK_MUTEX_LOCK) && defined(OP_CHECK_MUTEX_UNLOCK)
155 # define I_CHECK_MUTEX_LOCK   OP_CHECK_MUTEX_LOCK
156 # define I_CHECK_MUTEX_UNLOCK OP_CHECK_MUTEX_UNLOCK
157 #else
158 # define I_CHECK_MUTEX_LOCK   OP_REFCNT_LOCK
159 # define I_CHECK_MUTEX_UNLOCK OP_REFCNT_UNLOCK
160 #endif
161
162 typedef OP *(*indirect_ck_t)(pTHX_ OP *);
163
164 #ifdef wrap_op_checker
165
166 # define indirect_ck_replace(T, NC, OCP) wrap_op_checker((T), (NC), (OCP))
167
168 #else
169
170 static void indirect_ck_replace(pTHX_ OPCODE type, indirect_ck_t new_ck, indirect_ck_t *old_ck_p) {
171 #define indirect_ck_replace(T, NC, OCP) indirect_ck_replace(aTHX_ (T), (NC), (OCP))
172  I_CHECK_MUTEX_LOCK;
173  if (!*old_ck_p) {
174   *old_ck_p      = PL_check[type];
175   PL_check[type] = new_ck;
176  }
177  I_CHECK_MUTEX_UNLOCK;
178 }
179
180 #endif
181
182 static void indirect_ck_restore(pTHX_ OPCODE type, indirect_ck_t *old_ck_p) {
183 #define indirect_ck_restore(T, OCP) indirect_ck_restore(aTHX_ (T), (OCP))
184  I_CHECK_MUTEX_LOCK;
185  if (*old_ck_p) {
186   PL_check[type] = *old_ck_p;
187   *old_ck_p      = 0;
188  }
189  I_CHECK_MUTEX_UNLOCK;
190 }
191
192 /* --- Helpers ------------------------------------------------------------- */
193
194 /* ... Thread-safe hints ................................................... */
195
196 #if I_WORKAROUND_REQUIRE_PROPAGATION
197
198 typedef struct {
199  SV *code;
200  IV  require_tag;
201 } indirect_hint_t;
202
203 #define I_HINT_STRUCT 1
204
205 #define I_HINT_CODE(H) ((H)->code)
206
207 #define I_HINT_FREE(H) {   \
208  indirect_hint_t *h = (H); \
209  SvREFCNT_dec(h->code);    \
210  PerlMemShared_free(h);    \
211 }
212
213 #else  /*  I_WORKAROUND_REQUIRE_PROPAGATION */
214
215 typedef SV indirect_hint_t;
216
217 #define I_HINT_STRUCT 0
218
219 #define I_HINT_CODE(H) (H)
220
221 #define I_HINT_FREE(H) SvREFCNT_dec(H);
222
223 #endif /* !I_WORKAROUND_REQUIRE_PROPAGATION */
224
225 #if I_THREADSAFE
226
227 #define PTABLE_NAME        ptable_hints
228 #define PTABLE_VAL_FREE(V) I_HINT_FREE(V)
229
230 #define pPTBL  pTHX
231 #define pPTBL_ pTHX_
232 #define aPTBL  aTHX
233 #define aPTBL_ aTHX_
234
235 #include "ptable.h"
236
237 #define ptable_hints_store(T, K, V) ptable_hints_store(aTHX_ (T), (K), (V))
238 #define ptable_hints_free(T)        ptable_hints_free(aTHX_ (T))
239
240 #endif /* I_THREADSAFE */
241
242 /* Define the op->str ptable here because we need to be able to clean it during
243  * thread cleanup. */
244
245 typedef struct {
246  char   *buf;
247  STRLEN  pos;
248  STRLEN  size;
249  STRLEN  len;
250  line_t  line;
251 } indirect_op_info_t;
252
253 #define PTABLE_NAME        ptable
254 #define PTABLE_VAL_FREE(V) if (V) { Safefree(((indirect_op_info_t *) (V))->buf); Safefree(V); }
255
256 #define pPTBL  pTHX
257 #define pPTBL_ pTHX_
258 #define aPTBL  aTHX
259 #define aPTBL_ aTHX_
260
261 #include "ptable.h"
262
263 #define ptable_store(T, K, V) ptable_store(aTHX_ (T), (K), (V))
264 #define ptable_delete(T, K)   ptable_delete(aTHX_ (T), (K))
265 #define ptable_clear(T)       ptable_clear(aTHX_ (T))
266 #define ptable_free(T)        ptable_free(aTHX_ (T))
267
268 #define MY_CXT_KEY __PACKAGE__ "::_guts" XS_VERSION
269
270 typedef struct {
271 #if I_THREADSAFE
272  ptable *tbl; /* It really is a ptable_hints */
273  tTHX    owner;
274 #endif
275  ptable *map;
276  SV     *global_code;
277 } my_cxt_t;
278
279 START_MY_CXT
280
281 #if I_THREADSAFE
282
283 typedef struct {
284  ptable *tbl;
285 #if I_HAS_PERL(5, 13, 2)
286  CLONE_PARAMS *params;
287 #else
288  CLONE_PARAMS params;
289 #endif
290 } indirect_ptable_clone_ud;
291
292 #if I_HAS_PERL(5, 13, 2)
293 # define indirect_ptable_clone_ud_init(U, T, O) \
294    (U).tbl    = (T); \
295    (U).params = Perl_clone_params_new((O), aTHX)
296 # define indirect_ptable_clone_ud_deinit(U) Perl_clone_params_del((U).params)
297 # define indirect_dup_inc(S, U)             SvREFCNT_inc(sv_dup((S), (U)->params))
298 #else
299 # define indirect_ptable_clone_ud_init(U, T, O) \
300    (U).tbl               = (T);     \
301    (U).params.stashes    = newAV(); \
302    (U).params.flags      = 0;       \
303    (U).params.proto_perl = (O)
304 # define indirect_ptable_clone_ud_deinit(U) SvREFCNT_dec((U).params.stashes)
305 # define indirect_dup_inc(S, U)             SvREFCNT_inc(sv_dup((S), &((U)->params)))
306 #endif
307
308 static void indirect_ptable_clone(pTHX_ ptable_ent *ent, void *ud_) {
309  indirect_ptable_clone_ud *ud = ud_;
310  indirect_hint_t          *h1 = ent->val;
311  indirect_hint_t          *h2;
312
313 #if I_HINT_STRUCT
314
315  h2              = PerlMemShared_malloc(sizeof *h2);
316  h2->code        = indirect_dup_inc(h1->code, ud);
317 #if I_WORKAROUND_REQUIRE_PROPAGATION
318  h2->require_tag = PTR2IV(indirect_dup_inc(INT2PTR(SV *, h1->require_tag), ud));
319 #endif
320
321 #else  /*  I_HINT_STRUCT */
322
323  h2 = indirect_dup_inc(h1, ud);
324
325 #endif /* !I_HINT_STRUCT */
326
327  ptable_hints_store(ud->tbl, ent->key, h2);
328 }
329
330 static void indirect_thread_cleanup(pTHX_ void *ud) {
331  dMY_CXT;
332
333  SvREFCNT_dec(MY_CXT.global_code);
334  MY_CXT.global_code = NULL;
335  ptable_free(MY_CXT.map);
336  MY_CXT.map = NULL;
337  ptable_hints_free(MY_CXT.tbl);
338  MY_CXT.tbl = NULL;
339 }
340
341 static int indirect_endav_free(pTHX_ SV *sv, MAGIC *mg) {
342  SAVEDESTRUCTOR_X(indirect_thread_cleanup, NULL);
343
344  return 0;
345 }
346
347 static MGVTBL indirect_endav_vtbl = {
348  0,
349  0,
350  0,
351  0,
352  indirect_endav_free
353 #if MGf_COPY
354  , 0
355 #endif
356 #if MGf_DUP
357  , 0
358 #endif
359 #if MGf_LOCAL
360  , 0
361 #endif
362 };
363
364 #endif /* I_THREADSAFE */
365
366 #if I_WORKAROUND_REQUIRE_PROPAGATION
367 static IV indirect_require_tag(pTHX) {
368 #define indirect_require_tag() indirect_require_tag(aTHX)
369  const CV *cv, *outside;
370
371  cv = PL_compcv;
372
373  if (!cv) {
374   /* If for some reason the pragma is operational at run-time, try to discover
375    * the current cv in use. */
376   const PERL_SI *si;
377
378   for (si = PL_curstackinfo; si; si = si->si_prev) {
379    I32 cxix;
380
381    for (cxix = si->si_cxix; cxix >= 0; --cxix) {
382     const PERL_CONTEXT *cx = si->si_cxstack + cxix;
383
384     switch (CxTYPE(cx)) {
385      case CXt_SUB:
386      case CXt_FORMAT:
387       /* The propagation workaround is only needed up to 5.10.0 and at that
388        * time format and sub contexts were still identical. And even later the
389        * cv members offsets should have been kept the same. */
390       cv = cx->blk_sub.cv;
391       goto get_enclosing_cv;
392      case CXt_EVAL:
393       cv = cx->blk_eval.cv;
394       goto get_enclosing_cv;
395      default:
396       break;
397     }
398    }
399   }
400
401   cv = PL_main_cv;
402  }
403
404 get_enclosing_cv:
405  for (outside = CvOUTSIDE(cv); outside; outside = CvOUTSIDE(cv))
406   cv = outside;
407
408  return PTR2IV(cv);
409 }
410 #endif /* I_WORKAROUND_REQUIRE_PROPAGATION */
411
412 static SV *indirect_tag(pTHX_ SV *value) {
413 #define indirect_tag(V) indirect_tag(aTHX_ (V))
414  indirect_hint_t *h;
415  SV              *code = NULL;
416 #if I_THREADSAFE
417  dMY_CXT;
418
419  if (!MY_CXT.tbl)
420   return newSViv(0);
421 #endif /* I_THREADSAFE */
422
423  if (SvROK(value)) {
424   value = SvRV(value);
425   if (SvTYPE(value) >= SVt_PVCV) {
426    code = value;
427    SvREFCNT_inc_simple_void_NN(code);
428   }
429  }
430
431 #if I_HINT_STRUCT
432  h = PerlMemShared_malloc(sizeof *h);
433  h->code        = code;
434 # if I_WORKAROUND_REQUIRE_PROPAGATION
435  h->require_tag = indirect_require_tag();
436 # endif /* I_WORKAROUND_REQUIRE_PROPAGATION */
437 #else  /*  I_HINT_STRUCT */
438  h = code;
439 #endif /* !I_HINT_STRUCT */
440
441 #if I_THREADSAFE
442  /* We only need for the key to be an unique tag for looking up the value later
443   * Allocated memory provides convenient unique identifiers, so that's why we
444   * use the hint as the key itself. */
445  ptable_hints_store(MY_CXT.tbl, h, h);
446 #endif /* I_THREADSAFE */
447
448  return newSViv(PTR2IV(h));
449 }
450
451 static SV *indirect_detag(pTHX_ const SV *hint) {
452 #define indirect_detag(H) indirect_detag(aTHX_ (H))
453  indirect_hint_t *h;
454 #if I_THREADSAFE || I_WORKAROUND_REQUIRE_PROPAGATION
455  dMY_CXT;
456 #endif
457
458 #if I_THREADSAFE
459  if (!MY_CXT.tbl)
460   return NULL;
461 #endif /* I_THREADSAFE */
462
463  h = INT2PTR(indirect_hint_t *, SvIVX(hint));
464 #if I_THREADSAFE
465  h = ptable_fetch(MY_CXT.tbl, h);
466 #endif /* I_THREADSAFE */
467
468 #if I_WORKAROUND_REQUIRE_PROPAGATION
469  if (indirect_require_tag() != h->require_tag)
470   return MY_CXT.global_code;
471 #endif /* I_WORKAROUND_REQUIRE_PROPAGATION */
472
473  return I_HINT_CODE(h);
474 }
475
476 static VOL U32 indirect_hash = 0;
477
478 static SV *indirect_hint(pTHX) {
479 #define indirect_hint() indirect_hint(aTHX)
480  SV *hint = NULL;
481
482  if (IN_PERL_RUNTIME)
483   return NULL;
484
485 #if I_HAS_PERL(5, 10, 0) || defined(PL_parser)
486  if (!PL_parser)
487   return NULL;
488 #endif
489
490 #ifdef cop_hints_fetch_pvn
491  hint = cop_hints_fetch_pvn(PL_curcop, __PACKAGE__, __PACKAGE_LEN__,
492                                                               indirect_hash, 0);
493 #elif I_HAS_PERL(5, 9, 5)
494  hint = Perl_refcounted_he_fetch(aTHX_ PL_curcop->cop_hints_hash,
495                                        NULL,
496                                        __PACKAGE__, __PACKAGE_LEN__,
497                                        0,
498                                        indirect_hash);
499 #else
500  {
501   SV **val = hv_fetch(GvHV(PL_hintgv), __PACKAGE__, __PACKAGE_LEN__, 0);
502   if (val)
503    hint = *val;
504  }
505 #endif
506
507  if (hint && SvIOK(hint))
508   return indirect_detag(hint);
509  else {
510   dMY_CXT;
511   return MY_CXT.global_code;
512  }
513 }
514
515 /* ... op -> source position ............................................... */
516
517 static void indirect_map_store(pTHX_ const OP *o, STRLEN pos, SV *sv, line_t line) {
518 #define indirect_map_store(O, P, N, L) indirect_map_store(aTHX_ (O), (P), (N), (L))
519  indirect_op_info_t *oi;
520  const char *s;
521  STRLEN len;
522  dMY_CXT;
523
524  /* No need to check for MY_CXT.map != NULL because this code path is always
525   * guarded by indirect_hint(). */
526
527  if (!(oi = ptable_fetch(MY_CXT.map, o))) {
528   Newx(oi, 1, indirect_op_info_t);
529   ptable_store(MY_CXT.map, o, oi);
530   oi->buf  = NULL;
531   oi->size = 0;
532  }
533
534  if (sv) {
535   s = SvPV_const(sv, len);
536  } else {
537   s   = "{";
538   len = 1;
539  }
540
541  if (len > oi->size) {
542   Safefree(oi->buf);
543   Newx(oi->buf, len, char);
544   oi->size = len;
545  }
546  Copy(s, oi->buf, len, char);
547
548  oi->len  = len;
549  oi->pos  = pos;
550  oi->line = line;
551 }
552
553 static const indirect_op_info_t *indirect_map_fetch(pTHX_ const OP *o) {
554 #define indirect_map_fetch(O) indirect_map_fetch(aTHX_ (O))
555  dMY_CXT;
556
557  /* No need to check for MY_CXT.map != NULL because this code path is always
558   * guarded by indirect_hint(). */
559
560  return ptable_fetch(MY_CXT.map, o);
561 }
562
563 static void indirect_map_delete(pTHX_ const OP *o) {
564 #define indirect_map_delete(O) indirect_map_delete(aTHX_ (O))
565  dMY_CXT;
566
567  if (MY_CXT.map)
568   ptable_delete(MY_CXT.map, o);
569 }
570
571 /* --- Check functions ----------------------------------------------------- */
572
573 static int indirect_find(pTHX_ SV *name_sv, const char *line_bufptr, STRLEN *name_pos) {
574 #define indirect_find(NSV, LBP, NP) indirect_find(aTHX_ (NSV), (LBP), (NP))
575  STRLEN      name_len, line_len;
576  const char *name, *name_end;
577  const char *line, *line_end;
578  const char *p;
579
580  line     = SvPV_const(PL_linestr, line_len);
581  line_end = line + line_len;
582
583  name = SvPV_const(name_sv, name_len);
584  if (name_len >= 1 && *name == '$') {
585   ++name;
586   --name_len;
587   while (line_bufptr < line_end && *line_bufptr != '$')
588    ++line_bufptr;
589   if (line_bufptr >= line_end)
590    return 0;
591  }
592  name_end = name + name_len;
593
594  p = line_bufptr;
595  while (1) {
596   p = ninstr(p, line_end, name, name_end);
597   if (!p)
598    return 0;
599   if (!isALNUM(p[name_len]))
600    break;
601   /* p points to a word that has name as prefix, skip the rest of the word */
602   p += name_len + 1;
603   while (isALNUM(*p))
604    ++p;
605  }
606
607  *name_pos = p - line;
608
609  return 1;
610 }
611
612 /* ... ck_const ............................................................ */
613
614 static OP *(*indirect_old_ck_const)(pTHX_ OP *) = 0;
615
616 static OP *indirect_ck_const(pTHX_ OP *o) {
617  o = indirect_old_ck_const(aTHX_ o);
618
619  if (indirect_hint()) {
620   SV *sv = cSVOPo_sv;
621
622   if (SvPOK(sv) && (SvTYPE(sv) >= SVt_PV)) {
623    STRLEN pos;
624
625    if (indirect_find(sv, PL_oldbufptr, &pos)) {
626     STRLEN len;
627
628     /* If the constant is equal to the current package name, try to look for
629      * a "__PACKAGE__" coming before what we got. We only need to check this
630      * when we already had a match because __PACKAGE__ can only appear in
631      * direct method calls ("new __PACKAGE__" is a syntax error). */
632     len = SvCUR(sv);
633     if (PL_curstash
634         && len == (STRLEN) HvNAMELEN_get(PL_curstash)
635         && memcmp(SvPVX(sv), HvNAME_get(PL_curstash), len) == 0) {
636      STRLEN pos_pkg;
637      SV    *pkg = sv_newmortal();
638      sv_setpvn(pkg, "__PACKAGE__", sizeof("__PACKAGE__")-1);
639
640      if (indirect_find(pkg, PL_oldbufptr, &pos_pkg) && pos_pkg < pos) {
641       sv  = pkg;
642       pos = pos_pkg;
643      }
644     }
645
646     indirect_map_store(o, pos, sv, CopLINE(&PL_compiling));
647     return o;
648    }
649   }
650  }
651
652  indirect_map_delete(o);
653  return o;
654 }
655
656 /* ... ck_rv2sv ............................................................ */
657
658 static OP *(*indirect_old_ck_rv2sv)(pTHX_ OP *) = 0;
659
660 static OP *indirect_ck_rv2sv(pTHX_ OP *o) {
661  if (indirect_hint()) {
662   OP *op = cUNOPo->op_first;
663   SV *sv;
664   const char *name = NULL;
665   STRLEN pos, len;
666   OPCODE type = (OPCODE) op->op_type;
667
668   switch (type) {
669    case OP_GV:
670    case OP_GVSV: {
671     GV *gv = cGVOPx_gv(op);
672     name = GvNAME(gv);
673     len  = GvNAMELEN(gv);
674     break;
675    }
676    default:
677     if ((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP) {
678      SV *nsv = cSVOPx_sv(op);
679      if (SvPOK(nsv) && (SvTYPE(nsv) >= SVt_PV))
680       name = SvPV_const(nsv, len);
681     }
682   }
683   if (!name)
684    goto done;
685
686   sv = sv_2mortal(newSVpvn("$", 1));
687   sv_catpvn_nomg(sv, name, len);
688   if (!indirect_find(sv, PL_oldbufptr, &pos)) {
689    /* If it failed, retry without the current stash */
690    const char *stash = HvNAME_get(PL_curstash);
691    STRLEN stashlen = HvNAMELEN_get(PL_curstash);
692
693    if ((len < stashlen + 2) || strnNE(name, stash, stashlen)
694        || name[stashlen] != ':' || name[stashlen+1] != ':') {
695     /* Failed again ? Try to remove main */
696     stash = "main";
697     stashlen = 4;
698     if ((len < stashlen + 2) || strnNE(name, stash, stashlen)
699         || name[stashlen] != ':' || name[stashlen+1] != ':')
700      goto done;
701    }
702
703    sv_setpvn(sv, "$", 1);
704    stashlen += 2;
705    sv_catpvn_nomg(sv, name + stashlen, len - stashlen);
706    if (!indirect_find(sv, PL_oldbufptr, &pos))
707     goto done;
708   }
709
710   o = indirect_old_ck_rv2sv(aTHX_ o);
711
712   indirect_map_store(o, pos, sv, CopLINE(&PL_compiling));
713   return o;
714  }
715
716 done:
717  o = indirect_old_ck_rv2sv(aTHX_ o);
718
719  indirect_map_delete(o);
720  return o;
721 }
722
723 /* ... ck_padany ........................................................... */
724
725 static OP *(*indirect_old_ck_padany)(pTHX_ OP *) = 0;
726
727 static OP *indirect_ck_padany(pTHX_ OP *o) {
728  o = indirect_old_ck_padany(aTHX_ o);
729
730  if (indirect_hint()) {
731   SV *sv;
732   const char *s = PL_oldbufptr, *t = PL_bufptr - 1;
733
734   while (s < t && isSPACE(*s)) ++s;
735   if (*s == '$' && ++s <= t) {
736    while (s < t && isSPACE(*s)) ++s;
737    while (s < t && isSPACE(*t)) --t;
738    sv = sv_2mortal(newSVpvn("$", 1));
739    sv_catpvn_nomg(sv, s, t - s + 1);
740    indirect_map_store(o, s - SvPVX_const(PL_linestr),
741                          sv, CopLINE(&PL_compiling));
742    return o;
743   }
744  }
745
746  indirect_map_delete(o);
747  return o;
748 }
749
750 /* ... ck_scope ............................................................ */
751
752 static OP *(*indirect_old_ck_scope)  (pTHX_ OP *) = 0;
753 static OP *(*indirect_old_ck_lineseq)(pTHX_ OP *) = 0;
754
755 static OP *indirect_ck_scope(pTHX_ OP *o) {
756  OP *(*old_ck)(pTHX_ OP *) = 0;
757
758  switch (o->op_type) {
759   case OP_SCOPE:   old_ck = indirect_old_ck_scope;   break;
760   case OP_LINESEQ: old_ck = indirect_old_ck_lineseq; break;
761  }
762  o = old_ck(aTHX_ o);
763
764  if (indirect_hint()) {
765   indirect_map_store(o, PL_oldbufptr - SvPVX_const(PL_linestr),
766                         NULL, CopLINE(&PL_compiling));
767   return o;
768  }
769
770  indirect_map_delete(o);
771  return o;
772 }
773
774 /* We don't need to clean the map entries for leave ops because they can only
775  * be created by mutating from a lineseq. */
776
777 /* ... ck_method ........................................................... */
778
779 static OP *(*indirect_old_ck_method)(pTHX_ OP *) = 0;
780
781 static OP *indirect_ck_method(pTHX_ OP *o) {
782  if (indirect_hint()) {
783   OP *op = cUNOPo->op_first;
784
785   /* Indirect method call is only possible when the method is a bareword, so
786    * don't trip up on $obj->$meth. */
787   if (op && op->op_type == OP_CONST) {
788    const indirect_op_info_t *oi = indirect_map_fetch(op);
789    STRLEN pos;
790    line_t line;
791    SV *sv;
792
793    if (!oi)
794     goto done;
795
796    sv   = sv_2mortal(newSVpvn(oi->buf, oi->len));
797    pos  = oi->pos;
798    /* Keep the old line so that we really point to the first line of the
799     * expression. */
800    line = oi->line;
801
802    o = indirect_old_ck_method(aTHX_ o);
803    /* o may now be a method_named */
804
805    indirect_map_store(o, pos, sv, line);
806    return o;
807   }
808  }
809
810 done:
811  o = indirect_old_ck_method(aTHX_ o);
812
813  indirect_map_delete(o);
814  return o;
815 }
816
817 /* ... ck_method_named ..................................................... */
818
819 /* "use foo/no foo" compiles its call to import/unimport directly to a
820  * method_named op. */
821
822 static OP *(*indirect_old_ck_method_named)(pTHX_ OP *) = 0;
823
824 static OP *indirect_ck_method_named(pTHX_ OP *o) {
825  if (indirect_hint()) {
826   STRLEN pos;
827   line_t line;
828   SV *sv;
829
830   sv = cSVOPo_sv;
831   if (!SvPOK(sv) || (SvTYPE(sv) < SVt_PV))
832    goto done;
833   sv = sv_mortalcopy(sv);
834
835   if (!indirect_find(sv, PL_oldbufptr, &pos))
836    goto done;
837   line = CopLINE(&PL_compiling);
838
839   o = indirect_old_ck_method_named(aTHX_ o);
840
841   indirect_map_store(o, pos, sv, line);
842   return o;
843  }
844
845 done:
846  o = indirect_old_ck_method_named(aTHX_ o);
847
848  indirect_map_delete(o);
849  return o;
850 }
851
852 /* ... ck_entersub ......................................................... */
853
854 static OP *(*indirect_old_ck_entersub)(pTHX_ OP *) = 0;
855
856 static OP *indirect_ck_entersub(pTHX_ OP *o) {
857  SV *code = indirect_hint();
858
859  o = indirect_old_ck_entersub(aTHX_ o);
860
861  if (code) {
862   const indirect_op_info_t *moi, *ooi;
863   OP     *mop, *oop;
864   LISTOP *lop;
865
866   oop = o;
867   do {
868    lop = (LISTOP *) oop;
869    if (!(lop->op_flags & OPf_KIDS))
870     goto done;
871    oop = lop->op_first;
872   } while (oop->op_type != OP_PUSHMARK);
873   oop = OpSIBLING(oop);
874   mop = lop->op_last;
875
876   if (!oop)
877    goto done;
878
879   switch (oop->op_type) {
880    case OP_CONST:
881    case OP_RV2SV:
882    case OP_PADSV:
883    case OP_SCOPE:
884    case OP_LEAVE:
885     break;
886    default:
887     goto done;
888   }
889
890   if (mop->op_type == OP_METHOD)
891    mop = cUNOPx(mop)->op_first;
892   else if (mop->op_type != OP_METHOD_NAMED)
893    goto done;
894
895   moi = indirect_map_fetch(mop);
896   if (!moi)
897    goto done;
898
899   ooi = indirect_map_fetch(oop);
900   if (!ooi)
901    goto done;
902
903   /* When positions are identical, the method and the object must have the
904    * same name. But it also means that it is an indirect call, as "foo->foo"
905    * results in different positions. */
906   if (   moi->line < ooi->line
907       || (moi->line == ooi->line && moi->pos <= ooi->pos)) {
908    SV *file;
909    dSP;
910
911    ENTER;
912    SAVETMPS;
913
914 #ifdef USE_ITHREADS
915    file = sv_2mortal(newSVpv(CopFILE(&PL_compiling), 0));
916 #else
917    file = sv_mortalcopy(CopFILESV(&PL_compiling));
918 #endif
919
920    PUSHMARK(SP);
921    EXTEND(SP, 4);
922    mPUSHp(ooi->buf, ooi->len);
923    mPUSHp(moi->buf, moi->len);
924    PUSHs(file);
925    mPUSHu(moi->line);
926    PUTBACK;
927
928    call_sv(code, G_VOID);
929
930    PUTBACK;
931
932    FREETMPS;
933    LEAVE;
934   }
935  }
936
937 done:
938  return o;
939 }
940
941 /* --- Global setup/teardown ------------------------------------------------ */
942
943 static VOL U32 indirect_initialized = 0;
944
945 static void indirect_global_teardown(pTHX_ void *root) {
946  if (!indirect_initialized)
947   return;
948
949 #if I_MULTIPLICITY
950  if (aTHX != root)
951   return;
952 #endif
953
954  indirect_ck_restore(OP_CONST,   &indirect_old_ck_const);
955  indirect_ck_restore(OP_RV2SV,   &indirect_old_ck_rv2sv);
956  indirect_ck_restore(OP_PADANY,  &indirect_old_ck_padany);
957  indirect_ck_restore(OP_SCOPE,   &indirect_old_ck_scope);
958  indirect_ck_restore(OP_LINESEQ, &indirect_old_ck_lineseq);
959
960  indirect_ck_restore(OP_METHOD,       &indirect_old_ck_method);
961  indirect_ck_restore(OP_METHOD_NAMED, &indirect_old_ck_method_named);
962  indirect_ck_restore(OP_ENTERSUB,     &indirect_old_ck_entersub);
963
964  indirect_initialized = 0;
965
966  return;
967 }
968
969 static void indirect_global_setup(pTHX) {
970 #define indirect_global_setup() indirect_global_setup(aTHX)
971  HV *stash;
972
973  if (indirect_initialized)
974   return;
975
976  PERL_HASH(indirect_hash, __PACKAGE__, __PACKAGE_LEN__);
977
978  stash = gv_stashpvn(__PACKAGE__, __PACKAGE_LEN__, 1);
979  newCONSTSUB(stash, "I_THREADSAFE", newSVuv(I_THREADSAFE));
980  newCONSTSUB(stash, "I_FORKSAFE",   newSVuv(I_FORKSAFE));
981
982  indirect_ck_replace(OP_CONST,   indirect_ck_const,  &indirect_old_ck_const);
983  indirect_ck_replace(OP_RV2SV,   indirect_ck_rv2sv,  &indirect_old_ck_rv2sv);
984  indirect_ck_replace(OP_PADANY,  indirect_ck_padany, &indirect_old_ck_padany);
985  indirect_ck_replace(OP_SCOPE,   indirect_ck_scope,  &indirect_old_ck_scope);
986  indirect_ck_replace(OP_LINESEQ, indirect_ck_scope,  &indirect_old_ck_lineseq);
987
988  indirect_ck_replace(OP_METHOD,       indirect_ck_method,
989                                       &indirect_old_ck_method);
990  indirect_ck_replace(OP_METHOD_NAMED, indirect_ck_method_named,
991                                       &indirect_old_ck_method_named);
992  indirect_ck_replace(OP_ENTERSUB,     indirect_ck_entersub,
993                                       &indirect_old_ck_entersub);
994
995 #if I_MULTIPLICITY
996  call_atexit(indirect_global_teardown, aTHX);
997 #else
998  call_atexit(indirect_global_teardown, NULL);
999 #endif
1000
1001  indirect_initialized = 1;
1002
1003  return;
1004 }
1005
1006 /* --- Interpreter setup/teardown ------------------------------------------ */
1007
1008 static void indirect_local_teardown(pTHX_ void *param) {
1009  dMY_CXT;
1010
1011  ptable_free(MY_CXT.map);
1012  MY_CXT.map = NULL;
1013
1014 #if I_THREADSAFE
1015  ptable_hints_free(MY_CXT.tbl);
1016  MY_CXT.tbl = NULL;
1017 #endif
1018
1019  return;
1020 }
1021
1022 static void indirect_local_setup(pTHX) {
1023 #define indirect_local_setup() indirect_local_setup(aTHX)
1024  MY_CXT_INIT;
1025
1026 #if I_THREADSAFE
1027  MY_CXT.tbl         = ptable_new();
1028  MY_CXT.owner       = aTHX;
1029 #endif
1030
1031  MY_CXT.map         = ptable_new();
1032  MY_CXT.global_code = NULL;
1033
1034  call_atexit(indirect_local_teardown, NULL);
1035
1036  return;
1037 }
1038
1039 /* --- XS ------------------------------------------------------------------ */
1040
1041 MODULE = indirect      PACKAGE = indirect
1042
1043 PROTOTYPES: ENABLE
1044
1045 BOOT:
1046 {
1047  indirect_global_setup();
1048  indirect_local_setup();
1049 }
1050
1051 #if I_THREADSAFE
1052
1053 void
1054 CLONE(...)
1055 PROTOTYPE: DISABLE
1056 PREINIT:
1057  ptable *t;
1058  SV     *global_code_dup;
1059  GV     *gv;
1060 PPCODE:
1061  {
1062   indirect_ptable_clone_ud ud;
1063   dMY_CXT;
1064   t = ptable_new();
1065   indirect_ptable_clone_ud_init(ud, t, MY_CXT.owner);
1066   ptable_walk(MY_CXT.tbl, indirect_ptable_clone, &ud);
1067   global_code_dup = indirect_dup_inc(MY_CXT.global_code, &ud);
1068   indirect_ptable_clone_ud_deinit(ud);
1069  }
1070  {
1071   MY_CXT_CLONE;
1072   MY_CXT.map         = ptable_new();
1073   MY_CXT.tbl         = t;
1074   MY_CXT.owner       = aTHX;
1075   MY_CXT.global_code = global_code_dup;
1076  }
1077  gv = gv_fetchpv(__PACKAGE__ "::_THREAD_CLEANUP", 0, SVt_PVCV);
1078  if (gv) {
1079   CV *cv = GvCV(gv);
1080   if (!PL_endav)
1081    PL_endav = newAV();
1082   SvREFCNT_inc(cv);
1083   if (!av_store(PL_endav, av_len(PL_endav) + 1, (SV *) cv))
1084    SvREFCNT_dec(cv);
1085   sv_magicext((SV *) PL_endav, NULL, PERL_MAGIC_ext, &indirect_endav_vtbl, NULL, 0);
1086  }
1087  XSRETURN(0);
1088
1089 void
1090 _THREAD_CLEANUP(...)
1091 PROTOTYPE: DISABLE
1092 PPCODE:
1093  indirect_thread_cleanup(aTHX_ NULL);
1094  XSRETURN(0);
1095
1096 #endif
1097
1098 SV *
1099 _tag(SV *value)
1100 PROTOTYPE: $
1101 CODE:
1102  RETVAL = indirect_tag(value);
1103 OUTPUT:
1104  RETVAL
1105
1106 void
1107 _global(SV *code)
1108 PROTOTYPE: $
1109 PPCODE:
1110  if (!SvOK(code))
1111   code = NULL;
1112  else if (SvROK(code))
1113   code = SvRV(code);
1114  {
1115   dMY_CXT;
1116   SvREFCNT_dec(MY_CXT.global_code);
1117   MY_CXT.global_code = SvREFCNT_inc(code);
1118  }
1119  XSRETURN(0);