5db658d60131ecb44ec91d2dfd3257ef54ae45bc
[p5sagit/p5-mst-13.2.git] / ext / Opcode / Opcode.pm
1 package Opcode;
2
3 require 5.002;
4
5 use vars qw($VERSION @ISA @EXPORT_OK);
6
7 $VERSION = "1.01";
8
9 use strict;
10 use Carp;
11 use Exporter ();
12 use DynaLoader ();
13 @ISA = qw(Exporter DynaLoader);
14
15 BEGIN {
16     @EXPORT_OK = qw(
17         opset ops_to_opset
18         opset_to_ops opset_to_hex invert_opset
19         empty_opset full_opset
20         opdesc opcodes opmask define_optag
21         opmask_add verify_opset opdump
22     );
23 }
24
25 sub opset (;@);
26 sub opset_to_hex ($);
27 sub opdump (;$);
28 use subs @EXPORT_OK;
29
30 bootstrap Opcode $VERSION;
31
32 _init_optags();
33
34 sub ops_to_opset { opset @_ }   # alias for old name
35
36 sub opset_to_hex ($) {
37     return "(invalid opset)" unless verify_opset($_[0]);
38     unpack("h*",$_[0]);
39 }
40
41 sub opdump (;$) {
42         my $pat = shift;
43     # handy utility: perl -MOpcode=opdump -e 'opdump File'
44     foreach(opset_to_ops(full_opset)) {
45         my $op = sprintf "  %12s  %s\n", $_, opdesc($_);
46                 next if defined $pat and $op !~ m/$pat/i;
47                 print $op;
48     }
49 }
50
51
52
53 sub _init_optags {
54     my(%all, %seen);
55     @all{opset_to_ops(full_opset)} = (); # keys only
56
57     local($_);
58     local($/) = "\n=cut"; # skip to optags definition section
59     <DATA>;
60     $/ = "\n=";         # now read in 'pod section' chunks
61     while(<DATA>) {
62         next unless m/^item\s+(:\w+)/;
63         my $tag = $1;
64
65         # Split into lines, keep only indented lines
66         my @lines = grep { m/^\s/    } split(/\n/);
67         foreach (@lines) { s/--.*//  } # delete comments
68         my @ops   = map  { split ' ' } @lines; # get op words
69
70         foreach(@ops) {
71             warn "$tag - $_ already tagged in $seen{$_}\n" if $seen{$_};
72             $seen{$_} = $tag;
73             delete $all{$_};
74         }
75         # opset will croak on invalid names
76         define_optag($tag, opset(@ops));
77     }
78     close(DATA);
79     warn "Untagged opnames: ".join(' ',keys %all)."\n" if %all;
80 }
81
82
83 1;
84
85 __DATA__
86
87 =head1 NAME
88
89 Opcode - Disable named opcodes when compiling perl code
90
91 =head1 SYNOPSIS
92
93   use Opcode;
94
95
96 =head1 DESCRIPTION
97
98 Perl code is always compiled into an internal format before execution.
99
100 Evaluating perl code (e.g. via "eval" or "do 'file'") causes
101 the code to be compiled into an internal format and then,
102 provided there was no error in the compilation, executed.
103 The internal format is based on many distinct I<opcodes>.
104
105 By default no opmask is in effect and any code can be compiled.
106
107 The Opcode module allow you to define an I<operator mask> to be in
108 effect when perl I<next> compiles any code.  Attempting to compile code
109 which contains a masked opcode will cause the compilation to fail
110 with an error. The code will not be executed.
111
112 =head1 NOTE
113
114 The Opcode module is not usually used directly. See the ops pragma and
115 Safe modules for more typical uses.
116
117 =head1 WARNING
118
119 The authors make B<no warranty>, implied or otherwise, about the
120 suitability of this software for safety or security purposes.
121
122 The authors shall not in any case be liable for special, incidental,
123 consequential, indirect or other similar damages arising from the use
124 of this software.
125
126 Your mileage will vary. If in any doubt B<do not use it>.
127
128
129 =head1 Operator Names and Operator Lists
130
131 The canonical list of operator names is the contents of the array
132 op_name defined and initialised in file F<opcode.h> of the Perl
133 source distribution (and installed into the perl library).
134
135 Each operator has both a terse name (its opname) and a more verbose or
136 recognisable descriptive name. The opdesc function can be used to
137 return a list of descriptions for a list of operators.
138
139 Many of the functions and methods listed below take a list of
140 operators as parameters. Most operator lists can be made up of several
141 types of element. Each element can be one of
142
143 =over 8
144
145 =item an operator name (opname)
146
147 Operator names are typically small lowercase words like enterloop,
148 leaveloop, last, next, redo etc. Sometimes they are rather cryptic
149 like gv2cv, i_ncmp and ftsvtx.
150
151 =item an operator tag name (optag)
152
153 Operator tags can be used to refer to groups (or sets) of operators.
154 Tag names always being with a colon. The Opcode module defines several
155 optags and the user can define others using the define_optag function.
156
157 =item a negated opname or optag
158
159 An opname or optag can be prefixed with an exclamation mark, e.g., !mkdir.
160 Negating an opname or optag means remove the corresponding ops from the
161 accumulated set of ops at that point.
162
163 =item an operator set (opset)
164
165 An I<opset> as a binary string of approximately 43 bytes which holds a
166 set or zero or more operators.
167
168 The opset and opset_to_ops functions can be used to convert from
169 a list of operators to an opset and I<vice versa>.
170
171 Wherever a list of operators can be given you can use one or more opsets.
172 See also Manipulating Opsets below.
173
174 =back
175
176
177 =head1 Opcode Functions
178
179 The Opcode package contains functions for manipulating operator names
180 tags and sets. All are available for export by the package.
181
182 =over 8
183
184 =item opcodes
185
186 In a scalar context opcodes returns the number of opcodes in this
187 version of perl (around 340 for perl5.002).
188
189 In a list context it returns a list of all the operator names.
190 (Not yet implemented, use @names = opset_to_ops(full_opset).)
191
192 =item opset (OP, ...)
193
194 Returns an opset containing the listed operators.
195
196 =item opset_to_ops (OPSET)
197
198 Returns a list of operator names corresponding to those operators in
199 the set.
200
201 =item opset_to_hex (OPSET)
202
203 Returns a string representation of an opset. Can be handy for debugging.
204
205 =item full_opset
206
207 Returns an opset which includes all operators.
208
209 =item empty_opset
210
211 Returns an opset which contains no operators.
212
213 =item invert_opset (OPSET)
214
215 Returns an opset which is the inverse set of the one supplied.
216
217 =item verify_opset (OPSET, ...)
218
219 Returns true if the supplied opset looks like a valid opset (is the
220 right length etc) otherwise it returns false. If an optional second
221 parameter is true then verify_opset will croak on an invalid opset
222 instead of returning false.
223
224 Most of the other Opcode functions call verify_opset automatically
225 and will croak if given an invalid opset.
226
227 =item define_optag (OPTAG, OPSET)
228
229 Define OPTAG as a symbolic name for OPSET. Optag names always start
230 with a colon C<:>.
231
232 The optag name used must not be defined already (define_optag will
233 croak if it is already defined). Optag names are global to the perl
234 process and optag definitions cannot be altered or deleted once
235 defined.
236
237 It is strongly recommended that applications using Opcode should use a
238 leading capital letter on their tag names since lowercase names are
239 reserved for use by the Opcode module. If using Opcode within a module
240 you should prefix your tags names with the name of your module to
241 ensure uniqueness and thus avoid clashes with other modules.
242
243 =item opmask_add (OPSET)
244
245 Adds the supplied opset to the current opmask. Note that there is
246 currently I<no> mechanism for unmasking ops once they have been masked.
247 This is intentional.
248
249 =item opmask
250
251 Returns an opset corresponding to the current opmask.
252
253 =item opdesc (OP, ...)
254
255 This takes a list of operator names and returns the corresponding list
256 of operator descriptions.
257
258 =item opdump (PAT)
259
260 Dumps to STDOUT a two column list of op names and op descriptions.
261 If an optional pattern is given then only lines which match the
262 (case insensitive) pattern will be output.
263
264 It's designed to be used as a handy command line utility:
265
266         perl -MOpcode=opdump -e opdump
267         perl -MOpcode=opdump -e 'opdump Eval'
268
269 =back
270
271 =head1 Manipulating Opsets
272
273 Opsets may be manipulated using the perl bit vector operators & (and), | (or),
274 ^ (xor) and ~ (negate/invert).
275
276 However you should never rely on the numerical position of any opcode
277 within the opset. In other words both sides of a bit vector operator
278 should be opsets returned from Opcode functions.
279
280 Also, since the number of opcodes in your current version of perl might
281 not be an exact multiple of eight, there may be unused bits in the last
282 byte of an upset. This should not cause any problems (Opcode functions
283 ignore those extra bits) but it does mean that using the ~ operator
284 will typically not produce the same 'physical' opset 'string' as the
285 invert_opset function.
286
287
288 =head1 TO DO (maybe)
289
290     $bool = opset_eq($opset1, $opset2)  true if opsets are logically eqiv
291
292     $yes = opset_can($opset, @ops)      true if $opset has all @ops set
293
294     @diff = opset_diff($opset1, $opset2) => ('foo', '!bar', ...)
295
296 =cut
297
298 # the =cut above is used by _init_optags() to get here quickly
299
300 =head1 Predefined Opcode Tags
301
302 =over 5
303
304 =item :base_core
305
306     null stub scalar pushmark wantarray const defined undef
307
308     rv2sv sassign
309
310     rv2av aassign aelem aelemfast aslice av2arylen
311
312     rv2hv helem hslice each values keys exists delete
313
314     preinc i_preinc predec i_predec postinc i_postinc postdec i_postdec
315     int hex oct abs pow multiply i_multiply divide i_divide
316     modulo i_modulo add i_add subtract i_subtract
317
318     left_shift right_shift bit_and bit_xor bit_or negate i_negate
319     not complement
320
321     lt i_lt gt i_gt le i_le ge i_ge eq i_eq ne i_ne ncmp i_ncmp
322     slt sgt sle sge seq sne scmp
323
324     substr vec stringify study pos length index rindex ord chr
325
326     ucfirst lcfirst uc lc quotemeta trans chop schop chomp schomp
327
328     match split
329
330     list lslice splice push pop shift unshift reverse
331
332     cond_expr flip flop andassign orassign and or xor
333
334     warn die lineseq nextstate unstack scope enter leave
335
336     rv2cv anoncode prototype
337
338     entersub leavesub return method -- XXX loops via recursion?
339
340     leaveeval -- needed for Safe to operate, is safe without entereval
341
342 =item :base_mem
343
344 These memory related ops are not included in :base_core because they
345 can easily be used to implement a resource attack (e.g., consume all
346 available memory).
347
348     concat repeat join range
349
350     anonlist anonhash
351
352 Note that despite the existance of this optag a memory resource attack
353 may still be possible using only :base_core ops.
354
355 Disabling these ops is a I<very> heavy handed way to attempt to prevent
356 a memory resource attack. It's probable that a specific memory limit
357 mechanism will be added to perl in the near future.
358
359 =item :base_loop
360
361 These loop ops are not included in :base_core because they can easily be
362 used to implement a resource attack (e.g., consume all available CPU time).
363
364     grepstart grepwhile
365     mapstart mapwhile
366     enteriter iter
367     enterloop leaveloop
368     last next redo
369     goto
370
371 =item :base_io
372
373 These ops enable I<filehandle> (rather than filename) based input and
374 output. These are safe on the assumption that only pre-existing
375 filehandles are available for use.  To create new filehandles other ops
376 such as open would need to be enabled.
377
378     readline rcatline getc read
379
380     formline enterwrite leavewrite
381
382     print sysread syswrite send recv eof tell seek
383
384     readdir telldir seekdir rewinddir
385
386 =item :base_orig
387
388 These are a hotchpotch of opcodes still waiting to be considered
389
390     gvsv gv gelem
391
392     padsv padav padhv padany
393
394     rv2gv refgen srefgen ref
395
396     bless -- could be used to change ownership of objects (reblessing)
397
398     pushre regcmaybe regcomp subst substcont
399
400     sprintf prtf -- can core dump
401
402     crypt
403
404     tie untie
405
406     dbmopen dbmclose
407     sselect select
408     pipe_op sockpair
409
410     getppid getpgrp setpgrp getpriority setpriority localtime gmtime
411
412     entertry leavetry -- can be used to 'hide' fatal errors
413
414 =item :base_math
415
416 These ops are not included in :base_core because of the risk of them being
417 used to generate floating point exceptions (which would have to be caught
418 using a $SIG{FPE} handler).
419
420     atan2 sin cos exp log sqrt
421
422 These ops are not included in :base_core because they have an effect
423 beyond the scope of the compartment.
424
425     rand srand
426
427 =item :default
428
429 A handy tag name for a I<reasonable> default set of ops.  (The current ops
430 allowed are unstable while development continues. It will change.)
431
432     :base_core :base_mem :base_loop :base_io :base_orig
433
434 If safety matters to you (and why else would you be using the Opcode module?)
435 then you should not rely on the definition of this, or indeed any other, optag!
436
437
438 =item :filesys_read
439
440     stat lstat readlink
441
442     ftatime ftblk ftchr ftctime ftdir fteexec fteowned fteread
443     ftewrite ftfile ftis ftlink ftmtime ftpipe ftrexec ftrowned
444     ftrread ftsgid ftsize ftsock ftsuid fttty ftzero ftrwrite ftsvtx
445
446     fttext ftbinary
447
448     fileno
449
450 =item :sys_db
451
452     ghbyname ghbyaddr ghostent shostent ehostent      -- hosts
453     gnbyname gnbyaddr gnetent snetent enetent         -- networks
454     gpbyname gpbynumber gprotoent sprotoent eprotoent -- protocols
455     gsbyname gsbyport gservent sservent eservent      -- services
456
457     gpwnam gpwuid gpwent spwent epwent getlogin       -- users
458     ggrnam ggrgid ggrent sgrent egrent                -- groups
459
460 =item :browse
461
462 A handy tag name for a I<reasonable> default set of ops beyond the
463 :default optag.  Like :default (and indeed all the other optags) its
464 current definition is unstable while development continues. It will change.
465
466 The :browse tag represents the next step beyond :default. It it a
467 superset of the :default ops and adds :filesys_read the :sys_db.
468 The intent being that scripts can access more (possibly sensitive)
469 information about your system but not be able to change it.
470
471     :default :filesys_read :sys_db
472
473 =item :filesys_open
474
475     sysopen open close
476     umask binmode
477
478     open_dir closedir -- other dir ops are in :base_io
479
480 =item :filesys_write
481
482     link unlink rename symlink truncate
483
484     mkdir rmdir
485
486     utime chmod chown
487
488     fcntl -- not strictly filesys related, but possibly as dangerous?
489
490 =item :subprocess
491
492     backtick system
493
494     fork
495
496     wait waitpid
497
498     glob -- access to Cshell via <`rm *`>
499
500 =item :ownprocess
501
502     exec exit kill
503
504     time tms -- could be used for timing attacks (paranoid?)
505
506 =item :others
507
508 This tag holds groups of assorted specialist opcodes that don't warrant
509 having optags defined for them.
510
511 SystemV Interprocess Communications:
512
513     msgctl msgget msgrcv msgsnd
514
515     semctl semget semop
516
517     shmctl shmget shmread shmwrite
518
519 =item :still_to_be_decided
520
521     chdir
522     flock ioctl
523
524     socket getpeername ssockopt
525     bind connect listen accept shutdown gsockopt getsockname
526
527     sleep alarm -- changes global timer state and signal handling
528     sort -- assorted problems including core dumps
529     tied -- can be used to access object implementing a tie
530     pack unpack -- can be used to create/use memory pointers
531
532     entereval -- can be used to hide code from initial compile
533     require dofile 
534
535     caller -- get info about calling environment and args
536
537     reset
538
539     dbstate -- perl -d version of nextstate(ment) opcode
540
541 =item :dangerous
542
543 This tag is simply a bucket for opcodes that are unlikely to be used via
544 a tag name but need to be tagged for completness and documentation.
545
546     syscall dump chroot
547
548
549 =back
550
551 =head1 SEE ALSO
552
553 ops(3) -- perl pragma interface to Opcode module.
554
555 Safe(3) -- Opcode and namespace limited execution compartments
556
557 =head1 AUTHORS
558
559 Originally designed and implemented by Malcolm Beattie,
560 mbeattie@sable.ox.ac.uk as part of Safe version 1.
561
562 Split out from Safe module version 1, named opcode tags and other
563 changes added by Tim Bunce E<lt>F<Tim.Bunce@ig.co.uk>E<gt>.
564
565 =cut
566