]> git.vpit.fr Git - perl/modules/indirect.git/blob - indirect.xs
Don't cleanup thread local storage before END blocks are executed
[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  ptable_free(MY_CXT.map);
331  ptable_hints_free(MY_CXT.tbl);
332 }
333
334 STATIC int indirect_endav_free(pTHX_ SV *sv, MAGIC *mg) {
335  SAVEDESTRUCTOR_X(indirect_thread_cleanup, NULL);
336
337  return 0;
338 }
339
340 STATIC MGVTBL indirect_endav_vtbl = {
341  0,
342  0,
343  0,
344  0,
345  indirect_endav_free
346 #if MGf_COPY
347  , 0
348 #endif
349 #if MGf_DUP
350  , 0
351 #endif
352 #if MGf_LOCAL
353  , 0
354 #endif
355 };
356
357 #endif /* I_THREADSAFE */
358
359 #if I_WORKAROUND_REQUIRE_PROPAGATION
360 STATIC IV indirect_require_tag(pTHX) {
361 #define indirect_require_tag() indirect_require_tag(aTHX)
362  const CV *cv, *outside;
363
364  cv = PL_compcv;
365
366  if (!cv) {
367   /* If for some reason the pragma is operational at run-time, try to discover
368    * the current cv in use. */
369   const PERL_SI *si;
370
371   for (si = PL_curstackinfo; si; si = si->si_prev) {
372    I32 cxix;
373
374    for (cxix = si->si_cxix; cxix >= 0; --cxix) {
375     const PERL_CONTEXT *cx = si->si_cxstack + cxix;
376
377     switch (CxTYPE(cx)) {
378      case CXt_SUB:
379      case CXt_FORMAT:
380       /* The propagation workaround is only needed up to 5.10.0 and at that
381        * time format and sub contexts were still identical. And even later the
382        * cv members offsets should have been kept the same. */
383       cv = cx->blk_sub.cv;
384       goto get_enclosing_cv;
385      case CXt_EVAL:
386       cv = cx->blk_eval.cv;
387       goto get_enclosing_cv;
388      default:
389       break;
390     }
391    }
392   }
393
394   cv = PL_main_cv;
395  }
396
397 get_enclosing_cv:
398  for (outside = CvOUTSIDE(cv); outside; outside = CvOUTSIDE(cv))
399   cv = outside;
400
401  return PTR2IV(cv);
402 }
403 #endif /* I_WORKAROUND_REQUIRE_PROPAGATION */
404
405 STATIC SV *indirect_tag(pTHX_ SV *value) {
406 #define indirect_tag(V) indirect_tag(aTHX_ (V))
407  indirect_hint_t *h;
408  SV *code = NULL;
409
410  if (SvROK(value)) {
411   value = SvRV(value);
412   if (SvTYPE(value) >= SVt_PVCV) {
413    code = value;
414    SvREFCNT_inc_simple_void_NN(code);
415   }
416  }
417
418 #if I_HINT_STRUCT
419  h = PerlMemShared_malloc(sizeof *h);
420  h->code        = code;
421 # if I_WORKAROUND_REQUIRE_PROPAGATION
422  h->require_tag = indirect_require_tag();
423 # endif /* I_WORKAROUND_REQUIRE_PROPAGATION */
424 #else  /*  I_HINT_STRUCT */
425  h = code;
426 #endif /* !I_HINT_STRUCT */
427
428 #if I_THREADSAFE
429  {
430   dMY_CXT;
431   /* We only need for the key to be an unique tag for looking up the value later
432    * Allocated memory provides convenient unique identifiers, so that's why we
433    * use the hint as the key itself. */
434   ptable_hints_store(MY_CXT.tbl, h, h);
435  }
436 #endif /* I_THREADSAFE */
437
438  return newSViv(PTR2IV(h));
439 }
440
441 STATIC SV *indirect_detag(pTHX_ const SV *hint) {
442 #define indirect_detag(H) indirect_detag(aTHX_ (H))
443  indirect_hint_t *h;
444 #if I_THREADSAFE || I_WORKAROUND_REQUIRE_PROPAGATION
445  dMY_CXT;
446 #endif
447
448  h = INT2PTR(indirect_hint_t *, SvIVX(hint));
449 #if I_THREADSAFE
450  h = ptable_fetch(MY_CXT.tbl, h);
451 #endif /* I_THREADSAFE */
452
453 #if I_WORKAROUND_REQUIRE_PROPAGATION
454  if (indirect_require_tag() != h->require_tag)
455   return MY_CXT.global_code;
456 #endif /* I_WORKAROUND_REQUIRE_PROPAGATION */
457
458  return I_HINT_CODE(h);
459 }
460
461 STATIC U32 indirect_hash = 0;
462
463 STATIC SV *indirect_hint(pTHX) {
464 #define indirect_hint() indirect_hint(aTHX)
465  SV *hint = NULL;
466
467  if (IN_PERL_RUNTIME)
468   return NULL;
469
470 #if I_HAS_PERL(5, 10, 0) || defined(PL_parser)
471  if (!PL_parser)
472   return NULL;
473 #endif
474
475 #ifdef cop_hints_fetch_pvn
476  hint = cop_hints_fetch_pvn(PL_curcop, __PACKAGE__, __PACKAGE_LEN__,
477                                                               indirect_hash, 0);
478 #elif I_HAS_PERL(5, 9, 5)
479  hint = Perl_refcounted_he_fetch(aTHX_ PL_curcop->cop_hints_hash,
480                                        NULL,
481                                        __PACKAGE__, __PACKAGE_LEN__,
482                                        0,
483                                        indirect_hash);
484 #else
485  {
486   SV **val = hv_fetch(GvHV(PL_hintgv), __PACKAGE__, __PACKAGE_LEN__, 0);
487   if (val)
488    hint = *val;
489  }
490 #endif
491
492  if (hint && SvIOK(hint))
493   return indirect_detag(hint);
494  else {
495   dMY_CXT;
496   return MY_CXT.global_code;
497  }
498 }
499
500 /* ... op -> source position ............................................... */
501
502 STATIC void indirect_map_store(pTHX_ const OP *o, STRLEN pos, SV *sv, line_t line) {
503 #define indirect_map_store(O, P, N, L) indirect_map_store(aTHX_ (O), (P), (N), (L))
504  indirect_op_info_t *oi;
505  const char *s;
506  STRLEN len;
507  dMY_CXT;
508
509  if (!(oi = ptable_fetch(MY_CXT.map, o))) {
510   Newx(oi, 1, indirect_op_info_t);
511   ptable_store(MY_CXT.map, o, oi);
512   oi->buf  = NULL;
513   oi->size = 0;
514  }
515
516  if (sv) {
517   s = SvPV_const(sv, len);
518  } else {
519   s   = "{";
520   len = 1;
521  }
522
523  if (len > oi->size) {
524   Safefree(oi->buf);
525   Newx(oi->buf, len, char);
526   oi->size = len;
527  }
528  Copy(s, oi->buf, len, char);
529
530  oi->len  = len;
531  oi->pos  = pos;
532  oi->line = line;
533 }
534
535 STATIC const indirect_op_info_t *indirect_map_fetch(pTHX_ const OP *o) {
536 #define indirect_map_fetch(O) indirect_map_fetch(aTHX_ (O))
537  dMY_CXT;
538
539  return ptable_fetch(MY_CXT.map, o);
540 }
541
542 STATIC void indirect_map_delete(pTHX_ const OP *o) {
543 #define indirect_map_delete(O) indirect_map_delete(aTHX_ (O))
544  dMY_CXT;
545
546  ptable_delete(MY_CXT.map, o);
547 }
548
549 /* --- Check functions ----------------------------------------------------- */
550
551 STATIC int indirect_find(pTHX_ SV *name_sv, const char *line_bufptr, STRLEN *name_pos) {
552 #define indirect_find(NSV, LBP, NP) indirect_find(aTHX_ (NSV), (LBP), (NP))
553  STRLEN      name_len, line_len;
554  const char *name, *name_end;
555  const char *line, *line_end;
556  const char *p;
557
558  line     = SvPV_const(PL_linestr, line_len);
559  line_end = line + line_len;
560
561  name = SvPV_const(name_sv, name_len);
562  if (name_len >= 1 && *name == '$') {
563   ++name;
564   --name_len;
565   while (line_bufptr < line_end && *line_bufptr != '$')
566    ++line_bufptr;
567   if (line_bufptr >= line_end)
568    return 0;
569  }
570  name_end = name + name_len;
571
572  p = line_bufptr;
573  while (1) {
574   p = ninstr(p, line_end, name, name_end);
575   if (!p)
576    return 0;
577   if (!isALNUM(p[name_len]))
578    break;
579   /* p points to a word that has name as prefix, skip the rest of the word */
580   p += name_len + 1;
581   while (isALNUM(*p))
582    ++p;
583  }
584
585  *name_pos = p - line;
586
587  return 1;
588 }
589
590 /* ... ck_const ............................................................ */
591
592 STATIC OP *(*indirect_old_ck_const)(pTHX_ OP *) = 0;
593
594 STATIC OP *indirect_ck_const(pTHX_ OP *o) {
595  o = indirect_old_ck_const(aTHX_ o);
596
597  if (indirect_hint()) {
598   SV *sv = cSVOPo_sv;
599
600   if (SvPOK(sv) && (SvTYPE(sv) >= SVt_PV)) {
601    STRLEN pos;
602
603    if (indirect_find(sv, PL_oldbufptr, &pos)) {
604     STRLEN len;
605
606     /* If the constant is equal to the current package name, try to look for
607      * a "__PACKAGE__" coming before what we got. We only need to check this
608      * when we already had a match because __PACKAGE__ can only appear in
609      * direct method calls ("new __PACKAGE__" is a syntax error). */
610     len = SvCUR(sv);
611     if (PL_curstash
612         && len == (STRLEN) HvNAMELEN_get(PL_curstash)
613         && memcmp(SvPVX(sv), HvNAME_get(PL_curstash), len) == 0) {
614      STRLEN pos_pkg;
615      SV    *pkg = sv_newmortal();
616      sv_setpvn(pkg, "__PACKAGE__", sizeof("__PACKAGE__")-1);
617
618      if (indirect_find(pkg, PL_oldbufptr, &pos_pkg) && pos_pkg < pos) {
619       sv  = pkg;
620       pos = pos_pkg;
621      }
622     }
623
624     indirect_map_store(o, pos, sv, CopLINE(&PL_compiling));
625     return o;
626    }
627   }
628  }
629
630  indirect_map_delete(o);
631  return o;
632 }
633
634 /* ... ck_rv2sv ............................................................ */
635
636 STATIC OP *(*indirect_old_ck_rv2sv)(pTHX_ OP *) = 0;
637
638 STATIC OP *indirect_ck_rv2sv(pTHX_ OP *o) {
639  if (indirect_hint()) {
640   OP *op = cUNOPo->op_first;
641   SV *sv;
642   const char *name = NULL;
643   STRLEN pos, len;
644   OPCODE type = (OPCODE) op->op_type;
645
646   switch (type) {
647    case OP_GV:
648    case OP_GVSV: {
649     GV *gv = cGVOPx_gv(op);
650     name = GvNAME(gv);
651     len  = GvNAMELEN(gv);
652     break;
653    }
654    default:
655     if ((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP) {
656      SV *nsv = cSVOPx_sv(op);
657      if (SvPOK(nsv) && (SvTYPE(nsv) >= SVt_PV))
658       name = SvPV_const(nsv, len);
659     }
660   }
661   if (!name)
662    goto done;
663
664   sv = sv_2mortal(newSVpvn("$", 1));
665   sv_catpvn_nomg(sv, name, len);
666   if (!indirect_find(sv, PL_oldbufptr, &pos)) {
667    /* If it failed, retry without the current stash */
668    const char *stash = HvNAME_get(PL_curstash);
669    STRLEN stashlen = HvNAMELEN_get(PL_curstash);
670
671    if ((len < stashlen + 2) || strnNE(name, stash, stashlen)
672        || name[stashlen] != ':' || name[stashlen+1] != ':') {
673     /* Failed again ? Try to remove main */
674     stash = "main";
675     stashlen = 4;
676     if ((len < stashlen + 2) || strnNE(name, stash, stashlen)
677         || name[stashlen] != ':' || name[stashlen+1] != ':')
678      goto done;
679    }
680
681    sv_setpvn(sv, "$", 1);
682    stashlen += 2;
683    sv_catpvn_nomg(sv, name + stashlen, len - stashlen);
684    if (!indirect_find(sv, PL_oldbufptr, &pos))
685     goto done;
686   }
687
688   o = indirect_old_ck_rv2sv(aTHX_ o);
689
690   indirect_map_store(o, pos, sv, CopLINE(&PL_compiling));
691   return o;
692  }
693
694 done:
695  o = indirect_old_ck_rv2sv(aTHX_ o);
696
697  indirect_map_delete(o);
698  return o;
699 }
700
701 /* ... ck_padany ........................................................... */
702
703 STATIC OP *(*indirect_old_ck_padany)(pTHX_ OP *) = 0;
704
705 STATIC OP *indirect_ck_padany(pTHX_ OP *o) {
706  o = indirect_old_ck_padany(aTHX_ o);
707
708  if (indirect_hint()) {
709   SV *sv;
710   const char *s = PL_oldbufptr, *t = PL_bufptr - 1;
711
712   while (s < t && isSPACE(*s)) ++s;
713   if (*s == '$' && ++s <= t) {
714    while (s < t && isSPACE(*s)) ++s;
715    while (s < t && isSPACE(*t)) --t;
716    sv = sv_2mortal(newSVpvn("$", 1));
717    sv_catpvn_nomg(sv, s, t - s + 1);
718    indirect_map_store(o, s - SvPVX_const(PL_linestr),
719                          sv, CopLINE(&PL_compiling));
720    return o;
721   }
722  }
723
724  indirect_map_delete(o);
725  return o;
726 }
727
728 /* ... ck_scope ............................................................ */
729
730 STATIC OP *(*indirect_old_ck_scope)  (pTHX_ OP *) = 0;
731 STATIC OP *(*indirect_old_ck_lineseq)(pTHX_ OP *) = 0;
732
733 STATIC OP *indirect_ck_scope(pTHX_ OP *o) {
734  OP *(*old_ck)(pTHX_ OP *) = 0;
735
736  switch (o->op_type) {
737   case OP_SCOPE:   old_ck = indirect_old_ck_scope;   break;
738   case OP_LINESEQ: old_ck = indirect_old_ck_lineseq; break;
739  }
740  o = old_ck(aTHX_ o);
741
742  if (indirect_hint()) {
743   indirect_map_store(o, PL_oldbufptr - SvPVX_const(PL_linestr),
744                         NULL, CopLINE(&PL_compiling));
745   return o;
746  }
747
748  indirect_map_delete(o);
749  return o;
750 }
751
752 /* We don't need to clean the map entries for leave ops because they can only
753  * be created by mutating from a lineseq. */
754
755 /* ... ck_method ........................................................... */
756
757 STATIC OP *(*indirect_old_ck_method)(pTHX_ OP *) = 0;
758
759 STATIC OP *indirect_ck_method(pTHX_ OP *o) {
760  if (indirect_hint()) {
761   OP *op = cUNOPo->op_first;
762
763   /* Indirect method call is only possible when the method is a bareword, so
764    * don't trip up on $obj->$meth. */
765   if (op && op->op_type == OP_CONST) {
766    const indirect_op_info_t *oi = indirect_map_fetch(op);
767    STRLEN pos;
768    line_t line;
769    SV *sv;
770
771    if (!oi)
772     goto done;
773
774    sv   = sv_2mortal(newSVpvn(oi->buf, oi->len));
775    pos  = oi->pos;
776    /* Keep the old line so that we really point to the first line of the
777     * expression. */
778    line = oi->line;
779
780    o = indirect_old_ck_method(aTHX_ o);
781    /* o may now be a method_named */
782
783    indirect_map_store(o, pos, sv, line);
784    return o;
785   }
786  }
787
788 done:
789  o = indirect_old_ck_method(aTHX_ o);
790
791  indirect_map_delete(o);
792  return o;
793 }
794
795 /* ... ck_method_named ..................................................... */
796
797 /* "use foo/no foo" compiles its call to import/unimport directly to a
798  * method_named op. */
799
800 STATIC OP *(*indirect_old_ck_method_named)(pTHX_ OP *) = 0;
801
802 STATIC OP *indirect_ck_method_named(pTHX_ OP *o) {
803  if (indirect_hint()) {
804   STRLEN pos;
805   line_t line;
806   SV *sv;
807
808   sv = cSVOPo_sv;
809   if (!SvPOK(sv) || (SvTYPE(sv) < SVt_PV))
810    goto done;
811   sv = sv_mortalcopy(sv);
812
813   if (!indirect_find(sv, PL_oldbufptr, &pos))
814    goto done;
815   line = CopLINE(&PL_compiling);
816
817   o = indirect_old_ck_method_named(aTHX_ o);
818
819   indirect_map_store(o, pos, sv, line);
820   return o;
821  }
822
823 done:
824  o = indirect_old_ck_method_named(aTHX_ o);
825
826  indirect_map_delete(o);
827  return o;
828 }
829
830 /* ... ck_entersub ......................................................... */
831
832 STATIC OP *(*indirect_old_ck_entersub)(pTHX_ OP *) = 0;
833
834 STATIC OP *indirect_ck_entersub(pTHX_ OP *o) {
835  SV *code = indirect_hint();
836
837  o = indirect_old_ck_entersub(aTHX_ o);
838
839  if (code) {
840   const indirect_op_info_t *moi, *ooi;
841   OP     *mop, *oop;
842   LISTOP *lop;
843
844   oop = o;
845   do {
846    lop = (LISTOP *) oop;
847    if (!(lop->op_flags & OPf_KIDS))
848     goto done;
849    oop = lop->op_first;
850   } while (oop->op_type != OP_PUSHMARK);
851   oop = OP_SIBLING(oop);
852   mop = lop->op_last;
853
854   if (!oop)
855    goto done;
856
857   switch (oop->op_type) {
858    case OP_CONST:
859    case OP_RV2SV:
860    case OP_PADSV:
861    case OP_SCOPE:
862    case OP_LEAVE:
863     break;
864    default:
865     goto done;
866   }
867
868   if (mop->op_type == OP_METHOD)
869    mop = cUNOPx(mop)->op_first;
870   else if (mop->op_type != OP_METHOD_NAMED)
871    goto done;
872
873   moi = indirect_map_fetch(mop);
874   if (!moi)
875    goto done;
876
877   ooi = indirect_map_fetch(oop);
878   if (!ooi)
879    goto done;
880
881   /* When positions are identical, the method and the object must have the
882    * same name. But it also means that it is an indirect call, as "foo->foo"
883    * results in different positions. */
884   if (   moi->line < ooi->line
885       || (moi->line == ooi->line && moi->pos <= ooi->pos)) {
886    SV *file;
887    dSP;
888
889    ENTER;
890    SAVETMPS;
891
892 #ifdef USE_ITHREADS
893    file = sv_2mortal(newSVpv(CopFILE(&PL_compiling), 0));
894 #else
895    file = sv_mortalcopy(CopFILESV(&PL_compiling));
896 #endif
897
898    PUSHMARK(SP);
899    EXTEND(SP, 4);
900    mPUSHp(ooi->buf, ooi->len);
901    mPUSHp(moi->buf, moi->len);
902    PUSHs(file);
903    mPUSHu(moi->line);
904    PUTBACK;
905
906    call_sv(code, G_VOID);
907
908    PUTBACK;
909
910    FREETMPS;
911    LEAVE;
912   }
913  }
914
915 done:
916  return o;
917 }
918
919 STATIC U32 indirect_initialized = 0;
920
921 STATIC void indirect_teardown(pTHX_ void *root) {
922  if (!indirect_initialized)
923   return;
924
925 #if I_MULTIPLICITY
926  if (aTHX != root)
927   return;
928 #endif
929
930  {
931   dMY_CXT;
932   ptable_free(MY_CXT.map);
933 #if I_THREADSAFE
934   ptable_hints_free(MY_CXT.tbl);
935 #endif
936  }
937
938  indirect_ck_restore(OP_CONST,   &indirect_old_ck_const);
939  indirect_ck_restore(OP_RV2SV,   &indirect_old_ck_rv2sv);
940  indirect_ck_restore(OP_PADANY,  &indirect_old_ck_padany);
941  indirect_ck_restore(OP_SCOPE,   &indirect_old_ck_scope);
942  indirect_ck_restore(OP_LINESEQ, &indirect_old_ck_lineseq);
943
944  indirect_ck_restore(OP_METHOD,       &indirect_old_ck_method);
945  indirect_ck_restore(OP_METHOD_NAMED, &indirect_old_ck_method_named);
946  indirect_ck_restore(OP_ENTERSUB,     &indirect_old_ck_entersub);
947
948  indirect_initialized = 0;
949 }
950
951 STATIC void indirect_setup(pTHX) {
952 #define indirect_setup() indirect_setup(aTHX)
953  if (indirect_initialized)
954   return;
955
956  {
957   MY_CXT_INIT;
958 #if I_THREADSAFE
959   MY_CXT.tbl         = ptable_new();
960   MY_CXT.owner       = aTHX;
961 #endif
962   MY_CXT.map         = ptable_new();
963   MY_CXT.global_code = NULL;
964  }
965
966  indirect_ck_replace(OP_CONST,   indirect_ck_const,  &indirect_old_ck_const);
967  indirect_ck_replace(OP_RV2SV,   indirect_ck_rv2sv,  &indirect_old_ck_rv2sv);
968  indirect_ck_replace(OP_PADANY,  indirect_ck_padany, &indirect_old_ck_padany);
969  indirect_ck_replace(OP_SCOPE,   indirect_ck_scope,  &indirect_old_ck_scope);
970  indirect_ck_replace(OP_LINESEQ, indirect_ck_scope,  &indirect_old_ck_lineseq);
971
972  indirect_ck_replace(OP_METHOD,       indirect_ck_method,
973                                       &indirect_old_ck_method);
974  indirect_ck_replace(OP_METHOD_NAMED, indirect_ck_method_named,
975                                       &indirect_old_ck_method_named);
976  indirect_ck_replace(OP_ENTERSUB,     indirect_ck_entersub,
977                                       &indirect_old_ck_entersub);
978
979 #if I_MULTIPLICITY
980  call_atexit(indirect_teardown, aTHX);
981 #else
982  call_atexit(indirect_teardown, NULL);
983 #endif
984
985  indirect_initialized = 1;
986 }
987
988 STATIC U32 indirect_booted = 0;
989
990 /* --- XS ------------------------------------------------------------------ */
991
992 MODULE = indirect      PACKAGE = indirect
993
994 PROTOTYPES: ENABLE
995
996 BOOT:
997 {
998  if (!indirect_booted++) {
999   HV *stash;
1000
1001   PERL_HASH(indirect_hash, __PACKAGE__, __PACKAGE_LEN__);
1002
1003   stash = gv_stashpvn(__PACKAGE__, __PACKAGE_LEN__, 1);
1004   newCONSTSUB(stash, "I_THREADSAFE", newSVuv(I_THREADSAFE));
1005   newCONSTSUB(stash, "I_FORKSAFE",   newSVuv(I_FORKSAFE));
1006  }
1007
1008  indirect_setup();
1009 }
1010
1011 #if I_THREADSAFE
1012
1013 void
1014 CLONE(...)
1015 PROTOTYPE: DISABLE
1016 PREINIT:
1017  ptable *t;
1018  SV     *global_code_dup;
1019  GV     *gv;
1020 PPCODE:
1021  {
1022   my_cxt_t ud;
1023   dMY_CXT;
1024   ud.tbl   = t = ptable_new();
1025   ud.owner = MY_CXT.owner;
1026   ptable_walk(MY_CXT.tbl, indirect_ptable_clone, &ud);
1027   global_code_dup = indirect_clone(MY_CXT.global_code, MY_CXT.owner);
1028  }
1029  {
1030   MY_CXT_CLONE;
1031   MY_CXT.map         = ptable_new();
1032   MY_CXT.tbl         = t;
1033   MY_CXT.owner       = aTHX;
1034   MY_CXT.global_code = global_code_dup;
1035  }
1036  gv = gv_fetchpv(__PACKAGE__ "::_THREAD_CLEANUP", 0, SVt_PVCV);
1037  if (gv) {
1038   CV *cv = GvCV(gv);
1039   if (!PL_endav)
1040    PL_endav = newAV();
1041   SvREFCNT_inc(cv);
1042   if (!av_store(PL_endav, av_len(PL_endav) + 1, (SV *) cv))
1043    SvREFCNT_dec(cv);
1044   sv_magicext((SV *) PL_endav, NULL, PERL_MAGIC_ext, &indirect_endav_vtbl, NULL, 0);
1045  }
1046  XSRETURN(0);
1047
1048 void
1049 _THREAD_CLEANUP(...)
1050 PROTOTYPE: DISABLE
1051 PPCODE:
1052  indirect_thread_cleanup(aTHX_ NULL);
1053  XSRETURN(0);
1054
1055 #endif
1056
1057 SV *
1058 _tag(SV *value)
1059 PROTOTYPE: $
1060 CODE:
1061  RETVAL = indirect_tag(value);
1062 OUTPUT:
1063  RETVAL
1064
1065 void
1066 _global(SV *code)
1067 PROTOTYPE: $
1068 PPCODE:
1069  if (!SvOK(code))
1070   code = NULL;
1071  else if (SvROK(code))
1072   code = SvRV(code);
1073  {
1074   dMY_CXT;
1075   SvREFCNT_dec(MY_CXT.global_code);
1076   MY_CXT.global_code = SvREFCNT_inc(code);
1077  }
1078  XSRETURN(0);