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