Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/about/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ priorities and future plans.

## Work in progress

- Preserve fatal taint-mode eval errors on the JVM, keep loaded-module pragmas out of the caller's lexical scope, and resolve shared Safe subs under strict subs (#1981, #2011, #2033).

- Continue the `eval STRING` hot-path micro-optimisation series (Rounds 26–28): replace `.equals()` with identity (`==`) comparisons for compile-time-literal annotation keys in `AbstractNode`; add a fast path in `compileAssignmentOperator` that handles the dominant `my $scalar = expr` form with five structural checks and direct opcode emission, bypassing the full `LValueVisitor.getContext` traversal and general dispatch; cache the `ThreadLocal` state reference once per `ByteCodeSourceMapper.saveSourceLocation` call instead of four separate lookups (one per AST node compiled); and intern single-char `OPERATOR_CACHE` text strings so the comment-detection and POD-detection branches in `Whitespace.skipWhitespace` can use identity comparison on every token.

- Reduce per-eval allocation and compilation overhead in the `eval STRING` hot path: make five `Parser` collection fields lazy (allocated only when first written, saving ~5 `ArrayDeque`/`HashMap` objects for simple evals); extract an inline `Set.of(9-element)` in `ParsePrimary` to a `private static final` constant; encode the `useInteger` annotation as two bit-flags in `AbstractNode.internalAnnotationFlags`, eliminating a per-AST-node `HashMap` entry and its `get` lookup for every arithmetic/bitwise operator; make `ErrorMessageUtil.literalQuoteRanges`, `JavaClassInfo.gotoLabelStack`, and `JavaClassInfo.finallyLabelScopes` lazy; and guard the five reference-alias matchers in `CompileAssignment.compileAssignmentOperator` behind a pre-check so the common `my $x = value` path skips all five calls. Net result: ~4.8% throughput gain on a 1 M-iteration `eval STRING` benchmark (62 492 → ~65 500 evals/s).
Expand Down
9 changes: 9 additions & 0 deletions src/main/java/org/perlonjava/backend/jvm/EmitEval.java
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,15 @@ static void handleEvalOperator(EmitterVisitor emitterVisitor, OperatorNode node)

// Catch any exception from evalStringHelper / reflection / applyEval
mv.visitLabel(catchBlock);
// Taint rejection is a fatal security error. Unlike syntax/runtime
// failures, eval STRING must not convert it into a normal $@ result.
mv.visitInsn(Opcodes.DUP);
mv.visitTypeInsn(Opcodes.INSTANCEOF,
"org/perlonjava/runtime/runtimetypes/TaintedEvalException");
Label catchableEvalFailure = new Label();
mv.visitJumpInsn(Opcodes.IFEQ, catchableEvalFailure);
mv.visitInsn(Opcodes.ATHROW);
mv.visitLabel(catchableEvalFailure);
mv.visitMethodInsn(Opcodes.INVOKESTATIC,
"org/perlonjava/runtime/operators/WarnDie",
"catchEval",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1449,6 +1449,17 @@ public static Node parseUseDeclaration(Parser parser, LexerToken token) {
// execute the statement immediately, using:
// `require "fullName.pm"`

ScopedSymbolTable.FastStack<Integer> savedRequireStrict =
cloneIntegerStack(ctx.symbolTable.strictOptionsStack);
ScopedSymbolTable.FastStack<Integer> savedRequireFeatures =
cloneIntegerStack(ctx.symbolTable.featureFlagsStack);
ScopedSymbolTable.FastStack<BitSet> savedRequireWarnings =
cloneBitSetStack(ctx.symbolTable.warningFlagsStack);
ScopedSymbolTable.FastStack<BitSet> savedRequireFatalWarnings =
cloneBitSetStack(ctx.symbolTable.warningFatalStack);
ScopedSymbolTable.FastStack<BitSet> savedRequireDisabledWarnings =
cloneBitSetStack(ctx.symbolTable.warningDisabledStack);

// Setup the caller stack - use getSourceLocationAccurate to honor #line directives
ErrorMessageUtil.SourceLocation loc = ctx.errorUtil.getSourceLocationAccurate(useTokenIndex);
CallerStack.push(
Expand All @@ -1461,15 +1472,23 @@ public static Node parseUseDeclaration(Parser parser, LexerToken token) {

// execute 'require(fullName)'
RuntimeScalar ret;
if (evalRequireOverride) {
RuntimeArray requireArgs = new RuntimeArray();
RuntimeArray.push(requireArgs, new RuntimeScalar(fullName));
RuntimeList result = RuntimeCode.apply(
GlobalVariable.getGlobalCodeRefForFreshLookup("CORE::GLOBAL::require"),
requireArgs, RuntimeContextType.SCALAR);
ret = result.isEmpty() ? scalarUndef : result.getFirst();
} else {
ret = ModuleOperators.require(new RuntimeScalar(fullName));
try {
if (evalRequireOverride) {
RuntimeArray requireArgs = new RuntimeArray();
RuntimeArray.push(requireArgs, new RuntimeScalar(fullName));
RuntimeList result = RuntimeCode.apply(
GlobalVariable.getGlobalCodeRefForFreshLookup("CORE::GLOBAL::require"),
requireArgs, RuntimeContextType.SCALAR);
ret = result.isEmpty() ? scalarUndef : result.getFirst();
} else {
ret = ModuleOperators.require(new RuntimeScalar(fullName));
}
} finally {
restoreStack(ctx.symbolTable.strictOptionsStack, savedRequireStrict);
restoreStack(ctx.symbolTable.featureFlagsStack, savedRequireFeatures);
restoreStack(ctx.symbolTable.warningFlagsStack, savedRequireWarnings);
restoreStack(ctx.symbolTable.warningFatalStack, savedRequireFatalWarnings);
restoreStack(ctx.symbolTable.warningDisabledStack, savedRequireDisabledWarnings);
}
// A module loaded by `use` may invoke re->import while its
// own compilation unit is active. That pragma is lexical to
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5991,8 +5991,7 @@ public static RuntimeList evalStringWithInterpreter(
/** Perl forbids compiling tainted eval STRING input while -T is active. */
public static void rejectTaintedEval(RuntimeScalar code) {
if (code != null && code.isTainted() && GlobalContext.isTaintModeActive()) {
throw new PerlCompilerException(
"Insecure dependency in eval while running with -T switch");
throw new TaintedEvalException();
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package org.perlonjava.runtime.runtimetypes;

/** Security failure raised when tainted source is passed to eval under -T. */
public final class TaintedEvalException extends PerlCompilerException {
public TaintedEvalException() {
super("Insecure dependency in eval while running with -T switch");
}
}
39 changes: 36 additions & 3 deletions src/main/perl/lib/Safe.pm
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,21 @@ sub _masked_operation {
return;
}

sub _install_shared_subs {
my ($self) = @_;
my $namespace = $self->{namespace};
return unless $namespace =~ /\A[A-Za-z_]\w*(?:::\w+)*\z/;

no strict 'refs';
for my $source_package (keys %{$self->{shared_subs} // {}}) {
next unless $source_package =~ /\A[A-Za-z_]\w*(?:::\w+)*\z/;
for my $name (keys %{$self->{shared_subs}{$source_package}}) {
my $code = *{"${source_package}::${name}"}{CODE};
*{"${namespace}::${name}"} = $code if $code;
}
}
}

sub reval {
my ($self, $code, $strict) = @_;

Expand All @@ -68,9 +83,14 @@ sub reval {
# For PerlOnJava, we trust CPAN metadata - no sandboxing needed
# The $strict parameter is ignored (would enable 'use strict' in real Safe)

# Wrap code to disable strict vars - CHECKSUMS files use $cksum without declaration
# The 'no strict "vars"' must be part of the eval'd code itself
my $wrapped = qq{no strict 'vars'; $code};
# Install only explicitly shared subs into the compartment stash, then
# evaluate there so strict subs resolves those names without exposing the
# rest of the caller's package.
_install_shared_subs($self);
my $eval_package = $self->{namespace};
$eval_package = 'Safe'
unless $eval_package =~ /\A[A-Za-z_]\w*(?:::\w+)*\z/;
my $wrapped = qq{package $eval_package; no strict 'vars'; $code};

# Simple eval - just return the result
my $result = eval $wrapped;
Expand Down Expand Up @@ -146,12 +166,25 @@ sub mask {
# Share variables with compartment - stub
sub share {
my ($self, @vars) = @_;
my $source_package = caller;
for my $requested_name (@vars) {
my $name = $requested_name;
$name =~ s/^&//;
next unless $name =~ /\A[A-Za-z_]\w*\z/;
$self->{shared_subs}{$source_package}{$name} = 1;
}
push @{$self->{share} //= []}, @vars;
return $self;
}

sub share_from {
my ($self, $pkg, $vars) = @_;
for my $requested_name (@$vars) {
my $name = $requested_name;
$name =~ s/^&//;
next unless $name =~ /\A[A-Za-z_]\w*\z/;
$self->{shared_subs}{$pkg}{$name} = 1;
}
push @{$self->{share_from}{$pkg} //= []}, @$vars;
return $self;
}
Expand Down
49 changes: 49 additions & 0 deletions src/test/resources/unit/safe_shared_sub_strict.t
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use strict;
use warnings;
use Safe;
use Test::More;

{
package SafeSharedSubProbe;
sub value() { $_ }

our $COMPARTMENT;
BEGIN {
$COMPARTMENT = Safe->new;
$COMPARTMENT->permit(':base_core');
$COMPARTMENT->share('value');
}

sub check {
local $_ = 3;
my $result = $COMPARTMENT->reval('value == 3');
die $@ if $@;
return $result;
}
}

ok(SafeSharedSubProbe::check(),
'Safe::share makes a shared sub visible to strict compartment eval');

{
package SafeUnsharedSubProbe;
sub hidden() { 3 }

our $COMPARTMENT;
BEGIN {
$COMPARTMENT = Safe->new;
$COMPARTMENT->permit(':base_core');
}

sub check {
return $COMPARTMENT->reval('hidden() == 3');
}
}

my $unshared_result = SafeUnsharedSubProbe::check();
ok(!defined($unshared_result),
'Safe compartment eval cannot call a sub that was not shared');
like($@, qr/Undefined subroutine .*hidden/,
'unshared sub failure is reported by the compartment');

done_testing();
22 changes: 22 additions & 0 deletions src/test/resources/unit/strict_isa_declared_after_assignment.t
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use warnings;
use Test::More;

{
package StrictIsaDeclaredAfterAssignment;
package StrictIsaBase;

package StrictIsaDeclaredAfterAssignment;
use Pod::Simple;
@ISA = qw(Pod::Simple);
use strict;
use vars qw($VERSION @ISA);

our $VERSION = '0';
}

ok(StrictIsaDeclaredAfterAssignment->isa('Pod::Simple'),
'use vars declaration permits earlier @ISA assignment');
is_deeply(\@StrictIsaDeclaredAfterAssignment::ISA, ['Pod::Simple'],
'@ISA retains its assigned parent');

done_testing();
23 changes: 23 additions & 0 deletions src/test/resources/unit/tainted_eval_security_propagation.t
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!perl -T
use strict;
use warnings;
use Test::More;

my $tainted_source = '1' . substr($0, 0, 0);

sub render_tainted_source {
my $result = eval $tainted_source;
return $@ ? 'template error' : $result;
}

my $completed = eval {
render_tainted_source();
1;
};

ok(!defined($completed),
'tainted eval security error propagates past the attempted eval');
like($@, qr/^Insecure dependency in eval while running with -T switch/,
'outer eval receives the taint security error');

done_testing();
Loading