aboutsummaryrefslogtreecommitdiffstats
path: root/recipes/perl/perl-5.10.1/safe-upgrade.diff
blob: 51c063eac572a3c0235ba5517573db80c2f236b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
From: Niko Tyni <ntyni@debian.org>
Subject: Upgrade Safe.pm to 2.25, fixing CVE-2010-1974
Bug-Debian: http://bugs.debian.org/582978
Origin: upstream

Upgrade Safe.pm to 2.25, fixing CVE-2010-1974, as recommended in

 http://blogs.perl.org/users/rafael_garcia-suarez/2010/03/new-safepm-fixes-security-hole.html

Although 2.27 is available, its changes are more intrusive.

---
 ext/Safe/Safe.pm           |  290 +++++++++++++++++++++++++++++++++-----------
 ext/Safe/t/safe1.t         |    4 -
 ext/Safe/t/safe2.t         |    4 -
 ext/Safe/t/safe3.t         |    4 -
 ext/Safe/t/safeload.t      |    4 -
 ext/Safe/t/safeops.t       |    8 +-
 ext/Safe/t/safesort.t      |   61 +++++++++
 ext/Safe/t/safeuniversal.t |   13 +--
 ext/Safe/t/safeutf8.t      |   46 +++++++
 ext/Safe/t/safewrap.t      |   39 ++++++
 10 files changed, 370 insertions(+), 103 deletions(-)

diff --git a/ext/Safe/Safe.pm b/ext/Safe/Safe.pm
index ff099ec..e33598e 100644
--- a/ext/Safe/Safe.pm
+++ b/ext/Safe/Safe.pm
@@ -2,8 +2,10 @@ package Safe;
 
 use 5.003_11;
 use strict;
+use Scalar::Util qw(reftype);
+use B qw(sub_generation);
 
-$Safe::VERSION = "2.18";
+$Safe::VERSION = "2.25";
 
 # *** Don't declare any lexicals above this point ***
 #
@@ -11,18 +13,18 @@ $Safe::VERSION = "2.18";
 # 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;
@@ -38,6 +40,23 @@ use Opcode 1.01, qw(
 
 *ops_to_opset = \&opset;   # Temporary alias for old Penguins
 
+# Regular expressions and other unicode-aware code may need to call
+# utf8->SWASHNEW (via perl's utf8.c).  That will fail unless we share the
+# SWASHNEW method.
+# Sadly we can't just add utf8::SWASHNEW to $default_share because perl's
+# utf8.c code does a fetchmethod on SWASHNEW to check if utf8.pm is loaded,
+# and sharing makes it look like the method exists.
+# The simplest and most robust fix is to ensure the utf8 module is loaded when
+# Safe is loaded. Then we can add utf8::SWASHNEW to $default_share.
+require utf8;
+# we must ensure that utf8_heavy.pl, where SWASHNEW is defined, is loaded
+# but without depending on knowledge of that implementation detail.
+# This code (//i on a unicode string) ensures utf8 is fully loaded
+# and also loads the ToFold SWASH.
+# (Swashes are cached internally by perl in PL_utf8_* variables
+# independent of being inside/outside of Safe. So once loaded they can be)
+do { my $unicode = pack('U',0xC4).'1a'; $unicode =~ /\xE4/i; };
+# now we can safely include utf8::SWASHNEW in $default_share defined below.
 
 my $default_root  = 0;
 # share *_ and functions defined in universal.c
@@ -57,10 +76,15 @@ my $default_share = [qw[
     &utf8::downgrade
     &utf8::native_to_unicode
     &utf8::unicode_to_native
+    &utf8::SWASHNEW
     $version::VERSION
     $version::CLASS
+    $version::STRICT
+    $version::LAX
     @version::ISA
-], ($] >= 5.008001 && qw[
+], ($] < 5.010 && qw[
+    &utf8::SWASHGET
+]), ($] >= 5.008001 && qw[
     &Regexp::DESTROY
 ]), ($] >= 5.010 && qw[
     &re::is_regexp
@@ -93,6 +117,11 @@ my $default_share = [qw[
     &version::noop
     &version::is_alpha
     &version::qv
+    &version::vxs::declare
+    &version::vxs::qv
+    &version::vxs::_VERSION
+    &version::vxs::new
+    &version::vxs::parse
 ]), ($] >= 5.011 && qw[
     &re::regexp_pattern
 ])];
@@ -103,14 +132,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
@@ -125,7 +154,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;
 }
 
@@ -140,7 +171,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
@@ -149,7 +180,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};
 
@@ -220,12 +251,12 @@ sub dump_mask {
 }
 
 
-
 sub share {
     my($obj, @vars) = @_;
     $obj->share_from(scalar(caller), \@vars);
 }
 
+
 sub share_from {
     my $obj = shift;
     my $pkg = shift;
@@ -236,26 +267,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;
@@ -264,41 +296,135 @@ 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';
     return *{$obj->root()."::$var"};
 }
 
+sub _clean_stash {
+    my ($root, $saved_refs) = @_;
+    $saved_refs ||= [];
+    no strict 'refs';
+    foreach my $hook (qw(DESTROY AUTOLOAD), grep /^\(/, keys %$root) {
+        push @$saved_refs, \*{$root.$hook};
+        delete ${$root}{$hook};
+    }
+
+    for (grep /::$/, keys %$root) {
+        next if \%{$root.$_} eq \%$root;
+        _clean_stash($root.$_, $saved_refs);
+    }
+}
 
 sub reval {
     my ($obj, $expr, $strict) = @_;
     my $root = $obj->{Root};
 
-    my $evalsub = lexless_anon_sub($root,$strict, $expr);
-    return Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
+    my $evalsub = lexless_anon_sub($root, $strict, $expr);
+    # propagate context
+    my $sg = sub_generation();
+    my @subret = (wantarray)
+               ?        Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub)
+               : scalar Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
+    _clean_stash($root.'::') if $sg != sub_generation();
+    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) = @_;
+
+    # wrap code ref $sub with _safe_call_sv so that, when called, the
+    # execution will happen with the compartment fully 'in effect'.
+
+    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)
+            my $sg = sub_generation();
+            @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 = $@;
+            _clean_stash($obj->{Root}.'::') if $sg != sub_generation();
+        };
+        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 $sg = sub_generation();
     my $evalsub = eval
-	    sprintf('package %s; sub { @_ = (); do $file }', $root);
-    return Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
+            sprintf('package %s; sub { @_ = (); do $file }', $root);
+    my @subret = (wantarray)
+               ?        Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub)
+               : scalar Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
+    _clean_stash($root.'::') if $sg != sub_generation();
+    return (wantarray) ? @subret : $subret[0];
 }
 
 
@@ -390,15 +516,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
 
@@ -417,9 +535,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).
@@ -427,29 +543,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>
@@ -465,9 +582,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
@@ -475,20 +592,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:
+
+    $safe->share_from('Scalar::Util', [ 'reftype' ]);
+    $safe->share_from('main', [ 'Scalar::Util::reftype' ]);
 
-=item varglob (VARNAME)
+=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.
 
@@ -553,14 +679,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.
@@ -569,7 +693,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.
 
@@ -579,14 +703,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
 
@@ -624,7 +768,7 @@ but more subtle effect.
 
 =back
 
-=head2 AUTHOR
+=head1 AUTHOR
 
 Originally designed and implemented by Malcolm Beattie.
 
diff --git a/ext/Safe/t/safe1.t b/ext/Safe/t/safe1.t
index 6a3b908..385d661 100755
--- a/ext/Safe/t/safe1.t
+++ b/ext/Safe/t/safe1.t
@@ -1,10 +1,6 @@
 #!./perl -w
 $|=1;
 BEGIN {
-    if($ENV{PERL_CORE}) {
-	chdir 't' if -d 't';
-	@INC = '../lib';
-    }
     require Config; import Config;
     if ($Config{'extensions'} !~ /\bOpcode\b/ && $Config{'osname'} ne 'VMS') {
         print "1..0\n";
diff --git a/ext/Safe/t/safe2.t b/ext/Safe/t/safe2.t
index d0239d1..2548dcc 100755
--- a/ext/Safe/t/safe2.t
+++ b/ext/Safe/t/safe2.t
@@ -1,10 +1,6 @@
 #!./perl -w
 $|=1;
 BEGIN {
-    if($ENV{PERL_CORE}) {
-	chdir 't' if -d 't';
-	@INC = '../lib';
-    } 
     require Config; import Config;
     if ($Config{'extensions'} !~ /\bOpcode\b/ && $Config{'osname'} ne 'VMS') {
         print "1..0\n";
diff --git a/ext/Safe/t/safe3.t b/ext/Safe/t/safe3.t
index c809f27..1f99f49 100755
--- a/ext/Safe/t/safe3.t
+++ b/ext/Safe/t/safe3.t
@@ -1,10 +1,6 @@
 #!perl -w
 
 BEGIN {
-    if ($ENV{PERL_CORE}) {
-	chdir 't' if -d 't';
-	@INC = '../lib';
-    }
     require Config; import Config;
     if ($Config{'extensions'} !~ /\bOpcode\b/
 	&& $Config{'extensions'} !~ /\bPOSIX\b/
diff --git a/ext/Safe/t/safeload.t b/ext/Safe/t/safeload.t
index b15c290..2d2c3cc 100755
--- a/ext/Safe/t/safeload.t
+++ b/ext/Safe/t/safeload.t
@@ -1,10 +1,6 @@
 #!perl
 
 BEGIN {
-    if ($ENV{PERL_CORE}) {
-	chdir 't' if -d 't';
-	@INC = '../lib';
-    }
     require Config;
     import Config;
     if ($Config{'extensions'} !~ /\bOpcode\b/) {
diff --git a/ext/Safe/t/safeops.t b/ext/Safe/t/safeops.t
index 229672e..e8fa339 100755
--- a/ext/Safe/t/safeops.t
+++ b/ext/Safe/t/safeops.t
@@ -2,13 +2,9 @@
 # Tests that all ops can be trapped by a Safe compartment
 
 BEGIN {
-    if ($ENV{PERL_CORE}) {
-	chdir 't' if -d 't';
-	@INC = '../lib';
-    }
-    else {
+    unless ($ENV{PERL_CORE}) {
 	# this won't work outside of the core, so exit
-        print "1..0\n"; exit 0;
+        print "1..0 # skipped: PERL_CORE unset\n"; exit 0;
     }
 }
 use Config;
diff --git a/ext/Safe/t/safesort.t b/ext/Safe/t/safesort.t
new file mode 100644
index 0000000..797e155
--- /dev/null
+++ b/ext/Safe/t/safesort.t
@@ -0,0 +1,61 @@
+#!perl -w
+$|=1;
+BEGIN {
+    require Config; import Config;
+    if ($Config{'extensions'} !~ /\bOpcode\b/ && $Config{'osname'} ne 'VMS') {
+        print "1..0\n";
+        exit 0;
+    }
+}
+
+use Safe 1.00;
+use Test::More tests => 10;
+
+my $safe = Safe->new('PLPerl');
+$safe->permit_only(qw(:default sort));
+
+# check basic argument passing and context for anon-subs
+my $func = $safe->reval(q{ sub { @_ } });
+is_deeply [ $func->() ], [ ];
+is_deeply [ $func->("foo") ], [ "foo" ];
+
+my $func1 = $safe->reval(<<'EOS');
+
+    # uses quotes in { "$a" <=> $b } to avoid the optimizer replacing the block
+    # with a hardwired comparison
+    { package Pkg; sub p_sort { return sort { "$a" <=> $b } @_; } }
+                   sub l_sort { return sort { "$a" <=> $b } @_; }
+
+    return sub { return join(",",l_sort(@_)), join(",",Pkg::p_sort(@_)) }
+
+EOS
+
+is $@, '', 'reval should not fail';
+is ref $func, 'CODE', 'reval should return a CODE ref';
+
+# $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";
+
+# check other aspects of closures created inside Safe
+
+my $die_func = $safe->reval(q{ sub { die @_ if @_; 1 } });
+
+# check $@ not affected by successful call
+$@ = 42;
+$die_func->();
+is $@, 42, 'successful closure call should not alter $@';
+
+{
+    my $warns = 0;
+    local $SIG{__WARN__} = sub { $warns++ };
+    ok !eval { $die_func->("died\n"); 1 }, 'should die';
+    is $@, "died\n", '$@ should be set correctly';
+    is $warns, 0;
+}
diff --git a/ext/Safe/t/safeuniversal.t b/ext/Safe/t/safeuniversal.t
index 5ef3842..95867c5 100755
--- a/ext/Safe/t/safeuniversal.t
+++ b/ext/Safe/t/safeuniversal.t
@@ -1,10 +1,6 @@
 #!perl
 
 BEGIN {
-    if ($ENV{PERL_CORE}) {
-	chdir 't' if -d 't';
-	@INC = '../lib';
-    }
     require Config;
     import Config;
     if ($Config{'extensions'} !~ /\bOpcode\b/) {
@@ -22,8 +18,10 @@ plan(tests => 6);
 my $c = new Safe;
 $c->permit(qw(require caller));
 
-my $r = $c->reval(q!
-    no warnings 'redefine';
+my $no_warn_redef = ($] != 5.008009)
+    ? q(no warnings 'redefine';)
+    : q($SIG{__WARN__}=sub{};);
+my $r = $c->reval($no_warn_redef . q!
     sub UNIVERSAL::isa { "pwned" }
     (bless[],"Foo")->isa("Foo");
 !);
@@ -33,8 +31,7 @@ is( (bless[],"Foo")->isa("Foo"), 1, "... but not outside" );
 
 sub Foo::foo {}
 
-$r = $c->reval(q!
-    no warnings 'redefine';
+$r = $c->reval($no_warn_redef . q!
     sub UNIVERSAL::can { "pwned" }
     (bless[],"Foo")->can("foo");
 !);
diff --git a/ext/Safe/t/safeutf8.t b/ext/Safe/t/safeutf8.t
new file mode 100644
index 0000000..28441da
--- /dev/null
+++ b/ext/Safe/t/safeutf8.t
@@ -0,0 +1,46 @@
+#!perl -w
+$|=1;
+BEGIN {
+    require Config; import Config;
+    if ($Config{'extensions'} !~ /\bOpcode\b/ && $Config{'osname'} ne 'VMS') {
+        print "1..0\n";
+        exit 0;
+    }
+}
+
+use Test::More tests => 7;
+
+use Safe 1.00;
+use Opcode qw(full_opset);
+
+pass;
+
+my $safe = Safe->new('PLPerl');
+$safe->permit(qw(pack));
+
+# Expression that triggers require utf8 and call to SWASHNEW.
+# Fails with "Undefined subroutine PLPerl::utf8::SWASHNEW called"
+# if SWASHNEW is not shared, else returns true if unicode logic is working.
+my $trigger = q{ my $a = pack('U',0xC4); $a =~ /\\xE4/i };
+
+ok $safe->reval( $trigger ), 'trigger expression should return true';
+is $@, '', 'trigger expression should not die';
+
+# return a closure
+my $sub = $safe->reval(q{sub { warn pack('U',0xC4) }});
+
+# define code outside Safe that'll be triggered from inside
+my @warns;
+$SIG{__WARN__} = sub {
+    my $msg = shift;
+    # this regex requires a different SWASH digit data for \d)
+    # than the one used above and by the trigger code in Safe.pm
+    $msg =~ s/\(eval \d+\)/XXX/i; # uses IsDigit SWASH
+    push @warns, $msg;
+};
+
+is eval { $sub->() }, 1, 'warn should return 1';
+is $@, '', '__WARN__ hook should not die';
+is @warns, 1, 'should only be 1 warning';
+like $warns[0], qr/at XXX line/, 'warning should have been edited';
+
diff --git a/ext/Safe/t/safewrap.t b/ext/Safe/t/safewrap.t
new file mode 100644
index 0000000..27166f8
--- /dev/null
+++ b/ext/Safe/t/safewrap.t
@@ -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/;
-- 
tg: (daf8b46..) fixes/safe-upgrade (depends on: upstream)