Add methods wrap_code_ref and wrap_code_refs_within
Tim Bunce [Fri, 26 Feb 2010 10:25:02 +0000 (11:25 +0100)]
MANIFEST
dist/Safe/MANIFEST
dist/Safe/Safe.pm
dist/Safe/t/safesort.t
dist/Safe/t/safewrap.t [new file with mode: 0644]

index 1c34d01..5b9d1ea 100644 (file)
--- a/MANIFEST
+++ b/MANIFEST
@@ -2756,6 +2756,7 @@ dist/Safe/t/safeops.t             Tests that all ops can be trapped by Safe
 dist/Safe/t/safesort.t         Tests Safe with sort
 dist/Safe/t/safeuniversal.t    Tests Safe with functions from universal.c
 dist/Safe/t/safeutf8.t         Tests Safe with utf8.pm
+dist/Safe/t/safewrap.t         Tests Safe::wrap_code_ref()
 dist/SelfLoader/lib/SelfLoader.pm      Load functions only on demand
 dist/SelfLoader/t/01SelfLoader.t       See if SelfLoader works
 dist/SelfLoader/t/02SelfLoader-buggy.t See if SelfLoader works
index c054929..a610ca7 100644 (file)
@@ -11,4 +11,5 @@ t/safeops.t
 t/safesort.t
 t/safeuniversal.t
 t/safeutf8.t
+t/safewrap.t
 META.yml                                 Module meta-data (added by MakeMaker)
index 06d369b..278568a 100644 (file)
@@ -3,8 +3,6 @@ package Safe;
 use 5.003_11;
 use strict;
 use Scalar::Util qw(reftype);
-use Config qw(%Config);
-use constant is_usethreads => $Config{usethreads};
 
 $Safe::VERSION = "2.23";
 
@@ -14,18 +12,18 @@ $Safe::VERSION = "2.23";
 # see any lexicals in scope (apart from __ExPr__ which is unavoidable)
 
 sub lexless_anon_sub {
-                # $_[0] is package;
-                # $_[1] is strict flag;
+                 # $_[0] is package;
+                 # $_[1] is strict flag;
     my $__ExPr__ = $_[2];   # must be a lexical to create the closure that
-                           # can be used to pass the value into the safe
-                           # world
+                            # can be used to pass the value into the safe
+                            # world
 
     # Create anon sub ref in root of compartment.
     # Uses a closure (on $__ExPr__) to pass in the code to be executed.
     # (eval on one line to keep line numbers as expected by caller)
     eval sprintf
     'package %s; %s strict; sub { @_=(); eval q[my $__ExPr__;] . $__ExPr__; }',
-               $_[0], $_[1] ? 'use' : 'no';
+                $_[0], $_[1] ? 'use' : 'no';
 }
 
 use Carp;
@@ -133,14 +131,14 @@ sub new {
     bless $obj, $class;
 
     if (defined($root)) {
-       croak "Can't use \"$root\" as root name"
-           if $root =~ /^main\b/ or $root !~ /^\w[:\w]*$/;
-       $obj->{Root}  = $root;
-       $obj->{Erase} = 0;
+        croak "Can't use \"$root\" as root name"
+            if $root =~ /^main\b/ or $root !~ /^\w[:\w]*$/;
+        $obj->{Root}  = $root;
+        $obj->{Erase} = 0;
     }
     else {
-       $obj->{Root}  = "Safe::Root".$default_root++;
-       $obj->{Erase} = 1;
+        $obj->{Root}  = "Safe::Root".$default_root++;
+        $obj->{Erase} = 1;
     }
 
     # use permit/deny methods instead till interface issues resolved
@@ -155,7 +153,9 @@ sub new {
     # the whole glob *_ rather than $_ and @_ separately, otherwise
     # @_ in non default packages within the compartment don't work.
     $obj->share_from('main', $default_share);
+
     Opcode::_safe_pkg_prep($obj->{Root}) if($Opcode::VERSION > 1.04);
+
     return $obj;
 }
 
@@ -170,7 +170,7 @@ sub erase {
     my ($stem, $leaf);
 
     no strict 'refs';
-    $pkg = "main::$pkg\::";    # expand to full symbol table name
+    $pkg = "main::$pkg\::";     # expand to full symbol table name
     ($stem, $leaf) = $pkg =~ m/(.*::)(\w+::)$/;
 
     # The 'my $foo' is needed! Without it you get an
@@ -179,7 +179,7 @@ sub erase {
 
     #warn "erase($pkg) stem=$stem, leaf=$leaf";
     #warn " stem_symtab hash ".scalar(%$stem_symtab)."\n";
-       # ", join(', ', %$stem_symtab),"\n";
+    # ", join(', ', %$stem_symtab),"\n";
 
 #    delete $stem_symtab->{$leaf};
 
@@ -250,12 +250,12 @@ sub dump_mask {
 }
 
 
-
 sub share {
     my($obj, @vars) = @_;
     $obj->share_from(scalar(caller), \@vars);
 }
 
+
 sub share_from {
     my $obj = shift;
     my $pkg = shift;
@@ -266,26 +266,27 @@ sub share_from {
     no strict 'refs';
     # Check that 'from' package actually exists
     croak("Package \"$pkg\" does not exist")
-       unless keys %{"$pkg\::"};
+        unless keys %{"$pkg\::"};
     my $arg;
     foreach $arg (@$vars) {
-       # catch some $safe->share($var) errors:
-       my ($var, $type);
-       $type = $1 if ($var = $arg) =~ s/^(\W)//;
-       # warn "share_from $pkg $type $var";
-       for (1..2) { # assign twice to avoid any 'used once' warnings
-           *{$root."::$var"} = (!$type)       ? \&{$pkg."::$var"}
-                         : ($type eq '&') ? \&{$pkg."::$var"}
-                         : ($type eq '$') ? \${$pkg."::$var"}
-                         : ($type eq '@') ? \@{$pkg."::$var"}
-                         : ($type eq '%') ? \%{$pkg."::$var"}
-                         : ($type eq '*') ?  *{$pkg."::$var"}
-                         : croak(qq(Can't share "$type$var" of unknown type));
-       }
+        # catch some $safe->share($var) errors:
+        my ($var, $type);
+        $type = $1 if ($var = $arg) =~ s/^(\W)//;
+        # warn "share_from $pkg $type $var";
+        for (1..2) { # assign twice to avoid any 'used once' warnings
+            *{$root."::$var"} = (!$type)   ? \&{$pkg."::$var"}
+                          : ($type eq '&') ? \&{$pkg."::$var"}
+                          : ($type eq '$') ? \${$pkg."::$var"}
+                          : ($type eq '@') ? \@{$pkg."::$var"}
+                          : ($type eq '%') ? \%{$pkg."::$var"}
+                          : ($type eq '*') ?  *{$pkg."::$var"}
+                          : croak(qq(Can't share "$type$var" of unknown type));
+        }
     }
     $obj->share_record($pkg, $vars) unless $no_record or !$vars;
 }
 
+
 sub share_record {
     my $obj = shift;
     my $pkg = shift;
@@ -294,19 +295,24 @@ sub share_record {
     # Record shares using keys of $obj->{Shares}. See reinit.
     @{$shares}{@$vars} = ($pkg) x @$vars if @$vars;
 }
+
+
 sub share_redo {
     my $obj = shift;
     my $shares = \%{$obj->{Shares} ||= {}};
     my($var, $pkg);
     while(($var, $pkg) = each %$shares) {
-       # warn "share_redo $pkg\:: $var";
-       $obj->share_from($pkg,  [ $var ], 1);
+        # warn "share_redo $pkg\:: $var";
+        $obj->share_from($pkg,  [ $var ], 1);
     }
 }
+
+
 sub share_forget {
     delete shift->{Shares};
 }
 
+
 sub varglob {
     my ($obj, $var) = @_;
     no strict 'refs';
@@ -319,51 +325,79 @@ sub reval {
     my $root = $obj->{Root};
 
     my $evalsub = lexless_anon_sub($root, $strict, $expr);
-    my @ret = (wantarray)
-        ?        Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub)
-        : scalar Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
+    # propagate context
+    return Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
+}
 
-    # RT#60374: Safe.pm sort {} bug with -Dusethreads
-    # If the Safe eval returns a code ref in a perl compiled with usethreads
-    # then wrap code ref with _safe_call_sv so that, when called, the
-    # execution will happen with the compartment fully 'in effect'.
-    # Needed to fix sort blocks that reference $a & $b and
-    # possibly other subtle issues.
-    if (is_usethreads()) {
-        for my $ret (@ret) { # edit (via alias) any CODE refs
-            next unless (reftype($ret)||'') eq 'CODE';
-            my $sub = $ret; # avoid closure problems
-            $ret = sub {
-                my @args = @_; # lexical to close over
-                my $sub_with_args = sub { $sub->(@args) };
-
-                my @subret;
-                my $error;
-                do {
-                    local $@;  # needed due to perl_call_sv(sv, G_EVAL|G_KEEPERR)
-                    @subret = (wantarray)
-                        ?        Opcode::_safe_call_sv($root, $obj->{Mask}, $sub_with_args)
-                        : scalar Opcode::_safe_call_sv($root, $obj->{Mask}, $sub_with_args);
-                    $error = $@;
-                };
-                if ($error) { # rethrow exception
-                    $error =~ s/\t\(in cleanup\) //; # prefix added by G_KEEPERR
-                    die $error;
-                }
-                return (wantarray) ? @subret : $subret[0];
-            };
+
+sub wrap_code_refs_within {
+    my $obj = shift;
+
+    $obj->_find_code_refs('wrap_code_ref', @_);
+}
+
+
+sub _find_code_refs {
+    my $obj = shift;
+    my $visitor = shift;
+
+    for my $item (@_) {
+        my $reftype = $item && reftype $item
+            or next;
+        if ($reftype eq 'ARRAY') {
+            $obj->_find_code_refs($visitor, @$item);
+        }
+        elsif ($reftype eq 'HASH') {
+            $obj->_find_code_refs($visitor, values %$item);
+        }
+        # XXX GLOBs?
+        elsif ($reftype eq 'CODE') {
+            $item = $obj->$visitor($item);
         }
     }
+}
+
+
+sub wrap_code_ref {
+    my ($obj, $sub) = @_;
+    my $root = $obj->{Root};
+
+    # wrap code ref $sub with _safe_call_sv so that, when called, the
+    # execution will happen with the compartment fully 'in effect'.
 
-    return (wantarray) ? @ret : $ret[0];
+    croak "Not a CODE reference"
+        if reftype $sub ne 'CODE';
+
+    my $ret = sub {
+        my @args = @_; # lexical to close over
+        my $sub_with_args = sub { $sub->(@args) };
+
+        my @subret;
+        my $error;
+        do {
+            local $@;  # needed due to perl_call_sv(sv, G_EVAL|G_KEEPERR)
+            @subret = (wantarray)
+                ?        Opcode::_safe_call_sv($obj->{Root}, $obj->{Mask}, $sub_with_args)
+                : scalar Opcode::_safe_call_sv($obj->{Root}, $obj->{Mask}, $sub_with_args);
+            $error = $@;
+        };
+        if ($error) { # rethrow exception
+            $error =~ s/\t\(in cleanup\) //; # prefix added by G_KEEPERR
+            die $error;
+        }
+        return (wantarray) ? @subret : $subret[0];
+    };
+
+    return $ret;
 }
 
+
 sub rdo {
     my ($obj, $file) = @_;
     my $root = $obj->{Root};
 
     my $evalsub = eval
-           sprintf('package %s; sub { @_ = (); do $file }', $root);
+            sprintf('package %s; sub { @_ = (); do $file }', $root);
     return Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
 }
 
@@ -456,15 +490,7 @@ of this software.
 Your mileage will vary. If in any doubt B<do not use it>.
 
 
-=head2 RECENT CHANGES
-
-The interface to the Safe module has changed quite dramatically since
-version 1 (as supplied with Perl5.002). Study these pages carefully if
-you have code written to use Safe version 1 because you will need to
-makes changes.
-
-
-=head2 Methods in class Safe
+=head1 METHODS
 
 To create a new compartment, use
 
@@ -483,9 +509,7 @@ object returned by the above constructor. The object argument
 is implicit in each case.
 
 
-=over 8
-
-=item permit (OP, ...)
+=head2 permit (OP, ...)
 
 Permit the listed operators to be used when compiling code in the
 compartment (in I<addition> to any operators already permitted).
@@ -493,29 +517,30 @@ compartment (in I<addition> to any operators already permitted).
 You can list opcodes by names, or use a tag name; see
 L<Opcode/"Predefined Opcode Tags">.
 
-=item permit_only (OP, ...)
+=head2 permit_only (OP, ...)
 
 Permit I<only> the listed operators to be used when compiling code in
 the compartment (I<no> other operators are permitted).
 
-=item deny (OP, ...)
+=head2 deny (OP, ...)
 
 Deny the listed operators from being used when compiling code in the
 compartment (other operators may still be permitted).
 
-=item deny_only (OP, ...)
+=head2 deny_only (OP, ...)
 
 Deny I<only> the listed operators from being used when compiling code
-in the compartment (I<all> other operators will be permitted).
+in the compartment (I<all> other operators will be permitted, so you probably
+don't want to use this method).
 
-=item trap (OP, ...)
+=head2 trap (OP, ...)
 
-=item untrap (OP, ...)
+=head2 untrap (OP, ...)
 
 The trap and untrap methods are synonyms for deny and permit
 respectfully.
 
-=item share (NAME, ...)
+=head2 share (NAME, ...)
 
 This shares the variable(s) in the argument list with the compartment.
 This is almost identical to exporting variables using the L<Exporter>
@@ -531,9 +556,9 @@ for a glob (i.e.  all symbol table entries associated with "foo",
 including scalar, array, hash, sub and filehandle).
 
 Each NAME is assumed to be in the calling package. See share_from
-for an alternative method (which share uses).
+for an alternative method (which C<share> uses).
 
-=item share_from (PACKAGE, ARRAYREF)
+=head2 share_from (PACKAGE, ARRAYREF)
 
 This method is similar to share() but allows you to explicitly name the
 package that symbols should be shared from. The symbol names (including
@@ -541,20 +566,29 @@ type characters) are supplied as an array reference.
 
     $safe->share_from('main', [ '$foo', '%bar', 'func' ]);
 
+Names can include package names, which are relative to the specified PACKAGE.
+So these two calls have the same effect:
 
-=item varglob (VARNAME)
+    $safe->share_from('Scalar::Util', [ 'reftype' ]);
+    $safe->share_from('main', [ 'Scalar::Util::reftype' ]);
+
+=head2 varglob (VARNAME)
 
 This returns a glob reference for the symbol table entry of VARNAME in
 the package of the compartment. VARNAME must be the B<name> of a
-variable without any leading type marker. For example,
+variable without any leading type marker. For example:
+
+    ${$cpt->varglob('foo')} = "Hello world";
+
+has the same effect as:
 
     $cpt = new Safe 'Root';
     $Root::foo = "Hello world";
-    # Equivalent version which doesn't need to know $cpt's package name:
-    ${$cpt->varglob('foo')} = "Hello world";
 
+but avoids the need to know $cpt's package name.
 
-=item reval (STRING, STRICT)
+
+=head2 reval (STRING, STRICT)
 
 This evaluates STRING as perl code inside the compartment.
 
@@ -619,14 +653,12 @@ the code in the compartment.
 A similar effect applies to I<all> runtime symbol lookups in code
 called from a compartment but not compiled within it.
 
-
-
-=item rdo (FILENAME)
+=head2 rdo (FILENAME)
 
 This evaluates the contents of file FILENAME inside the compartment.
 See above documentation on the B<reval> method for further details.
 
-=item root (NAMESPACE)
+=head2 root (NAMESPACE)
 
 This method returns the name of the package that is the root of the
 compartment's namespace.
@@ -635,7 +667,7 @@ Note that this behaviour differs from version 1.00 of the Safe module
 where the root module could be used to change the namespace. That
 functionality has been withdrawn pending deeper consideration.
 
-=item mask (MASK)
+=head2 mask (MASK)
 
 This is a get-or-set method for the compartment's operator mask.
 
@@ -645,14 +677,34 @@ the compartment.
 With the MASK argument present, it sets the operator mask for the
 compartment (equivalent to calling the deny_only method).
 
-=back
+=head2 wrap_code_ref (CODEREF)
+
+Returns a reference to an anonymous subroutine that, when executed, will call
+CODEREF with the Safe compartment 'in effect'.  In other words, with the
+package namespace adjusted and the opmask enabled.
 
+Note that the opmask doesn't affect the already compiled code, it only affects
+any I<further> compilation that the already compiled code may try to perform.
 
-=head2 Some Safety Issues
+This is particularly useful when applied to code references returned from reval().
 
-This section is currently just an outline of some of the things code in
-a compartment might do (intentionally or unintentionally) which can
-have an effect outside the compartment.
+(It also provides a kind of workaround for RT#60374: "Safe.pm sort {} bug with
+-Dusethreads". See L<http://rt.perl.org/rt3//Public/Bug/Display.html?id=60374>
+for I<much> more detail.)
+
+=head2 wrap_code_refs_within (...)
+
+Wraps any CODE references found within the arguments by replacing each with the
+result of calling L</wrap_code_ref> on the CODE reference. Any ARRAY or HASH
+references in the arguments are inspected recursively.
+
+Returns nothing.
+
+=head1 RISKS
+
+This section is just an outline of some of the things code in a compartment
+might do (intentionally or unintentionally) which can have an effect outside
+the compartment.
 
 =over 8
 
@@ -690,7 +742,7 @@ but more subtle effect.
 
 =back
 
-=head2 AUTHOR
+=head1 AUTHOR
 
 Originally designed and implemented by Malcolm Beattie.
 
index 01bed36..991884d 100644 (file)
@@ -19,7 +19,7 @@ my $func = $safe->reval(q{ sub { @_ } });
 is_deeply [ $func->() ], [ ];
 is_deeply [ $func->("foo") ], [ "foo" ];
 
-$func = $safe->reval(<<'EOS');
+my $func1 = $safe->reval(<<'EOS');
 
     # uses quotes in { "$a" <=> $b } to avoid the optimizer replacing the block
     # with a hardwired comparison
@@ -33,7 +33,13 @@ EOS
 is $@, '', 'reval should not fail';
 is ref $func, 'CODE', 'reval should return a CODE ref';
 
-my ($l_sorted, $p_sorted) = $func->(1,2,3);
+# $func1 will work in non-threaded perl
+# but RT#60374 "Safe.pm sort {} bug with -Dusethreads"
+# means the sorting won't work unless we wrap the code ref
+# such that it's executed with Safe 'in effect' at runtime
+my $func2 = $safe->wrap_code_ref($func1);
+
+my ($l_sorted, $p_sorted) = $func2->(3,1,2);
 is $l_sorted, "1,2,3";
 is $p_sorted, "1,2,3";
 
diff --git a/dist/Safe/t/safewrap.t b/dist/Safe/t/safewrap.t
new file mode 100644 (file)
index 0000000..27166f8
--- /dev/null
@@ -0,0 +1,39 @@
+#!perl -w
+
+$|=1;
+BEGIN {
+    require Config; import Config;
+    if ($Config{'extensions'} !~ /\bOpcode\b/ && $Config{'osname'} ne 'VMS') {
+        print "1..0\n";
+        exit 0;
+    }
+}
+
+use strict;
+use Safe 1.00;
+use Test::More tests => 9;
+
+my $safe = Safe->new('PLPerl');
+$safe->permit_only(qw(:default sort));
+
+# eval within an eval: the outer eval is compiled into the sub, the inner is
+# compiled (by the outer) at runtime and so is subject to runtime opmask
+my $sub1 = sub { eval " eval '1+1' " };
+is $sub1->(), 2;
+
+my $sub1w = $safe->wrap_code_ref($sub1);
+is ref $sub1w, 'CODE';
+is eval { $sub1w->() }, undef;
+like $@, qr/eval .* trapped by operation mask/;
+
+is $sub1->(), 2, 'original ref should be unaffected';
+
+# setup args for wrap_code_refs_within including nested data
+my @args = (42, [[ 0, { sub => $sub1 }, 2 ]], 24);
+is $args[1][0][1]{sub}, $sub1;
+
+$safe->wrap_code_refs_within(@args);
+my $sub1w2 = $args[1][0][1]{sub};
+isnt $sub1w2, $sub1;
+is eval { $sub1w2->() }, undef;
+like $@, qr/eval .* trapped by operation mask/;