This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perlapi: XS, XS_EXTERNAL do take a parameter
[perl5.git] / ext / Opcode / Opcode.xs
1 #define PERL_NO_GET_CONTEXT
2 #include "EXTERN.h"
3 #include "perl.h"
4 #include "XSUB.h"
5
6 /* PL_maxo shouldn't differ from MAXO but leave room anyway (see BOOT:) */
7 #define OP_MASK_BUF_SIZE (MAXO + 100)
8
9 /* XXX op_named_bits and opset_all are never freed */
10 #define MY_CXT_KEY "Opcode::_guts" XS_VERSION
11
12 typedef struct {
13     HV *        x_op_named_bits;        /* cache shared for whole process */
14     SV *        x_opset_all;            /* mask with all bits set       */
15     IV          x_opset_len;            /* length of opmasks in bytes   */
16 #ifdef OPCODE_DEBUG
17     int         x_opcode_debug;         /* unused warn() emitting debugging code */
18 #endif
19 } my_cxt_t;
20
21 START_MY_CXT
22
23 #define op_named_bits           (MY_CXT.x_op_named_bits)
24 #define opset_all               (MY_CXT.x_opset_all)
25 #define opset_len               (MY_CXT.x_opset_len)
26 #ifdef OPCODE_DEBUG
27 #  define opcode_debug          (MY_CXT.x_opcode_debug)
28 #else
29  /* no API to turn this on at runtime, so constant fold the code away */
30 #  define opcode_debug          0
31 #endif
32
33 static SV  *new_opset (pTHX_ SV *old_opset);
34 static int  verify_opset (pTHX_ SV *opset, int fatal);
35 static void set_opset_bits (pTHX_ char *bitmap, SV *bitspec, int on, const char *opname);
36 static void put_op_bitspec (pTHX_ const char *optag,  STRLEN len, SV *opset);
37 static SV  *get_op_bitspec (pTHX_ const char *opname, STRLEN len, int fatal);
38
39
40 /* Initialise our private op_named_bits HV.
41  * It is first loaded with the name and number of each perl operator.
42  * Then the builtin tags :none and :all are added.
43  * Opcode.pm loads the standard optags from __DATA__
44  * XXX leak-alert: data allocated here is never freed, call this
45  *     at most once
46  */
47
48 static void
49 op_names_init(pTHX)
50 {
51     int i;
52     STRLEN len;
53     char **op_names;
54     U8 *bitmap;
55     dMY_CXT;
56
57     op_named_bits = newHV();
58     op_names = get_op_names();
59     for(i=0; i < PL_maxo; ++i) {
60         SV * const sv = newSViv(i);
61         SvREADONLY_on(sv);
62         (void) hv_store(op_named_bits, op_names[i], strlen(op_names[i]), sv, 0);
63     }
64
65     put_op_bitspec(aTHX_ STR_WITH_LEN(":none"), sv_2mortal(new_opset(aTHX_ Nullsv)));
66
67     opset_all = new_opset(aTHX_ Nullsv);
68     bitmap = (U8*)SvPV(opset_all, len);
69     memset(bitmap, 0xFF, len-1); /* deal with last byte specially, see below */
70     /* Take care to set the right number of bits in the last byte */
71     bitmap[len-1] = (PL_maxo & 0x07) ? ((~(0xFF << (PL_maxo & 0x07))) & 0xFF)
72                                      : 0xFF;
73     put_op_bitspec(aTHX_ STR_WITH_LEN(":all"), opset_all); /* don't mortalise */
74 }
75
76
77 /* Store a new tag definition. Always a mask.
78  * The tag must not already be defined.
79  * SV *mask is copied not referenced.
80  */
81
82 static void
83 put_op_bitspec(pTHX_ const char *optag, STRLEN len, SV *mask)
84 {
85     SV **svp;
86     dMY_CXT;
87
88     verify_opset(aTHX_ mask,1);
89     svp = hv_fetch(op_named_bits, optag, len, 1);
90     if (SvOK(*svp))
91         croak("Opcode tag \"%s\" already defined", optag);
92     sv_setsv(*svp, mask);
93     SvREADONLY_on(*svp);
94 }
95
96
97
98 /* Fetch a 'bits' entry for an opname or optag (IV/PV).
99  * Note that we return the actual entry for speed.
100  * Always sv_mortalcopy() if returning it to user code.
101  */
102
103 static SV *
104 get_op_bitspec(pTHX_ const char *opname, STRLEN len, int fatal)
105 {
106     SV **svp;
107     dMY_CXT;
108
109     svp = hv_fetch(op_named_bits, opname, len, 0);
110     if (!svp || !SvOK(*svp)) {
111         if (!fatal)
112             return Nullsv;
113         if (*opname == ':')
114             croak("Unknown operator tag \"%s\"", opname);
115         if (*opname == '!')     /* XXX here later, or elsewhere? */
116             croak("Can't negate operators here (\"%s\")", opname);
117         if (isALPHA(*opname))
118             croak("Unknown operator name \"%s\"", opname);
119         croak("Unknown operator prefix \"%s\"", opname);
120     }
121     return *svp;
122 }
123
124
125
126 static SV *
127 new_opset(pTHX_ SV *old_opset)
128 {
129     SV *opset;
130     dMY_CXT;
131
132     if (old_opset) {
133         verify_opset(aTHX_ old_opset,1);
134         opset = newSVsv(old_opset);
135     }
136     else {
137         opset = newSV(opset_len);
138         Zero(SvPVX_const(opset), opset_len + 1, char);
139         SvCUR_set(opset, opset_len);
140         (void)SvPOK_only(opset);
141     }
142     /* not mortalised here */
143     return opset;
144 }
145
146
147 static int
148 verify_opset(pTHX_ SV *opset, int fatal)
149 {
150     const char *err = NULL;
151     dMY_CXT;
152
153     if      (!SvOK(opset))              err = "undefined";
154     else if (!SvPOK(opset))             err = "wrong type";
155     else if (SvCUR(opset) != (STRLEN)opset_len) err = "wrong size";
156     if (err && fatal) {
157         croak("Invalid opset: %s", err);
158     }
159     return !err;
160 }
161
162
163 static void
164 set_opset_bits(pTHX_ char *bitmap, SV *bitspec, int on, const char *opname)
165 {
166     dMY_CXT;
167
168     if (SvIOK(bitspec)) {
169         const int myopcode = SvIV(bitspec);
170         const int offset = myopcode >> 3;
171         const int bit    = myopcode & 0x07;
172         if (myopcode >= PL_maxo || myopcode < 0)
173             croak("panic: opcode \"%s\" value %d is invalid", opname, myopcode);
174         if (opcode_debug >= 2)
175             warn("set_opset_bits bit %2d (off=%d, bit=%d) %s %s\n",
176                         myopcode, offset, bit, opname, (on)?"on":"off");
177         if (on)
178             bitmap[offset] |= 1 << bit;
179         else
180             bitmap[offset] &= ~(1 << bit);
181     }
182     else if (SvPOK(bitspec) && SvCUR(bitspec) == (STRLEN)opset_len) {
183
184         STRLEN len;
185         const char * const specbits = SvPV(bitspec, len);
186         if (opcode_debug >= 2)
187             warn("set_opset_bits opset %s %s\n", opname, (on)?"on":"off");
188         if (on) 
189             while(len-- > 0) bitmap[len] |=  specbits[len];
190         else
191             while(len-- > 0) bitmap[len] &= ~specbits[len];
192     }
193     else
194         croak("panic: invalid bitspec for \"%s\" (type %u)",
195                 opname, (unsigned)SvTYPE(bitspec));
196 }
197
198
199 static void
200 opmask_add(pTHX_ SV *opset)     /* THE ONLY FUNCTION TO EDIT PL_op_mask ITSELF  */
201 {
202     int i,j;
203     char *bitmask;
204     STRLEN len;
205     int myopcode = 0;
206     dMY_CXT;
207
208     verify_opset(aTHX_ opset,1);                /* croaks on bad opset  */
209
210     if (!PL_op_mask)            /* caller must ensure PL_op_mask exists */
211         croak("Can't add to uninitialised PL_op_mask");
212
213     /* OPCODES ALREADY MASKED ARE NEVER UNMASKED. See opmask_addlocal() */
214
215     bitmask = SvPV(opset, len);
216     for (i=0; i < opset_len; i++) {
217         const U16 bits = bitmask[i];
218         if (!bits) {    /* optimise for sparse masks */
219             myopcode += 8;
220             continue;
221         }
222         for (j=0; j < 8 && myopcode < PL_maxo; )
223             PL_op_mask[myopcode++] |= bits & (1 << j++);
224     }
225 }
226
227 static void
228 opmask_addlocal(pTHX_ SV *opset, char *op_mask_buf) /* Localise PL_op_mask then opmask_add() */
229 {
230     char *orig_op_mask = PL_op_mask;
231 #ifdef OPCODE_DEBUG
232     dMY_CXT;
233 #endif
234
235     SAVEVPTR(PL_op_mask);
236     /* XXX casting to an ordinary function ptr from a member function ptr
237      * is disallowed by Borland
238      */
239     if (opcode_debug >= 2)
240         SAVEDESTRUCTOR((void(*)(void*))Perl_warn,"PL_op_mask restored");
241     PL_op_mask = &op_mask_buf[0];
242     if (orig_op_mask)
243         Copy(orig_op_mask, PL_op_mask, PL_maxo, char);
244     else
245         Zero(PL_op_mask, PL_maxo, char);
246     opmask_add(aTHX_ opset);
247 }
248
249
250
251 MODULE = Opcode PACKAGE = Opcode
252
253 PROTOTYPES: ENABLE
254
255 BOOT:
256 {
257     MY_CXT_INIT;
258     STATIC_ASSERT_STMT(PL_maxo < OP_MASK_BUF_SIZE);
259     opset_len = (PL_maxo + 7) / 8;
260     if (opcode_debug >= 1)
261         warn("opset_len %ld\n", (long)opset_len);
262     op_names_init(aTHX);
263 }
264
265 void
266 _safe_pkg_prep(Package)
267     SV *Package
268 PPCODE:
269     HV *hv; 
270     char *hvname;
271     ENTER;
272    
273     hv = gv_stashsv(Package, GV_ADDWARN); /* should exist already       */
274
275     hvname = HvNAME_get(hv);
276     if (!hvname || strNE(hvname, "main")) {
277         /* make it think it's in main:: */
278         hv_name_set(hv, "main", 4, 0);
279         (void) hv_store(hv,"_",1,(SV *)PL_defgv,0);  /* connect _ to global */
280         SvREFCNT_inc((SV *)PL_defgv);  /* want to keep _ around! */
281     }
282     LEAVE;
283
284
285
286
287
288 void
289 _safe_call_sv(Package, mask, codesv)
290     SV *        Package
291     SV *        mask
292     SV *        codesv
293 PPCODE:
294     char op_mask_buf[OP_MASK_BUF_SIZE];
295     GV *gv;
296     HV *dummy_hv;
297
298     ENTER;
299
300     opmask_addlocal(aTHX_ mask, op_mask_buf);
301
302     save_aptr(&PL_endav);
303     PL_endav = (AV*)sv_2mortal((SV*)newAV()); /* ignore END blocks for now      */
304
305     save_hptr(&PL_defstash);            /* save current default stash   */
306     /* the assignment to global defstash changes our sense of 'main'    */
307     PL_defstash = gv_stashsv(Package, GV_ADDWARN); /* should exist already      */
308
309     SAVEGENERICSV(PL_curstash);
310     PL_curstash = (HV *)SvREFCNT_inc_simple(PL_defstash);
311
312     /* defstash must itself contain a main:: so we'll add that now      */
313     /* take care with the ref counts (was cause of long standing bug)   */
314     /* XXX I'm still not sure if this is right, GV_ADDWARN should warn! */
315     gv = gv_fetchpvs("main::", GV_ADDWARN, SVt_PVHV);
316     sv_free((SV*)GvHV(gv));
317     GvHV(gv) = (HV*)SvREFCNT_inc(PL_defstash);
318
319     /* %INC must be clean for use/require in compartment */
320     dummy_hv = save_hash(PL_incgv);
321     GvHV(PL_incgv) = (HV*)SvREFCNT_inc(GvHV(gv_HVadd(gv_fetchpvs("INC",GV_ADD,SVt_PVHV))));
322
323     /* Invalidate class and method caches */
324     ++PL_sub_generation;
325     hv_clear(PL_stashcache);
326
327     PUSHMARK(SP);
328     /* use caller’s context */
329     perl_call_sv(codesv, GIMME_V|G_EVAL|G_KEEPERR);
330     sv_free( (SV *) dummy_hv);  /* get rid of what save_hash gave us*/
331     SPAGAIN; /* for the PUTBACK added by xsubpp */
332     LEAVE;
333
334     /* Invalidate again */
335     ++PL_sub_generation;
336     hv_clear(PL_stashcache);
337
338
339 int
340 verify_opset(opset, fatal = 0)
341     SV *opset
342     int fatal
343 CODE:
344     RETVAL = verify_opset(aTHX_ opset,fatal);
345 OUTPUT:
346     RETVAL
347
348 void
349 invert_opset(opset)
350     SV *opset
351 CODE:
352     {
353     char *bitmap;
354     dMY_CXT;
355     STRLEN len = opset_len;
356
357     opset = sv_2mortal(new_opset(aTHX_ opset)); /* verify and clone opset */
358     bitmap = SvPVX(opset);
359     while(len-- > 0)
360         bitmap[len] = ~bitmap[len];
361     /* take care of extra bits beyond PL_maxo in last byte      */
362     if (PL_maxo & 07)
363         bitmap[opset_len-1] &= ~(char)(0xFF << (PL_maxo & 0x07));
364     }
365     ST(0) = opset;
366
367
368 void
369 opset_to_ops(opset, desc = 0)
370     SV *opset
371     int desc
372 PPCODE:
373     {
374     STRLEN len;
375     int i, j, myopcode;
376     const char * const bitmap = SvPV(opset, len);
377     char **names = (desc) ? get_op_descs() : get_op_names();
378     dMY_CXT;
379
380     verify_opset(aTHX_ opset,1);
381     for (myopcode=0, i=0; i < opset_len; i++) {
382         const U16 bits = bitmap[i];
383         for (j=0; j < 8 && myopcode < PL_maxo; j++, myopcode++) {
384             if ( bits & (1 << j) )
385                 XPUSHs(newSVpvn_flags(names[myopcode], strlen(names[myopcode]),
386                                       SVs_TEMP));
387         }
388     }
389     }
390
391
392 void
393 opset(...)
394 CODE:
395     int i;
396     SV *bitspec;
397     STRLEN len, on;
398
399     SV * const opset = sv_2mortal(new_opset(aTHX_ Nullsv));
400     char * const bitmap = SvPVX(opset);
401     for (i = 0; i < items; i++) {
402         const char *opname;
403         on = 1;
404         if (verify_opset(aTHX_ ST(i),0)) {
405             opname = "(opset)";
406             bitspec = ST(i);
407         }
408         else {
409             opname = SvPV(ST(i), len);
410             if (*opname == '!') { on=0; ++opname;--len; }
411             bitspec = get_op_bitspec(aTHX_ opname, len, 1);
412         }
413         set_opset_bits(aTHX_ bitmap, bitspec, on, opname);
414     }
415     ST(0) = opset;
416
417
418 #define PERMITING  (ix == 0 || ix == 1)
419 #define ONLY_THESE (ix == 0 || ix == 2)
420
421 void
422 permit_only(safe, ...)
423     SV *safe
424 ALIAS:
425         permit    = 1
426         deny_only = 2
427         deny      = 3
428 CODE:
429     int i;
430     SV *bitspec, *mask;
431     char *bitmap;
432     STRLEN len;
433     dMY_CXT;
434
435     if (!SvROK(safe) || !SvOBJECT(SvRV(safe)) || SvTYPE(SvRV(safe))!=SVt_PVHV)
436         croak("Not a Safe object");
437     mask = *hv_fetchs((HV*)SvRV(safe), "Mask", 1);
438     if (ONLY_THESE)     /* *_only = new mask, else edit current */
439         sv_setsv(mask, sv_2mortal(new_opset(aTHX_ PERMITING ? opset_all : Nullsv)));
440     else
441         verify_opset(aTHX_ mask,1); /* croaks */
442     bitmap = SvPVX(mask);
443     for (i = 1; i < items; i++) {
444         const char *opname;
445         int on = PERMITING ? 0 : 1;             /* deny = mask bit on   */
446         if (verify_opset(aTHX_ ST(i),0)) {      /* it's a valid mask    */
447             opname = "(opset)";
448             bitspec = ST(i);
449         }
450         else {                          /* it's an opname/optag */
451             opname = SvPV(ST(i), len);
452             /* invert if op has ! prefix (only one allowed)     */
453             if (*opname == '!') { on = !on; ++opname; --len; }
454             bitspec = get_op_bitspec(aTHX_ opname, len, 1); /* croaks */
455         }
456         set_opset_bits(aTHX_ bitmap, bitspec, on, opname);
457     }
458     ST(0) = &PL_sv_yes;
459
460
461
462 void
463 opdesc(...)
464 PPCODE:
465     int i;
466     STRLEN len;
467     SV **args;
468     char **op_desc = get_op_descs(); 
469     dMY_CXT;
470
471     /* copy args to a scratch area since we may push output values onto */
472     /* the stack faster than we read values off it if masks are used.   */
473     args = (SV**)SvPVX(newSVpvn_flags((char*)&ST(0), items*sizeof(SV*), SVs_TEMP));
474     for (i = 0; i < items; i++) {
475         const char * const opname = SvPV(args[i], len);
476         SV *bitspec = get_op_bitspec(aTHX_ opname, len, 1);
477         if (SvIOK(bitspec)) {
478             const int myopcode = SvIV(bitspec);
479             if (myopcode < 0 || myopcode >= PL_maxo)
480                 croak("panic: opcode %d (%s) out of range",myopcode,opname);
481             XPUSHs(newSVpvn_flags(op_desc[myopcode], strlen(op_desc[myopcode]),
482                                   SVs_TEMP));
483         }
484         else if (SvPOK(bitspec) && SvCUR(bitspec) == (STRLEN)opset_len) {
485             int b, j;
486             const char * const bitmap = SvPV_nolen_const(bitspec);
487             int myopcode = 0;
488             for (b=0; b < opset_len; b++) {
489                 const U16 bits = bitmap[b];
490                 for (j=0; j < 8 && myopcode < PL_maxo; j++, myopcode++)
491                     if (bits & (1 << j))
492                         XPUSHs(newSVpvn_flags(op_desc[myopcode],
493                                               strlen(op_desc[myopcode]),
494                                               SVs_TEMP));
495             }
496         }
497         else
498             croak("panic: invalid bitspec for \"%s\" (type %u)",
499                 opname, (unsigned)SvTYPE(bitspec));
500     }
501
502
503 void
504 define_optag(optagsv, mask)
505     SV *optagsv
506     SV *mask
507 CODE:
508     STRLEN len;
509     const char *optag = SvPV(optagsv, len);
510
511     put_op_bitspec(aTHX_ optag, len, mask); /* croaks */
512     ST(0) = &PL_sv_yes;
513
514
515 void
516 empty_opset()
517 CODE:
518     ST(0) = sv_2mortal(new_opset(aTHX_ Nullsv));
519
520 void
521 full_opset()
522 CODE:
523     dMY_CXT;
524     ST(0) = sv_2mortal(new_opset(aTHX_ opset_all));
525
526 void
527 opmask_add(opset)
528     SV *opset
529 PREINIT:
530     if (!PL_op_mask)
531         Newxz(PL_op_mask, PL_maxo, char);
532 CODE:
533     opmask_add(aTHX_ opset);
534
535 void
536 opcodes()
537 PPCODE:
538     if (GIMME_V == G_ARRAY) {
539         croak("opcodes in list context not yet implemented"); /* XXX */
540     }
541     else {
542         XPUSHs(sv_2mortal(newSViv(PL_maxo)));
543     }
544
545 void
546 opmask()
547 CODE:
548     ST(0) = sv_2mortal(new_opset(aTHX_ Nullsv));
549     if (PL_op_mask) {
550         char * const bitmap = SvPVX(ST(0));
551         int myopcode;
552         for(myopcode=0; myopcode < PL_maxo; ++myopcode) {
553             if (PL_op_mask[myopcode])
554                 bitmap[myopcode >> 3] |= 1 << (myopcode & 0x07);
555         }
556     }
557