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