blib/lib/Sub/Protected.pm

filter: Statementstmt 100% 127 / 127 Branchbran 97.3% 37 / 38 Conditioncond 91.4% 32 / 35 MC/DCmcdc 85.0% 17 / 20 Subroutinesub 100% 26 / 26 Podpod 0.0% 0 / 1 totaltotal 96.7% 239 / 247 CC 34 SCAR 17.1
CC
34
Cov
98%
import
13.0
_check_access
8.0
_process_one
5.0
CRAP 5.5
↑ Summary
1 package Sub::Protected;
2  
3 # Minimum Perl version: 5.10 (the // operator; several dependencies need it).
4 # Loading after CHECK (require, string eval) also needs 5.14: see LIMITATIONS.
5 13 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 13 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 13 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 13 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 13 ▶use Attribute::Handlers;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 13 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 13 ▶use Params::Get qw(get_params);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 13 ▶use Params::Validate::Strict 0.33 qw(validate_strict);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 13 ▶use Return::Set qw(set_return);
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 13 our $VERSION = '0.03';
17  
18 # Public bypass flag. Set to a true value to disable all access checks.
19 # Use C<local $Sub::Protected::BYPASS = 1> in test code; see BYPASS section.
20 13 our $BYPASS = 0;
21  
22 # Module-level configuration hash.
23 # Can be modified directly or injected via Object::Configure.
24 13 our %config = (
25 # When true, access checks are skipped if $ENV{HARNESS_ACTIVE} is set.
26 # Set to 0 to test protection behaviour from within a test harness.
27 harness_bypass => 1,
28 );
29  
30 # Self-referential constant: the name of this package.
31 # Used to identify our own frames in the call-stack walk.
32 13 Readonly::Scalar my $SELF => __PACKAGE__;
33  
34 # Validation schema for a single Perl sub name passed to import().
35 13 Readonly::Scalar my $SUB_NAME_SCHEMA => {
36 name => {
37 type => 'string',
38 regex => qr/\A[_a-zA-Z]\w*\z/,
39 }
40 };
41  
42 # Pending (owner_pkg, sub_name) pairs to be wrapped at CHECK time.
43 # Populated by import(); consumed and cleared by the CHECK block.
44 13 my @_pending;
45  
46 # Set to 1 when the CHECK block fires. Import() uses this to decide
47 # whether to schedule wrapping (pre-CHECK) or wrap immediately (post-CHECK).
48 # If this module is itself loaded after CHECK (run-time require, plugin
49 # loader, string eval) our CHECK block never runs, so start from the global
50 # phase. ${^GLOBAL_PHASE} exists from Perl 5.14; on older Perls it is undef
51 # and the flag starts at 0, so the module must be loaded at compile time.
52 13 ▶my $_post_check = (defined(${^GLOBAL_PHASE}) && ${^GLOBAL_PHASE} ne 'START') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined ${^GLOBAL_PHASE} && ${^GLOBAL_PHASE} ne 'START' ? : 1 12 13
Condition66%2/3
defined ${^GLOBAL_PHASE} and ${^GLOBAL_PHASE} ne "START"
!ll&&!rl&&r
0121
MC/DC50%1/2
defined ${^GLOBAL_PHASE} and ${^GLOBAL_PHASE} ne "START"
defined ${^GLOBAL_PHASE} ${^GLOBAL_PHASE} ne "START"
Truth table66%2/3
A and B
A= defined ${^GLOBAL_PHASE}B= ${^GLOBAL_PHASE} ne "START"
ABresult
0X0
100
111
53  
54 # -------------------------------------------------------------------
55 # ATTRIBUTE HANDLER
56 # -------------------------------------------------------------------
57  
58 # Another module may already own UNIVERSAL::Protected (a :Protected attribute
59 # of its own). Redefining it would silently change that module's behaviour,
60 # so say so loudly. This runs before the sub below is compiled.
61 13 ▶BEGIN {
Subroutine BEGIN: called CC=2 SCAR=7.6
62 13 ▶ Carp::carp(__PACKAGE__ . ": UNIVERSAL::Protected is already defined; another module's :Protected attribute will be replaced")
Branch: 1 branch
BranchTrueFalseTotal
if defined &UNIVERSAL::Protected 0 13 13
63 if defined &UNIVERSAL::Protected;
64 }
65  
66 # Install the :Protected attribute in UNIVERSAL so every package can use it
67 # the moment this module is loaded, with no per-package setup needed.
68 # Attribute::Handlers calls this sub at CHECK phase for each decorated symbol.
69 # It is also called at BEGIN phase: before CHECK that call does nothing (the
70 # CHECK-phase call does the work), but after CHECK the CHECK-phase call never
71 # happens, so the BEGIN-phase call wraps the sub instead. The sub is still
72 # being compiled at that point and may have no name yet, so the wrapping is
73 # deferred to the end of the scope (normally the file) being compiled.
74 # on_scope_end() works here because a BEGIN-phase handler runs while the
75 # user's file is being compiled; it does NOT work from a CHECK-phase callback.
76 # The unused parameters ($attr, $data) are required by the protocol.
77 97 ▶sub UNIVERSAL::Protected : ATTR(CODE,BEGIN,CHECK) {
Subroutine Protected: called CC=3 SCAR=11.0
Pod undocumented
78 97 my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
79  
80 97 ▶ if($phase eq 'BEGIN') {
Branch: 1 branch
BranchTrueFalseTotal
if ($phase eq "BEGIN") 48 49 97
81 48 ▶ return unless($_post_check); # CHECK will do it
Branch: 1 branch
BranchTrueFalseTotal
unless $_post_check 46 2 48
82 2 require B::Hooks::EndOfScope;
83 2 require Sub::Identify;
84 2 ▶ B::Hooks::EndOfScope::on_scope_end(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
85 2 my ($pkg, $name) = Sub::Identify::get_code_info($referent);
86 13 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
87 2 UNIVERSAL::Protected($pkg, \*{"${pkg}::$name"}, $referent, $attr, $data, 'CHECK');
88 2 });
89 2 return;
90 }
91  
92 49 my $sub_name = *{$symbol}{NAME};
93 13 ▶ no warnings 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.0
94 49 *{$symbol} = _wrap($package, $sub_name, $referent); # function call, not method call
95 49 return;
96 13 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
97  
98 # -------------------------------------------------------------------
99 # PUBLIC INTERFACE
100 # -------------------------------------------------------------------
101  
102 =head1 NAME
103  
104 Sub::Protected - Enforce protected subroutine access (Java/C++ semantics)
105  
106 =head1 VERSION
107  
108 0.03
109  
110 =head1 SYNOPSIS
111  
112 package Foo;
113 use Sub::Protected; # enables the :Protected attribute
114  
115 sub new { bless {}, shift }
116  
117 # Attribute form (preferred: protection lives next to the definition)
118 sub _helper :Protected {
119 ...
120 }
121  
122 sub public_method {
123 my $self = shift;
124 $self->_helper; # OK -- same package
125 }
126  
127 # ----------------------------------------------------------------
128  
129 package Bar;
130 use Sub::Protected qw(_other _private); # declarative form
131  
132 sub _other { 'other' }
133 sub _private { 'private' }
134  
135 =head1 DESCRIPTION
136  
137 Enforces Java/C++-style "protected" access at runtime: a subroutine
138 decorated with C<:Protected> (or named in C<use Sub::Protected qw(...)>)
139 may only be called from within its defining package or from a subclass of
140 that package. Any other caller causes a C<Carp::croak> with a descriptive
141 message.
142  
143 =head2 Two usage forms
144  
145 =over 4
146  
147 =item Attribute form (preferred)
148  
149 sub _helper :Protected { ... }
150  
151 The C<:Protected> attribute is registered in C<UNIVERSAL> via
152 L<Attribute::Handlers> when C<Sub::Protected> is loaded, so every package
153 has access to it without any further C<use> or inheritance. The sub is
154 wrapped at C<CHECK> time, or, if the module is loaded after C<CHECK> (Perl
155 5.14 or later), at the end of the file being compiled. This form is preferred because the protection
156 declaration sits next to the definition and wrapping happens at compile time
157 (making pre-wrap raw-coderef captures impossible).
158  
159 =item Declarative form
160  
161 use Sub::Protected qw(_helper _other);
162  
163 Each named sub is looked up in the caller's stash and wrapped at C<CHECK>
164 time (or immediately if the module is loaded at runtime via C<require>).
165 All named subs must be defined before C<CHECK> fires -- i.e. they must be
166 compile-time named subs in the same file, not generated at runtime.
167  
168 =back
169  
170 =head2 Bypass for testing
171  
172 Either condition alone (OR logic) disables all access checks:
173  
174 =over 4
175  
176 =item * C<$Sub::Protected::BYPASS> set to a true value. Use C<local> in tests.
177  
178 =item * C<$ENV{HARNESS_ACTIVE}> set (the convention used by L<Test::Harness>/prove).
179  
180 =back
181  
182 C<$Sub::Protected::BYPASS> is the recommended form for new test code;
183 it is explicit and does not depend on the test runner.
184 C<HARNESS_ACTIVE> is a zero-config convenience.
185  
186 The HARNESS_ACTIVE bypass can be disabled by setting:
187  
188 $Sub::Protected::config{harness_bypass} = 0;
189  
190 =head2 Configuration
191  
192 The module exposes C<%Sub::Protected::config> for runtime configuration:
193  
194 =over 4
195  
196 =item C<harness_bypass> (default: 1)
197  
198 When true, access checks are skipped whenever C<$ENV{HARNESS_ACTIVE}> is
199 set. Set to 0 to test protection behaviour from within a test harness.
200  
201 =back
202  
203 The hash is compatible with L<Object::Configure> for dependency-injection
204 scenarios.
205  
206 =head2 Error message format
207  
208 _helper() is a protected method of Foo and cannot be called from Bar
209  
210 The error is raised with L<Carp/croak>, so it reports the file and line of
211 the offending call, not a line inside Sub::Protected.
212  
213 =head2 How access is decided
214  
215 =over 4
216  
217 =item * Only the immediate caller counts
218  
219 The decision is made on the package of the code that called the protected
220 sub. If C<Bar::run> calls C<Foo::public>, which calls C<Foo::_helper>, the
221 call is allowed: the immediate caller is C<Foo>. If C<Foo::public> instead
222 calls a C<Bar> method that calls C<Foo::_helper>, it is blocked, however
223 deep the chain.
224  
225 =item * Subclasses are allowed
226  
227 A caller whose package C<isa> the owner is allowed, so calls through
228 C<SUPER::>, C<< $self->can('_helper') >> and ordinary inherited method
229 calls all work from a subclass.
230  
231 =item * The wrapper is invisible
232  
233 The wrapper hands over with C<goto &sub>, so inside the protected sub
234 C<caller()> reports the real caller, not Sub::Protected. Arguments
235 (including aliasing of C<@_>), calling context (list, scalar or void) and
236 return values, including false ones, pass through unchanged.
237  
238 =back
239  
240 =head1 PUBLIC INTERFACE
241  
242 =head2 import
243  
244 use Sub::Protected; # attribute form -- no arguments
245 use Sub::Protected qw(_a _b _c); # declarative form
246  
247 =head3 Purpose
248  
249 Called automatically by C<use Sub::Protected>.
250  
251 With B<no arguments>: does nothing beyond making the C<:Protected> attribute
252 globally available (which happens when the module is first loaded).
253  
254 With B<one or more sub names>: registers those subs in the calling
255 package for wrapping at C<CHECK> time. If C<CHECK> has already fired
256 (e.g. the module was loaded via runtime C<require>, a plugin loader or a
257 string C<eval>), wrapping is applied immediately.
258 Each named sub must be defined before C<CHECK> fires (for pre-CHECK loads)
259 or before C<import> is called (for post-CHECK loads), so a module loaded at
260 run time should call C<< Sub::Protected->import(...) >> at the end of the
261 file, after its subs are defined.
262  
263 Run-time loading needs Perl 5.14 or later. On older Perls the module must
264 be loaded at compile time (C<use>, or C<require> inside C<BEGIN>).
265  
266 =head3 Arguments
267  
268 =over 4
269  
270 =item C<$class> (positional, required)
271  
272 The name of the importing class. Set automatically by the C<use> mechanism.
273 Must be a non-empty string.
274  
275 =item C<@subs> (positional, optional)
276  
277 Zero or more sub names to protect in the calling package. Each must be a
278 valid Perl identifier: matching C</\A[_a-zA-Z]\w*\z/>.
279  
280 These calls are equivalent:
281  
282 Sub::Protected->import(qw(_a _b));
283 Sub::Protected->import([ qw(_a _b) ]);
284 Sub::Protected->import({ subs => [ qw(_a _b) ] });
285  
286 A plain list is always a list of names, so C<qw(subs _x)> protects both
287 C<subs> and C<_x>. A single arrayref or hashref is normalised by
288 L<Params::Get>.
289  
290 =back
291  
292 =head3 Returns
293  
294 C<$class> (the importing class name). The return value is ignored by the
295 C<use> mechanism; it is provided for optional method chaining at the class
296 level.
297  
298 =head3 Side effects
299  
300 =over 4
301  
302 =item *
303  
304 Each supplied sub name is appended to an internal pending list (if pre-CHECK)
305 or wrapped immediately (if post-CHECK).
306  
307 =item *
308  
309 The pending list is consumed and cleared when the CHECK block fires.
310  
311 =item *
312  
313 C<$@>, C<$!> and C<$_> are left unchanged, as are any pending C<alarm()>
314 timers.
315  
316 =back
317  
318 =head3 Example
319  
320 package Foo;
321 use Sub::Protected qw(_helper _init);
322  
323 sub _helper { ... } # will be protected
324 sub _init { ... } # will be protected
325  
326 =head3 API SPECIFICATION
327  
328 =head4 Input
329  
330 # Params::Get::get_params / Params::Validate::Strict schema
331 {
332 # class is the implicit first argument, set by Perl's 'use' mechanism
333 subs => {
334 type => 'array',
335 required => 0,
336 each => {
337 type => 'string',
338 regex => qr/\A[_a-zA-Z]\w*\z/,
339 },
340 },
341 }
342  
343 =head4 Output
344  
345 # Return::Set schema
346 {
347 type => 'string',
348 desc => 'The importing class name ($class), for optional chaining.',
349 }
350  
351 =head3 MESSAGES
352  
353 The following table lists every error or warning this method can produce.
354  
355 Message Meaning
356 ---------------------------------------- -------------------------------------
357 "Sub::Protected->import: 'NAME' is not a A sub name passed to import() failed
358 valid Perl identifier" the identifier regex. Use a name
359 matching /\A[_a-zA-Z]\w*\z/.
360 NAME is shown as '' when the
361 name was undef or a reference.
362  
363 "Sub::Protected: PKG::NAME is not defined" The named sub was not found in the
364 package stash at wrap time. For
365 pre-CHECK loads, ensure the sub is
366 a compile-time named sub. For
367 post-CHECK/runtime loads, ensure
368 the sub is defined before import().
369  
370 Calling a protected sub from outside its package or subclasses croaks
371 with the message shown in L</Error message format>.
372  
373 =encoding utf8
374  
375 =head3 FORMAL SPECIFICATION
376  
377 ValidName ≙ { n : seq CHAR | n matches /\A[_a-zA-Z]\w*\z/ }
378  
379 ┌─ Import ──────────────────────────────────────────
380 │ ΔRegistry
381 │ class? : Package ; caller? : Package
382 │ names? : seq SubName ; postCheck : 𝔹
383 │ result! : Package
384 ├───────────────────────────────────────────────────
385 │ ∀ n ∈ ran names? • n ∈ ValidName
386 │ postCheck ⇒ (∀ n ∈ ran names? • defined(caller?, n))
387 │ postCheck ⇒ protected′ = protected ∪ { n : ran names? • (caller?, n) }
388 │ ¬postCheck ⇒ pending′ = pending ⁀ ⟨ n : names? • (caller?, n) ⟩
389 │ result! = class?
390 └───────────────────────────────────────────────────
391  
392 -- Failure cases (croak, Registry unchanged):
393 -- ∃ n ∈ ran names? • n ∉ ValidName
394 -- ⇒ "Sub::Protected->import: 'n' is not a valid Perl identifier"
395 -- postCheck ∧ ∃ n ∈ ran names? • ¬defined(caller?, n)
396 -- ⇒ "Sub::Protected: caller?::n is not defined"
397  
398 =cut
399  
400 97 ▶sub import {
Subroutine import: called CC=13 SCAR=25.7
401 97 my ($class, @subs) = @_;
402  
403 # No sub names: the :Protected attribute is always active via UNIVERSAL.
404 97 ▶ return _return_class($class) unless @subs;
Branch: 1 branch
BranchTrueFalseTotal
unless @subs 47 50 97
405  
406 # A plain list is always a list of names. Only a single arrayref or
407 # hashref goes through Params::Get: passing a plain list to it would read
408 # qw(subs _x) as subs => '_x', silently leaving a sub called subs open.
409 50 my @names = @subs;
410 50 ▶ if (@subs == 1 && ref($subs[0]) && ref($subs[0]) ne 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (@subs == 1 and ref $subs[0] and ref $subs[0] ne "CODE") 8 42 50
Condition83%5/6
@subs == 1 and ref $subs[0] and ref $subs[0] ne "CODE"
!ll&&!rl&&r
4208
@subs == 1 and ref $subs[0]
!ll&&!rl&&r
5378
MC/DC66%2/3
@subs == 1 and ref $subs[0] and ref $subs[0] ne "CODE"
@subs == 1 ref $subs[0] ref $subs[0] ne "CODE"
Truth table75%3/4
A and B and C
A= @subs == 1B= ref $subs[0]C= ref $subs[0] ne "CODE"
ABCresult
0XX0
10X0
1100
1111
411 8 my $args = get_params('subs', \@subs);
412 @names = ref($args->{subs}) eq 'ARRAY'
413 5 ? @{$args->{subs}}
414 8 ▶ : ($args->{subs});
Branch: 1 branch
BranchTrueFalseTotal
ref $args->{'subs'} eq 'ARRAY' ? : 5 3 8
415 }
416  
417 # Validate each name against the schema; validate_strict croaks on failure.
418 # Params::Validate::Strict silently accepts undef for type => 'string', so
419 # we coerce undef and references to '' so the regex check fires for them.
420 # local $@ so a successful eval does not clear the caller's $@.
421 50 for my $sub_name (@names) {
422 58 ▶ my $check = (defined $sub_name && !ref $sub_name) ? $sub_name : q{};
Branch: 1 branch
BranchTrueFalseTotal
defined $sub_name && !ref($sub_name) ? : 51 7 58
Condition100%3/3
defined $sub_name and not ref $sub_name
!ll&&!rl&&r
6151
MC/DC100%2/2
defined $sub_name and not ref $sub_name
defined $sub_name not ref $sub_name
Truth table100%3/3
A and not(B)
A= defined $sub_nameB= not ref $sub_name
ABresult
0X0
100
111
423 58 my $valid = do {
424 58 local $@;
425 58 eval { validate_strict(schema => $SUB_NAME_SCHEMA, input => { name => $check }); 1 };
426 };
427 58 ▶ croak "$SELF->import: '$check' is not a valid Perl identifier"
Branch: 1 branch
BranchTrueFalseTotal
unless $valid 21 37 58
428 unless $valid;
429 }
430  
431 # Schedule or immediately apply wrapping depending on compilation phase.
432 29 my $owner_pkg = caller;
433 29 ▶ if ($_post_check) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_post_check) { } 20 9 29
434 # Module was loaded at runtime (past CHECK): wrap immediately.
435 20 _process_one($owner_pkg, $_) for @names;
436 } else {
437 # Pre-CHECK: register for the CHECK block to process.
438 9 push @_pending, [ $owner_pkg, $_ ] for @names;
439 }
440  
441 24 return _return_class($class);
442 }
443  
444 # -------------------------------------------------------------------
445 # CHECK-TIME PROCESSING
446 # -------------------------------------------------------------------
447  
448 # Process all pending declarative wraps registered during import().
449 # After processing, set the post_check flag so runtime imports wrap directly.
450 # The bare block silences "Too late to run CHECK block" when this module is
451 # loaded after CHECK; $_post_check is already 1 in that case.
452 {
453 13 ▶ no warnings 'void'; # "Too late to run CHECK block"
Subroutine BEGIN: called CC=1 SCAR=0.0
454 12 ▶ CHECK {
Subroutine CHECK: called CC=2 SCAR=6.9
455 12 $_post_check = 1;
456  
457 # Wrap every pending (package, sub) pair.
458 12 _process_one(@$_) for @_pending;
459 12 @_pending = ();
460 }
461 }
462  
463 # -------------------------------------------------------------------
464 # PRIVATE SUBROUTINES
465 # -------------------------------------------------------------------
466  
467 # _return_class
468 # Purpose: Validate and return import()'s return value.
469 # Entry: ($class) -- the importing class name.
470 # Exit: Returns $class, checked against the documented string schema.
471 # Notes: Return::Set::set_return clears $@ even when it succeeds, and
472 # import() promises to leave $@ alone, so it is localised here.
473 13 ▶sub _return_class {
Subroutine _return_class: called CC=1 SCAR=0.0
474 71 my ($class) = @_;
475  
476 71 local $@;
477 71 return set_return($class, { type => 'string' });
478 }
479  
480 # _process_one
481 # Purpose: Look up a named sub in a package's stash and wrap it.
482 # Called from the CHECK block and from import() (post-CHECK).
483 # Entry: ($owner_pkg, $sub_name) -- both non-empty strings;
484 # $owner_pkg::$sub_name must be defined in the stash.
485 # Exit: The stash entry is replaced with the wrapper closure.
486 # Croaks if the sub is not defined.
487 # Side effects: Modifies the caller package's stash (redefines the named glob).
488 # Notes: Uses 'no warnings redefine' because the whole point is replacement.
489 45 ▶sub _process_one {
Subroutine _process_one: called CC=5 SCAR=16.1
490 45 my ($owner_pkg, $sub_name) = @_;
491  
492 # Guard: only Sub::Protected code should call this.
493 _assert_private_caller('_process_one')
494 45 ▶ unless $BYPASS || ($config{harness_bypass} && $ENV{HARNESS_ACTIVE});
Branch: 1 branch
BranchTrueFalseTotal
unless $Sub::Protected::BYPASS or $Sub::Protected::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"} 11 34 45
Condition100%6/6
$Sub::Protected::BYPASS or $Sub::Protected::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"}
l!l&&r!l&&!r
62811
$Sub::Protected::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"}
!ll&&!rl&&r
2928
MC/DC100%3/3
$Sub::Protected::BYPASS or $Sub::Protected::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"}
$Sub::Protected::BYPASS $Sub::Protected::config{"harness_bypass"} $ENV{"HARNESS_ACTIVE"}
Truth table100%4/4
A or B and C
A= $Sub::Protected::BYPASSB= $Sub::Protected::config{"harness_bypass"}C= $ENV{"HARNESS_ACTIVE"}
ABCresult
1XX1
0111
00X0
0100
495  
496 13 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
497  
498 # Abort clearly when the sub was never defined.
499 croak "$SELF: ${owner_pkg}::${sub_name} is not defined"
500 41 ▶ unless defined &{"${owner_pkg}::${sub_name}"};
Branch: 1 branch
BranchTrueFalseTotal
unless defined &{"${owner_pkg}::$sub_name";} 7 34 41
501  
502 34 my $code = \&{"${owner_pkg}::${sub_name}"};
503 13 ▶ no warnings 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.0
504 34 *{"${owner_pkg}::${sub_name}"} = _wrap($owner_pkg, $sub_name, $code);
505 34 return;
506 }
507  
508 # _wrap
509 # Purpose: Construct the protection wrapper closure around a coderef.
510 # Entry: ($owner_pkg, $sub_name, $code) -- all defined; $code is a CODE ref.
511 # Exit: Returns a new anonymous CODE ref (the wrapper closure).
512 # At call time: calls _check_access (may croak), then $code.
513 # Notes: 'goto &$code' is a deliberate, necessary exception to the
514 # "avoid goto" guideline. It replaces the wrapper's stack frame
515 # with $code's frame so that caller() inside the protected body
516 # sees the real caller, not 'Sub::Protected'. Replacing with
517 # $code->(@_) would make caller(0) return 'Sub::Protected' inside
518 # the protected sub, breaking any code there that inspects its
519 # caller. Do NOT change this without updating t/caller_integrity.t.
520 96 ▶sub _wrap {
Subroutine _wrap: called CC=4 SCAR=13.9
521 96 my ($owner_pkg, $sub_name, $code) = @_;
522  
523 # Guard: only Sub::Protected code (and its subclasses) should call _wrap.
524 _assert_private_caller('_wrap')
525 96 ▶ unless $BYPASS || ($config{harness_bypass} && $ENV{HARNESS_ACTIVE});
Branch: 1 branch
BranchTrueFalseTotal
unless $Sub::Protected::BYPASS or $Sub::Protected::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"} 12 84 96
Condition100%6/6
$Sub::Protected::BYPASS or $Sub::Protected::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"}
l!l&&r!l&&!r
107412
$Sub::Protected::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"}
!ll&&!rl&&r
21074
MC/DC100%3/3
$Sub::Protected::BYPASS or $Sub::Protected::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"}
$Sub::Protected::BYPASS $Sub::Protected::config{"harness_bypass"} $ENV{"HARNESS_ACTIVE"}
Truth table100%4/4
A or B and C
A= $Sub::Protected::BYPASSB= $Sub::Protected::config{"harness_bypass"}C= $ENV{"HARNESS_ACTIVE"}
ABCresult
1XX1
0111
00X0
0100
526  
527 # Return the wrapper. The goto is load-bearing -- see Notes above.
528 191 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
529 191 Sub::Protected::_check_access($owner_pkg, $sub_name);
530 115 goto &$code; ## no critic (ControlStructures::ProhibitGoto)
531 91 };
532 }
533  
534 # _check_access
535 # Purpose: Enforce the protected-access invariant at call time.
536 # Walk the call stack (skipping Sub::Protected frames) to find
537 # the first external frame, then allow or croak based on the
538 # owner/isa relationship.
539 # Entry: ($owner_pkg, $sub_name) -- both defined strings.
540 # The current stack has the wrapper closure at the top (frame 0),
541 # followed by the real caller.
542 # Exit: Returns normally (undef) if access is permitted.
543 # Croaks with a descriptive message if access is denied.
544 # Notes: Frame index starts at 0 (= the wrapper closure that called us).
545 # The walk increments until a non-Sub::Protected package appears.
546 # This approach is robust against SUPER:: chains, can() delegation,
547 # and XS frames that may insert extra frames.
548 201 ▶sub _check_access {
Subroutine _check_access: called CC=8 SCAR=20.8
549 201 my ($owner_pkg, $sub_name) = @_;
550  
551 # Short-circuit on bypass (OR logic: either condition alone is sufficient).
552 201 ▶ return if $BYPASS;
Branch: 1 branch
BranchTrueFalseTotal
if $Sub::Protected::BYPASS 15 186 201
553 186 ▶ return if $config{harness_bypass} && $ENV{HARNESS_ACTIVE};
Branch: 1 branch
BranchTrueFalseTotal
if $Sub::Protected::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"} 7 179 186
Condition100%3/3
$Sub::Protected::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"}
!ll&&!rl&&r
81717
MC/DC100%2/2
$Sub::Protected::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"}
$Sub::Protected::config{"harness_bypass"} $ENV{"HARNESS_ACTIVE"}
Truth table100%3/3
A and B
A= $Sub::Protected::config{"harness_bypass"}B= $ENV{"HARNESS_ACTIVE"}
ABresult
0X0
100
111
554  
555 # Walk the stack to find the real (first non-SP) caller.
556 179 my $frame = 0;
557 179 while (1) {
558 352 my $pkg = (caller($frame))[0];
559  
560 # No package found: reached the top of the stack.
561 352 ▶ if (!defined $pkg) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $pkg) 1 351 352
562 1 croak "${sub_name}() is a protected method of ${owner_pkg}"
563 . ' and cannot be called outside any package context';
564 }
565  
566 # Skip Sub::Protected's own frames (wrapper closure, _check_access).
567 351 ▶ if ($pkg eq $SELF) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pkg eq $SELF) 173 178 351
568 173 $frame++;
569 173 next;
570 }
571  
572 # Found the real caller: allow if owner or subclass, else croak.
573 178 ▶ return if $pkg eq $owner_pkg || $pkg->isa($owner_pkg);
Branch: 1 branch
BranchTrueFalseTotal
if $pkg eq $owner_pkg or $pkg->isa($owner_pkg) 99 79 178
Condition100%3/3
$pkg eq $owner_pkg or $pkg->isa($owner_pkg)
l!l&&r!l&&!r
841579
MC/DC100%2/2
$pkg eq $owner_pkg or $pkg->isa($owner_pkg)
$pkg eq $owner_pkg $pkg->isa($owner_pkg)
Truth table100%3/3
A or B
A= $pkg eq $owner_pkgB= $pkg->isa($owner_pkg)
ABresult
1X1
011
000
574  
575 79 croak "${sub_name}() is a protected method of ${owner_pkg}"
576 . " and cannot be called from ${pkg}";
577 }
578 }
579  
580 # _assert_private_caller
581 # Purpose: Croak if the guarded private method was called from outside
582 # Sub::Protected (or a subclass). Used to enforce visibility.
583 # Entry: ($method_name) -- name of the guarded method, used in the message.
584 # Must be called directly (not nested deeper) inside the guarded method.
585 # Exit: Returns normally if the caller is Sub::Protected or a subclass.
586 # Croaks with a descriptive message otherwise.
587 # Side effects: Calls Carp::croak on failure.
588 # Notes: caller() semantics from inside this sub:
589 # caller(0) -- the package in which the call TO this sub was made.
590 # That is the guarded method's package = Sub::Protected.
591 # caller(1) -- the package in which the call TO the guarded method
592 # was made. That is the actual external caller to check.
593 29 ▶sub _assert_private_caller {
Subroutine _assert_private_caller: called CC=4 SCAR=13.9
594 29 my ($method_name) = @_;
595  
596 # caller(1): the package that invoked the guarded method directly.
597 29 ▶ my $caller = (caller(1))[0] // q{};
Condition50%1/2
(&CORE::GLOBAL::caller(1))[0] // ""
l!l
290
MC/DC0%0/1
(&CORE::GLOBAL::caller(1))[0] // ""
(&CORE::GLOBAL::caller(1))[0]
Truth table50%1/2
A
A= (&CORE::GLOBAL::caller(1))[0]
Aresult
11
00
598 29 ▶ return if $caller eq $SELF || eval { $caller->isa($SELF) };
Branch: 1 branch
BranchTrueFalseTotal
if $caller eq $SELF or eval { do { $caller->isa($SELF) } } 17 12 29
Condition100%3/3
$caller eq $SELF or eval { do { $caller->isa($SELF) } }
l!l&&r!l&&!r
15212
MC/DC100%2/2
$caller eq $SELF or eval { do { $caller->isa($SELF) } }
$caller eq $SELF eval { do { $caller->isa($SELF) } }
Truth table100%3/3
A or B
A= $caller eq $SELFB= eval { do { $caller->isa($SELF) } }
ABresult
1X1
011
000
599  
600 12 croak "${method_name}() is a private method of $SELF"
601 . " and cannot be called from ${caller}";
602 }
603  
604 13 1;
605  
606 __END__
↑ Summary