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