xref: /openbsd-src/gnu/usr.bin/perl/dist/Carp/lib/Carp.pm (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1package Carp;
2
3{ use 5.006; }
4use strict;
5use warnings;
6
7BEGIN {
8    no strict "refs";
9    if(exists($::{"utf8::"}) && exists(*{$::{"utf8::"}}{HASH}->{"is_utf8"}) &&
10	    defined(*{*{$::{"utf8::"}}{HASH}->{"is_utf8"}}{CODE})) {
11	*is_utf8 = \&{"utf8::is_utf8"};
12    } else {
13	*is_utf8 = sub { 0 };
14    }
15}
16
17BEGIN {
18    no strict "refs";
19    if(exists($::{"utf8::"}) && exists(*{$::{"utf8::"}}{HASH}->{"downgrade"}) &&
20	    defined(*{*{$::{"utf8::"}}{HASH}->{"downgrade"}}{CODE})) {
21	*downgrade = \&{"utf8::downgrade"};
22    } else {
23	*downgrade = sub {};
24    }
25}
26
27our $VERSION = '1.29';
28
29our $MaxEvalLen = 0;
30our $Verbose    = 0;
31our $CarpLevel  = 0;
32our $MaxArgLen  = 64;    # How much of each argument to print. 0 = all.
33our $MaxArgNums = 8;     # How many arguments to print. 0 = all.
34
35require Exporter;
36our @ISA       = ('Exporter');
37our @EXPORT    = qw(confess croak carp);
38our @EXPORT_OK = qw(cluck verbose longmess shortmess);
39our @EXPORT_FAIL = qw(verbose);    # hook to enable verbose mode
40
41# The members of %Internal are packages that are internal to perl.
42# Carp will not report errors from within these packages if it
43# can.  The members of %CarpInternal are internal to Perl's warning
44# system.  Carp will not report errors from within these packages
45# either, and will not report calls *to* these packages for carp and
46# croak.  They replace $CarpLevel, which is deprecated.    The
47# $Max(EvalLen|(Arg(Len|Nums)) variables are used to specify how the eval
48# text and function arguments should be formatted when printed.
49
50our %CarpInternal;
51our %Internal;
52
53# disable these by default, so they can live w/o require Carp
54$CarpInternal{Carp}++;
55$CarpInternal{warnings}++;
56$Internal{Exporter}++;
57$Internal{'Exporter::Heavy'}++;
58
59# if the caller specifies verbose usage ("perl -MCarp=verbose script.pl")
60# then the following method will be called by the Exporter which knows
61# to do this thanks to @EXPORT_FAIL, above.  $_[1] will contain the word
62# 'verbose'.
63
64sub export_fail { shift; $Verbose = shift if $_[0] eq 'verbose'; @_ }
65
66sub _cgc {
67    no strict 'refs';
68    return \&{"CORE::GLOBAL::caller"} if defined &{"CORE::GLOBAL::caller"};
69    return;
70}
71
72sub longmess {
73    # Icky backwards compatibility wrapper. :-(
74    #
75    # The story is that the original implementation hard-coded the
76    # number of call levels to go back, so calls to longmess were off
77    # by one.  Other code began calling longmess and expecting this
78    # behaviour, so the replacement has to emulate that behaviour.
79    my $cgc = _cgc();
80    my $call_pack = $cgc ? $cgc->() : caller();
81    if ( $Internal{$call_pack} or $CarpInternal{$call_pack} ) {
82        return longmess_heavy(@_);
83    }
84    else {
85        local $CarpLevel = $CarpLevel + 1;
86        return longmess_heavy(@_);
87    }
88}
89
90our @CARP_NOT;
91
92sub shortmess {
93    my $cgc = _cgc();
94
95    # Icky backwards compatibility wrapper. :-(
96    local @CARP_NOT = $cgc ? $cgc->() : caller();
97    shortmess_heavy(@_);
98}
99
100sub croak   { die shortmess @_ }
101sub confess { die longmess @_ }
102sub carp    { warn shortmess @_ }
103sub cluck   { warn longmess @_ }
104
105BEGIN {
106    if("$]" >= 5.015002 || ("$]" >= 5.014002 && "$]" < 5.015) ||
107	    ("$]" >= 5.012005 && "$]" < 5.013)) {
108	*CALLER_OVERRIDE_CHECK_OK = sub () { 1 };
109    } else {
110	*CALLER_OVERRIDE_CHECK_OK = sub () { 0 };
111    }
112}
113
114sub caller_info {
115    my $i = shift(@_) + 1;
116    my %call_info;
117    my $cgc = _cgc();
118    {
119	# Some things override caller() but forget to implement the
120	# @DB::args part of it, which we need.  We check for this by
121	# pre-populating @DB::args with a sentinel which no-one else
122	# has the address of, so that we can detect whether @DB::args
123	# has been properly populated.  However, on earlier versions
124	# of perl this check tickles a bug in CORE::caller() which
125	# leaks memory.  So we only check on fixed perls.
126        @DB::args = \$i if CALLER_OVERRIDE_CHECK_OK;
127        package DB;
128        @call_info{
129            qw(pack file line sub has_args wantarray evaltext is_require) }
130            = $cgc ? $cgc->($i) : caller($i);
131    }
132
133    unless ( defined $call_info{file} ) {
134        return ();
135    }
136
137    my $sub_name = Carp::get_subname( \%call_info );
138    if ( $call_info{has_args} ) {
139        my @args;
140        if (CALLER_OVERRIDE_CHECK_OK && @DB::args == 1
141            && ref $DB::args[0] eq ref \$i
142            && $DB::args[0] == \$i ) {
143            @DB::args = ();    # Don't let anyone see the address of $i
144            local $@;
145            my $where = eval {
146                my $func    = $cgc or return '';
147                my $gv      =
148                    *{
149                        ( $::{"B::"} || return '')       # B stash
150                          ->{svref_2object} || return '' # entry in stash
151                     }{CODE}                             # coderef in entry
152                        ->($func)->GV;
153                my $package = $gv->STASH->NAME;
154                my $subname = $gv->NAME;
155                return unless defined $package && defined $subname;
156
157                # returning CORE::GLOBAL::caller isn't useful for tracing the cause:
158                return if $package eq 'CORE::GLOBAL' && $subname eq 'caller';
159                " in &${package}::$subname";
160            } || '';
161            @args
162                = "** Incomplete caller override detected$where; \@DB::args were not set **";
163        }
164        else {
165            @args = @DB::args;
166            my $overflow;
167            if ( $MaxArgNums and @args > $MaxArgNums )
168            {    # More than we want to show?
169                $#args = $MaxArgNums;
170                $overflow = 1;
171            }
172
173            @args = map { Carp::format_arg($_) } @args;
174
175            if ($overflow) {
176                push @args, '...';
177            }
178        }
179
180        # Push the args onto the subroutine
181        $sub_name .= '(' . join( ', ', @args ) . ')';
182    }
183    $call_info{sub_name} = $sub_name;
184    return wantarray() ? %call_info : \%call_info;
185}
186
187# Transform an argument to a function into a string.
188sub format_arg {
189    my $arg = shift;
190    if ( ref($arg) ) {
191        $arg = defined($overload::VERSION) ? overload::StrVal($arg) : "$arg";
192    }
193    if ( defined($arg) ) {
194        $arg =~ s/'/\\'/g;
195        $arg = str_len_trim( $arg, $MaxArgLen );
196
197        # Quote it?
198        # Downgrade, and use [0-9] rather than \d, to avoid loading
199        # Unicode tables, which would be liable to fail if we're
200        # processing a syntax error.
201        downgrade($arg, 1);
202        $arg = "'$arg'" unless $arg =~ /^-?[0-9.]+\z/;
203    }
204    else {
205        $arg = 'undef';
206    }
207
208    # The following handling of "control chars" is direct from
209    # the original code - it is broken on Unicode though.
210    # Suggestions?
211    is_utf8($arg)
212        or $arg =~ s/([[:cntrl:]]|[[:^ascii:]])/sprintf("\\x{%x}",ord($1))/eg;
213    return $arg;
214}
215
216# Takes an inheritance cache and a package and returns
217# an anon hash of known inheritances and anon array of
218# inheritances which consequences have not been figured
219# for.
220sub get_status {
221    my $cache = shift;
222    my $pkg   = shift;
223    $cache->{$pkg} ||= [ { $pkg => $pkg }, [ trusts_directly($pkg) ] ];
224    return @{ $cache->{$pkg} };
225}
226
227# Takes the info from caller() and figures out the name of
228# the sub/require/eval
229sub get_subname {
230    my $info = shift;
231    if ( defined( $info->{evaltext} ) ) {
232        my $eval = $info->{evaltext};
233        if ( $info->{is_require} ) {
234            return "require $eval";
235        }
236        else {
237            $eval =~ s/([\\\'])/\\$1/g;
238            return "eval '" . str_len_trim( $eval, $MaxEvalLen ) . "'";
239        }
240    }
241
242    # this can happen on older perls when the sub (or the stash containing it)
243    # has been deleted
244    if ( !defined( $info->{sub} ) ) {
245        return '__ANON__::__ANON__';
246    }
247
248    return ( $info->{sub} eq '(eval)' ) ? 'eval {...}' : $info->{sub};
249}
250
251# Figures out what call (from the point of view of the caller)
252# the long error backtrace should start at.
253sub long_error_loc {
254    my $i;
255    my $lvl = $CarpLevel;
256    {
257        ++$i;
258        my $cgc = _cgc();
259        my @caller = $cgc ? $cgc->($i) : caller($i);
260        my $pkg = $caller[0];
261        unless ( defined($pkg) ) {
262
263            # This *shouldn't* happen.
264            if (%Internal) {
265                local %Internal;
266                $i = long_error_loc();
267                last;
268            }
269            elsif (defined $caller[2]) {
270                # this can happen when the stash has been deleted
271                # in that case, just assume that it's a reasonable place to
272                # stop (the file and line data will still be intact in any
273                # case) - the only issue is that we can't detect if the
274                # deleted package was internal (so don't do that then)
275                # -doy
276                redo unless 0 > --$lvl;
277                last;
278            }
279            else {
280                return 2;
281            }
282        }
283        redo if $CarpInternal{$pkg};
284        redo unless 0 > --$lvl;
285        redo if $Internal{$pkg};
286    }
287    return $i - 1;
288}
289
290sub longmess_heavy {
291    return @_ if ref( $_[0] );    # don't break references as exceptions
292    my $i = long_error_loc();
293    return ret_backtrace( $i, @_ );
294}
295
296# Returns a full stack backtrace starting from where it is
297# told.
298sub ret_backtrace {
299    my ( $i, @error ) = @_;
300    my $mess;
301    my $err = join '', @error;
302    $i++;
303
304    my $tid_msg = '';
305    if ( defined &threads::tid ) {
306        my $tid = threads->tid;
307        $tid_msg = " thread $tid" if $tid;
308    }
309
310    my %i = caller_info($i);
311    $mess = "$err at $i{file} line $i{line}$tid_msg";
312    if( defined $. ) {
313        local $@ = '';
314        local $SIG{__DIE__};
315        eval {
316            CORE::die;
317        };
318        if($@ =~ /^Died at .*(, <.*?> line \d+).$/ ) {
319            $mess .= $1;
320        }
321    }
322    $mess .= "\.\n";
323
324    while ( my %i = caller_info( ++$i ) ) {
325        $mess .= "\t$i{sub_name} called at $i{file} line $i{line}$tid_msg\n";
326    }
327
328    return $mess;
329}
330
331sub ret_summary {
332    my ( $i, @error ) = @_;
333    my $err = join '', @error;
334    $i++;
335
336    my $tid_msg = '';
337    if ( defined &threads::tid ) {
338        my $tid = threads->tid;
339        $tid_msg = " thread $tid" if $tid;
340    }
341
342    my %i = caller_info($i);
343    return "$err at $i{file} line $i{line}$tid_msg\.\n";
344}
345
346sub short_error_loc {
347    # You have to create your (hash)ref out here, rather than defaulting it
348    # inside trusts *on a lexical*, as you want it to persist across calls.
349    # (You can default it on $_[2], but that gets messy)
350    my $cache = {};
351    my $i     = 1;
352    my $lvl   = $CarpLevel;
353    {
354        my $cgc = _cgc();
355        my $called = $cgc ? $cgc->($i) : caller($i);
356        $i++;
357        my $caller = $cgc ? $cgc->($i) : caller($i);
358
359        if (!defined($caller)) {
360            my @caller = $cgc ? $cgc->($i) : caller($i);
361            if (@caller) {
362                # if there's no package but there is other caller info, then
363                # the package has been deleted - treat this as a valid package
364                # in this case
365                redo if defined($called) && $CarpInternal{$called};
366                redo unless 0 > --$lvl;
367                last;
368            }
369            else {
370                return 0;
371            }
372        }
373        redo if $Internal{$caller};
374        redo if $CarpInternal{$caller};
375        redo if $CarpInternal{$called};
376        redo if trusts( $called, $caller, $cache );
377        redo if trusts( $caller, $called, $cache );
378        redo unless 0 > --$lvl;
379    }
380    return $i - 1;
381}
382
383sub shortmess_heavy {
384    return longmess_heavy(@_) if $Verbose;
385    return @_ if ref( $_[0] );    # don't break references as exceptions
386    my $i = short_error_loc();
387    if ($i) {
388        ret_summary( $i, @_ );
389    }
390    else {
391        longmess_heavy(@_);
392    }
393}
394
395# If a string is too long, trims it with ...
396sub str_len_trim {
397    my $str = shift;
398    my $max = shift || 0;
399    if ( 2 < $max and $max < length($str) ) {
400        substr( $str, $max - 3 ) = '...';
401    }
402    return $str;
403}
404
405# Takes two packages and an optional cache.  Says whether the
406# first inherits from the second.
407#
408# Recursive versions of this have to work to avoid certain
409# possible endless loops, and when following long chains of
410# inheritance are less efficient.
411sub trusts {
412    my $child  = shift;
413    my $parent = shift;
414    my $cache  = shift;
415    my ( $known, $partial ) = get_status( $cache, $child );
416
417    # Figure out consequences until we have an answer
418    while ( @$partial and not exists $known->{$parent} ) {
419        my $anc = shift @$partial;
420        next if exists $known->{$anc};
421        $known->{$anc}++;
422        my ( $anc_knows, $anc_partial ) = get_status( $cache, $anc );
423        my @found = keys %$anc_knows;
424        @$known{@found} = ();
425        push @$partial, @$anc_partial;
426    }
427    return exists $known->{$parent};
428}
429
430# Takes a package and gives a list of those trusted directly
431sub trusts_directly {
432    my $class = shift;
433    no strict 'refs';
434    no warnings 'once';
435    return @{"$class\::CARP_NOT"}
436        ? @{"$class\::CARP_NOT"}
437        : @{"$class\::ISA"};
438}
439
440if(!defined($warnings::VERSION) ||
441	do { no warnings "numeric"; $warnings::VERSION < 1.03 }) {
442    # Very old versions of warnings.pm import from Carp.  This can go
443    # wrong due to the circular dependency.  If Carp is invoked before
444    # warnings, then Carp starts by loading warnings, then warnings
445    # tries to import from Carp, and gets nothing because Carp is in
446    # the process of loading and hasn't defined its import method yet.
447    # So we work around that by manually exporting to warnings here.
448    no strict "refs";
449    *{"warnings::$_"} = \&$_ foreach @EXPORT;
450}
451
4521;
453
454__END__
455
456=head1 NAME
457
458Carp - alternative warn and die for modules
459
460=head1 SYNOPSIS
461
462    use Carp;
463
464    # warn user (from perspective of caller)
465    carp "string trimmed to 80 chars";
466
467    # die of errors (from perspective of caller)
468    croak "We're outta here!";
469
470    # die of errors with stack backtrace
471    confess "not implemented";
472
473    # cluck, longmess and shortmess not exported by default
474    use Carp qw(cluck longmess shortmess);
475    cluck "This is how we got here!";
476    $long_message   = longmess( "message from cluck() or confess()" );
477    $short_message  = shortmess( "message from carp() or croak()" );
478
479=head1 DESCRIPTION
480
481The Carp routines are useful in your own modules because
482they act like C<die()> or C<warn()>, but with a message which is more
483likely to be useful to a user of your module.  In the case of
484C<cluck()> and C<confess()>, that context is a summary of every
485call in the call-stack; C<longmess()> returns the contents of the error
486message.
487
488For a shorter message you can use C<carp()> or C<croak()> which report the
489error as being from where your module was called.  C<shortmess()> returns the
490contents of this error message.  There is no guarantee that that is where the
491error was, but it is a good educated guess.
492
493You can also alter the way the output and logic of C<Carp> works, by
494changing some global variables in the C<Carp> namespace. See the
495section on C<GLOBAL VARIABLES> below.
496
497Here is a more complete description of how C<carp> and C<croak> work.
498What they do is search the call-stack for a function call stack where
499they have not been told that there shouldn't be an error.  If every
500call is marked safe, they give up and give a full stack backtrace
501instead.  In other words they presume that the first likely looking
502potential suspect is guilty.  Their rules for telling whether
503a call shouldn't generate errors work as follows:
504
505=over 4
506
507=item 1.
508
509Any call from a package to itself is safe.
510
511=item 2.
512
513Packages claim that there won't be errors on calls to or from
514packages explicitly marked as safe by inclusion in C<@CARP_NOT>, or
515(if that array is empty) C<@ISA>.  The ability to override what
516@ISA says is new in 5.8.
517
518=item 3.
519
520The trust in item 2 is transitive.  If A trusts B, and B
521trusts C, then A trusts C.  So if you do not override C<@ISA>
522with C<@CARP_NOT>, then this trust relationship is identical to,
523"inherits from".
524
525=item 4.
526
527Any call from an internal Perl module is safe.  (Nothing keeps
528user modules from marking themselves as internal to Perl, but
529this practice is discouraged.)
530
531=item 5.
532
533Any call to Perl's warning system (eg Carp itself) is safe.
534(This rule is what keeps it from reporting the error at the
535point where you call C<carp> or C<croak>.)
536
537=item 6.
538
539C<$Carp::CarpLevel> can be set to skip a fixed number of additional
540call levels.  Using this is not recommended because it is very
541difficult to get it to behave correctly.
542
543=back
544
545=head2 Forcing a Stack Trace
546
547As a debugging aid, you can force Carp to treat a croak as a confess
548and a carp as a cluck across I<all> modules. In other words, force a
549detailed stack trace to be given.  This can be very helpful when trying
550to understand why, or from where, a warning or error is being generated.
551
552This feature is enabled by 'importing' the non-existent symbol
553'verbose'. You would typically enable it by saying
554
555    perl -MCarp=verbose script.pl
556
557or by including the string C<-MCarp=verbose> in the PERL5OPT
558environment variable.
559
560Alternately, you can set the global variable C<$Carp::Verbose> to true.
561See the C<GLOBAL VARIABLES> section below.
562
563=head1 GLOBAL VARIABLES
564
565=head2 $Carp::MaxEvalLen
566
567This variable determines how many characters of a string-eval are to
568be shown in the output. Use a value of C<0> to show all text.
569
570Defaults to C<0>.
571
572=head2 $Carp::MaxArgLen
573
574This variable determines how many characters of each argument to a
575function to print. Use a value of C<0> to show the full length of the
576argument.
577
578Defaults to C<64>.
579
580=head2 $Carp::MaxArgNums
581
582This variable determines how many arguments to each function to show.
583Use a value of C<0> to show all arguments to a function call.
584
585Defaults to C<8>.
586
587=head2 $Carp::Verbose
588
589This variable makes C<carp()> and C<croak()> generate stack backtraces
590just like C<cluck()> and C<confess()>.  This is how C<use Carp 'verbose'>
591is implemented internally.
592
593Defaults to C<0>.
594
595=head2 @CARP_NOT
596
597This variable, I<in your package>, says which packages are I<not> to be
598considered as the location of an error. The C<carp()> and C<cluck()>
599functions will skip over callers when reporting where an error occurred.
600
601NB: This variable must be in the package's symbol table, thus:
602
603    # These work
604    our @CARP_NOT; # file scope
605    use vars qw(@CARP_NOT); # package scope
606    @My::Package::CARP_NOT = ... ; # explicit package variable
607
608    # These don't work
609    sub xyz { ... @CARP_NOT = ... } # w/o declarations above
610    my @CARP_NOT; # even at top-level
611
612Example of use:
613
614    package My::Carping::Package;
615    use Carp;
616    our @CARP_NOT;
617    sub bar     { .... or _error('Wrong input') }
618    sub _error  {
619        # temporary control of where'ness, __PACKAGE__ is implicit
620        local @CARP_NOT = qw(My::Friendly::Caller);
621        carp(@_)
622    }
623
624This would make C<Carp> report the error as coming from a caller not
625in C<My::Carping::Package>, nor from C<My::Friendly::Caller>.
626
627Also read the L</DESCRIPTION> section above, about how C<Carp> decides
628where the error is reported from.
629
630Use C<@CARP_NOT>, instead of C<$Carp::CarpLevel>.
631
632Overrides C<Carp>'s use of C<@ISA>.
633
634=head2 %Carp::Internal
635
636This says what packages are internal to Perl.  C<Carp> will never
637report an error as being from a line in a package that is internal to
638Perl.  For example:
639
640    $Carp::Internal{ (__PACKAGE__) }++;
641    # time passes...
642    sub foo { ... or confess("whatever") };
643
644would give a full stack backtrace starting from the first caller
645outside of __PACKAGE__.  (Unless that package was also internal to
646Perl.)
647
648=head2 %Carp::CarpInternal
649
650This says which packages are internal to Perl's warning system.  For
651generating a full stack backtrace this is the same as being internal
652to Perl, the stack backtrace will not start inside packages that are
653listed in C<%Carp::CarpInternal>.  But it is slightly different for
654the summary message generated by C<carp> or C<croak>.  There errors
655will not be reported on any lines that are calling packages in
656C<%Carp::CarpInternal>.
657
658For example C<Carp> itself is listed in C<%Carp::CarpInternal>.
659Therefore the full stack backtrace from C<confess> will not start
660inside of C<Carp>, and the short message from calling C<croak> is
661not placed on the line where C<croak> was called.
662
663=head2 $Carp::CarpLevel
664
665This variable determines how many additional call frames are to be
666skipped that would not otherwise be when reporting where an error
667occurred on a call to one of C<Carp>'s functions.  It is fairly easy
668to count these call frames on calls that generate a full stack
669backtrace.  However it is much harder to do this accounting for calls
670that generate a short message.  Usually people skip too many call
671frames.  If they are lucky they skip enough that C<Carp> goes all of
672the way through the call stack, realizes that something is wrong, and
673then generates a full stack backtrace.  If they are unlucky then the
674error is reported from somewhere misleading very high in the call
675stack.
676
677Therefore it is best to avoid C<$Carp::CarpLevel>.  Instead use
678C<@CARP_NOT>, C<%Carp::Internal> and C<%Carp::CarpInternal>.
679
680Defaults to C<0>.
681
682=head1 BUGS
683
684The Carp routines don't handle exception objects currently.
685If called with a first argument that is a reference, they simply
686call die() or warn(), as appropriate.
687
688=head1 SEE ALSO
689
690L<Carp::Always>,
691L<Carp::Clan>
692
693=head1 AUTHOR
694
695The Carp module first appeared in Larry Wall's perl 5.000 distribution.
696Since then it has been modified by several of the perl 5 porters.
697Andrew Main (Zefram) <zefram@fysh.org> divested Carp into an independent
698distribution.
699
700=head1 COPYRIGHT
701
702Copyright (C) 1994-2012 Larry Wall
703
704Copyright (C) 2011, 2012 Andrew Main (Zefram) <zefram@fysh.org>
705
706=head1 LICENSE
707
708This module is free software; you can redistribute it and/or modify it
709under the same terms as Perl itself.
710