diff --git a/docs/about/changelog.md b/docs/about/changelog.md index 784ff1ee00..a9de8a6357 100644 --- a/docs/about/changelog.md +++ b/docs/about/changelog.md @@ -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). diff --git a/src/main/java/org/perlonjava/backend/jvm/EmitEval.java b/src/main/java/org/perlonjava/backend/jvm/EmitEval.java index 1a66cfb7f6..f4fcb10b94 100644 --- a/src/main/java/org/perlonjava/backend/jvm/EmitEval.java +++ b/src/main/java/org/perlonjava/backend/jvm/EmitEval.java @@ -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", diff --git a/src/main/java/org/perlonjava/frontend/parser/StatementParser.java b/src/main/java/org/perlonjava/frontend/parser/StatementParser.java index 80951d629e..8c4a52b8f3 100644 --- a/src/main/java/org/perlonjava/frontend/parser/StatementParser.java +++ b/src/main/java/org/perlonjava/frontend/parser/StatementParser.java @@ -1449,6 +1449,17 @@ public static Node parseUseDeclaration(Parser parser, LexerToken token) { // execute the statement immediately, using: // `require "fullName.pm"` + ScopedSymbolTable.FastStack savedRequireStrict = + cloneIntegerStack(ctx.symbolTable.strictOptionsStack); + ScopedSymbolTable.FastStack savedRequireFeatures = + cloneIntegerStack(ctx.symbolTable.featureFlagsStack); + ScopedSymbolTable.FastStack savedRequireWarnings = + cloneBitSetStack(ctx.symbolTable.warningFlagsStack); + ScopedSymbolTable.FastStack savedRequireFatalWarnings = + cloneBitSetStack(ctx.symbolTable.warningFatalStack); + ScopedSymbolTable.FastStack savedRequireDisabledWarnings = + cloneBitSetStack(ctx.symbolTable.warningDisabledStack); + // Setup the caller stack - use getSourceLocationAccurate to honor #line directives ErrorMessageUtil.SourceLocation loc = ctx.errorUtil.getSourceLocationAccurate(useTokenIndex); CallerStack.push( @@ -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 diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCode.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCode.java index 33540a0b24..a8a828472b 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCode.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCode.java @@ -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(); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/TaintedEvalException.java b/src/main/java/org/perlonjava/runtime/runtimetypes/TaintedEvalException.java new file mode 100644 index 0000000000..2ba3a03c44 --- /dev/null +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/TaintedEvalException.java @@ -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"); + } +} diff --git a/src/main/perl/lib/Safe.pm b/src/main/perl/lib/Safe.pm index 6646f81ee7..88c8988025 100644 --- a/src/main/perl/lib/Safe.pm +++ b/src/main/perl/lib/Safe.pm @@ -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) = @_; @@ -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; @@ -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; } diff --git a/src/test/resources/unit/safe_shared_sub_strict.t b/src/test/resources/unit/safe_shared_sub_strict.t new file mode 100644 index 0000000000..50611e953b --- /dev/null +++ b/src/test/resources/unit/safe_shared_sub_strict.t @@ -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(); diff --git a/src/test/resources/unit/strict_isa_declared_after_assignment.t b/src/test/resources/unit/strict_isa_declared_after_assignment.t new file mode 100644 index 0000000000..540ed34bd5 --- /dev/null +++ b/src/test/resources/unit/strict_isa_declared_after_assignment.t @@ -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(); diff --git a/src/test/resources/unit/tainted_eval_security_propagation.t b/src/test/resources/unit/tainted_eval_security_propagation.t new file mode 100644 index 0000000000..067b53471f --- /dev/null +++ b/src/test/resources/unit/tainted_eval_security_propagation.t @@ -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();