This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Extract _handle_cmd_wrapper_commands.
[perl5.git] / lib / dumpvar.pl
1 require 5.002;                  # For (defined ref)
2 package dumpvar;
3
4 # Needed for PrettyPrinter only:
5
6 # require 5.001;  # Well, it coredumps anyway undef DB in 5.000 (not now)
7
8 # translate control chars to ^X - Randal Schwartz
9 # Modifications to print types by Peter Gordon v1.0
10
11 # Ilya Zakharevich -- patches after 5.001 (and some before ;-)
12
13 # Won't dump symbol tables and contents of debugged files by default
14
15 $winsize = 80 unless defined $winsize;
16
17
18 # Defaults
19
20 # $globPrint = 1;
21 $printUndef = 1 unless defined $printUndef;
22 $tick = "auto" unless defined $tick;
23 $unctrl = 'quote' unless defined $unctrl;
24 $subdump = 1;
25 $dumpReused = 0 unless defined $dumpReused;
26 $bareStringify = 1 unless defined $bareStringify;
27
28 sub main::dumpValue {
29   local %address;
30   local $^W=0;
31   (print "undef\n"), return unless defined $_[0];
32   (print &stringify($_[0]), "\n"), return unless ref $_[0];
33   push @_, -1 if @_ == 1;
34   dumpvar::unwrap($_[0], 0, $_[1]);
35 }
36
37 # This one is good for variable names:
38
39 sub unctrl {
40     for (my($dummy) = shift) {
41         local($v) ; 
42
43         return \$_ if ref \$_ eq "GLOB";
44         if (ord('A') == 193) { # EBCDIC.
45             # EBCDIC has no concept of "\cA" or "A" being related
46             # to each other by a linear/boolean mapping.
47         } else {
48             s/([\001-\037\177])/'^'.pack('c',ord($1)^64)/eg;
49         }
50         return $_;
51     }
52 }
53
54 sub uniescape {
55     join("",
56          map { $_ > 255 ? sprintf("\\x{%04X}", $_) : chr($_) }
57              unpack("U*", $_[0]));
58 }
59
60 sub stringify {
61     (my $__, local $noticks) = @_;
62     for ($__) {
63         local($v) ; 
64         my $tick = $tick;
65
66         return 'undef' unless defined $_ or not $printUndef;
67         return $_ . "" if ref \$_ eq 'GLOB';
68         $_ = &{'overload::StrVal'}($_) 
69           if $bareStringify and ref $_ 
70             and %overload:: and defined &{'overload::StrVal'};
71         
72         if ($tick eq 'auto') {
73             if (ord('A') == 193) {
74                 if (/[\000-\011]/ or /[\013-\024\31-\037\177]/) {
75                     $tick = '"';
76                 } else {
77                     $tick = "'";
78                 }
79             }  else {
80                 if (/[\000-\011\013-\037\177]/) {
81                     $tick = '"';
82                 } else {
83                     $tick = "'";
84                 }
85             }
86         }
87         if ($tick eq "'") {
88           s/([\'\\])/\\$1/g;
89         } elsif ($unctrl eq 'unctrl') {
90           s/([\"\\])/\\$1/g ;
91           s/([\000-\037\177])/'^'.pack('c',ord($1)^64)/eg;
92           # uniescape?
93           s/([\200-\377])/'\\0x'.sprintf('%2X',ord($1))/eg 
94             if $quoteHighBit;
95         } elsif ($unctrl eq 'quote') {
96           s/([\"\\\$\@])/\\$1/g if $tick eq '"';
97           s/\033/\\e/g;
98           if (ord('A') == 193) { # EBCDIC.
99               s/([\000-\037\177])/'\\c'.chr(193)/eg; # Unfinished.
100           } else {
101               s/([\000-\037\177])/'\\c'._escaped_ord($1)/eg;
102           }
103         }
104         $_ = uniescape($_);
105         s/([\200-\377])/'\\'.sprintf('%3o',ord($1))/eg if $quoteHighBit;
106         return ($noticks || /^\d+(\.\d*)?\Z/) 
107           ? $_ 
108           : $tick . $_ . $tick;
109     }
110 }
111
112 # Ensure a resulting \ is escaped to be \\
113 sub _escaped_ord {
114     my $chr = shift;
115     $chr = chr(ord($chr)^64);
116     $chr =~ s{\\}{\\\\}g;
117     return $chr;
118 }
119
120 sub ShortArray {
121   my $tArrayDepth = $#{$_[0]} ; 
122   $tArrayDepth = $#{$_[0]} < $arrayDepth-1 ? $#{$_[0]} : $arrayDepth-1 
123     unless  $arrayDepth eq '' ; 
124   my $shortmore = "";
125   $shortmore = " ..." if $tArrayDepth < $#{$_[0]} ;
126   if (!grep(ref $_, @{$_[0]})) {
127     $short = "0..$#{$_[0]}  '" . 
128       join("' '", @{$_[0]}[0..$tArrayDepth]) . "'$shortmore";
129     return $short if length $short <= $compactDump;
130   }
131   undef;
132 }
133
134 sub DumpElem {
135   my $short = &stringify($_[0], ref $_[0]);
136   if ($veryCompact && ref $_[0]
137       && (ref $_[0] eq 'ARRAY' and !grep(ref $_, @{$_[0]}) )) {
138     my $end = "0..$#{$v}  '" . 
139       join("' '", @{$_[0]}[0..$tArrayDepth]) . "'$shortmore";
140   } elsif ($veryCompact && ref $_[0]
141       && (ref $_[0] eq 'HASH') and !grep(ref $_, values %{$_[0]})) {
142     my $end = 1;
143           $short = $sp . "0..$#{$v}  '" . 
144             join("' '", @{$v}[0..$tArrayDepth]) . "'$shortmore";
145   } else {
146     print "$short\n";
147     unwrap($_[0],$_[1],$_[2]) if ref $_[0];
148   }
149 }
150
151 sub unwrap {
152     return if $DB::signal;
153     local($v) = shift ; 
154     local($s) = shift ; # extra no of spaces
155     local($m) = shift ; # maximum recursion depth
156     return if $m == 0;
157     local(%v,@v,$sp,$value,$key,@sortKeys,$more,$shortmore,$short) ;
158     local($tHashDepth,$tArrayDepth) ;
159
160     $sp = " " x $s ;
161     $s += 3 ; 
162
163     # Check for reused addresses
164     if (ref $v) { 
165       my $val = $v;
166       $val = &{'overload::StrVal'}($v) 
167         if %overload:: and defined &{'overload::StrVal'};
168       # Match type and address.                      
169       # Unblessed references will look like TYPE(0x...)
170       # Blessed references will look like Class=TYPE(0x...)
171       $val =~ s/^.*=//; # suppress the Class part, just keep TYPE(0x...)
172       ($item_type, $address) = 
173         $val =~ /([^\(]+)        # Keep stuff that's     
174                                  # not an open paren
175                  \(              # Skip open paren
176                  (0x[0-9a-f]+)   # Save the address
177                  \)              # Skip close paren
178                  $/x;            # Should be at end now
179
180       if (!$dumpReused && defined $address) { 
181         $address{$address}++ ;
182         if ( $address{$address} > 1 ) { 
183           print "${sp}-> REUSED_ADDRESS\n" ; 
184           return ; 
185         } 
186       }
187     } elsif (ref \$v eq 'GLOB') {
188       # This is a raw glob. Special handling for that.
189       $address = "$v" . "";     # To avoid a bug with globs
190       $address{$address}++ ;
191       if ( $address{$address} > 1 ) { 
192         print "${sp}*DUMPED_GLOB*\n" ; 
193         return ; 
194       } 
195     }
196
197     if (ref $v eq 'Regexp') {
198       # Reformat the regexp to look the standard way.
199       my $re = "$v";
200       $re =~ s,/,\\/,g;
201       print "$sp-> qr/$re/\n";
202       return;
203     }
204
205     if ( $item_type eq 'HASH' ) { 
206         # Hash ref or hash-based object.
207         my @sortKeys = sort keys(%$v) ;
208         undef $more ; 
209         $tHashDepth = $#sortKeys ; 
210         $tHashDepth = $#sortKeys < $hashDepth-1 ? $#sortKeys : $hashDepth-1
211           unless $hashDepth eq '' ; 
212         $more = "....\n" if $tHashDepth < $#sortKeys ; 
213         $shortmore = "";
214         $shortmore = ", ..." if $tHashDepth < $#sortKeys ; 
215         $#sortKeys = $tHashDepth ; 
216         if ($compactDump && !grep(ref $_, values %{$v})) {
217           #$short = $sp . 
218           #  (join ', ', 
219 # Next row core dumps during require from DB on 5.000, even with map {"_"}
220           #   map {&stringify($_) . " => " . &stringify($v->{$_})} 
221           #   @sortKeys) . "'$shortmore";
222           $short = $sp;
223           my @keys;
224           for (@sortKeys) {
225             push @keys, &stringify($_) . " => " . &stringify($v->{$_});
226           }
227           $short .= join ', ', @keys;
228           $short .= $shortmore;
229           (print "$short\n"), return if length $short <= $compactDump;
230         }
231         for $key (@sortKeys) {
232             return if $DB::signal;
233             $value = $ {$v}{$key} ;
234             print "$sp", &stringify($key), " => ";
235             DumpElem $value, $s, $m-1;
236         }
237         print "$sp  empty hash\n" unless @sortKeys;
238         print "$sp$more" if defined $more ;
239     } elsif ( $item_type eq 'ARRAY' ) { 
240         # Array ref or array-based object. Also: undef.
241         # See how big the array is.
242         $tArrayDepth = $#{$v} ; 
243         undef $more ; 
244         # Bigger than the max?
245         $tArrayDepth = $#{$v} < $arrayDepth-1 ? $#{$v} : $arrayDepth-1 
246           if defined $arrayDepth && $arrayDepth ne '';
247         # Yep. Don't show it all.
248         $more = "....\n" if $tArrayDepth < $#{$v} ; 
249         $shortmore = "";
250         $shortmore = " ..." if $tArrayDepth < $#{$v} ;
251
252         if ($compactDump && !grep(ref $_, @{$v})) {
253           if ($#$v >= 0) {
254             $short = $sp . "0..$#{$v}  " . 
255               join(" ", 
256                    map {exists $v->[$_] ? stringify $v->[$_] : "empty"} (0..$tArrayDepth)
257                   ) . "$shortmore";
258           } else {
259             $short = $sp . "empty array";
260           }
261           (print "$short\n"), return if length $short <= $compactDump;
262         }
263         #if ($compactDump && $short = ShortArray($v)) {
264         #  print "$short\n";
265         #  return;
266         #}
267         for $num (0 .. $tArrayDepth) {
268             return if $DB::signal;
269             print "$sp$num  ";
270             if (exists $v->[$num]) {
271                 if (defined $v->[$num]) {
272                   DumpElem $v->[$num], $s, $m-1;
273                 } 
274                 else {
275                   print "undef\n";
276                 }
277             } else {
278                 print "empty slot\n";
279             }
280         }
281         print "$sp  empty array\n" unless @$v;
282         print "$sp$more" if defined $more ;  
283     } elsif ( $item_type eq 'SCALAR' ) { 
284             unless (defined $$v) {
285               print "$sp-> undef\n";
286               return;
287             }
288             print "$sp-> ";
289             DumpElem $$v, $s, $m-1;
290     } elsif ( $item_type eq 'REF' ) { 
291             print "$sp-> $$v\n";
292             return unless defined $$v;
293             unwrap($$v, $s+3, $m-1);
294     } elsif ( $item_type eq 'CODE' ) { 
295             # Code object or reference.
296             print "$sp-> ";
297             dumpsub (0, $v);
298     } elsif ( $item_type eq 'GLOB' ) {
299       # Glob object or reference.
300       print "$sp-> ",&stringify($$v,1),"\n";
301       if ($globPrint) {
302         $s += 3;
303        dumpglob($s, "{$$v}", $$v, 1, $m-1);
304       } elsif (defined ($fileno = eval {fileno($v)})) {
305         print( (' ' x ($s+3)) .  "FileHandle({$$v}) => fileno($fileno)\n" );
306       }
307     } elsif (ref \$v eq 'GLOB') {
308       # Raw glob (again?)
309       if ($globPrint) {
310        dumpglob($s, "{$v}", $v, 1, $m-1) if $globPrint;
311       } elsif (defined ($fileno = eval {fileno(\$v)})) {
312         print( (' ' x $s) .  "FileHandle({$v}) => fileno($fileno)\n" );
313       }
314     }
315 }
316
317 sub matchlex {
318   (my $var = $_[0]) =~ s/.//;
319   $var eq $_[1] or 
320     ($_[1] =~ /^([!~])(.)([\x00-\xff]*)/) and 
321       ($1 eq '!') ^ (eval { $var =~ /$2$3/ });
322 }
323
324 sub matchvar {
325   $_[0] eq $_[1] or 
326     ($_[1] =~ /^([!~])(.)([\x00-\xff]*)/) and 
327       ($1 eq '!') ^ (eval {($_[2] . "::" . $_[0]) =~ /$2$3/});
328 }
329
330 sub compactDump {
331   $compactDump = shift if @_;
332   $compactDump = 6*80-1 if $compactDump and $compactDump < 2;
333   $compactDump;
334 }
335
336 sub veryCompact {
337   $veryCompact = shift if @_;
338   compactDump(1) if !$compactDump and $veryCompact;
339   $veryCompact;
340 }
341
342 sub unctrlSet {
343   if (@_) {
344     my $in = shift;
345     if ($in eq 'unctrl' or $in eq 'quote') {
346       $unctrl = $in;
347     } else {
348       print "Unknown value for 'unctrl'.\n";
349     }
350   }
351   $unctrl;
352 }
353
354 sub quote {
355   if (@_ and $_[0] eq '"') {
356     $tick = '"';
357     $unctrl = 'quote';
358   } elsif (@_ and $_[0] eq 'auto') {
359     $tick = 'auto';
360     $unctrl = 'quote';
361   } elsif (@_) {                # Need to set
362     $tick = "'";
363     $unctrl = 'unctrl';
364   }
365   $tick;
366 }
367
368 sub dumpglob {
369     return if $DB::signal;
370     my ($off,$key, $val, $all, $m) = @_;
371     local(*entry) = $val;
372     my $fileno;
373     if (($key !~ /^_</ or $dumpDBFiles) and defined $entry) {
374       print( (' ' x $off) . "\$", &unctrl($key), " = " );
375       DumpElem $entry, 3+$off, $m;
376     }
377     if (($key !~ /^_</ or $dumpDBFiles) and @entry) {
378       print( (' ' x $off) . "\@$key = (\n" );
379       unwrap(\@entry,3+$off,$m) ;
380       print( (' ' x $off) .  ")\n" );
381     }
382     if ($key ne "main::" && $key ne "DB::" && %entry
383         && ($dumpPackages or $key !~ /::$/)
384         && ($key !~ /^_</ or $dumpDBFiles)
385         && !($package eq "dumpvar" and $key eq "stab")) {
386       print( (' ' x $off) . "\%$key = (\n" );
387       unwrap(\%entry,3+$off,$m) ;
388       print( (' ' x $off) .  ")\n" );
389     }
390     if (defined ($fileno = eval{fileno(*entry)})) {
391       print( (' ' x $off) .  "FileHandle($key) => fileno($fileno)\n" );
392     }
393     if ($all) {
394       if (defined &entry) {
395         dumpsub($off, $key);
396       }
397     }
398 }
399
400 sub dumplex {
401   return if $DB::signal;
402   my ($key, $val, $m, @vars) = @_;
403   return if @vars && !grep( matchlex($key, $_), @vars );
404   local %address;
405   my $off = 0;  # It reads better this way
406   my $fileno;
407   if (UNIVERSAL::isa($val,'ARRAY')) {
408     print( (' ' x $off) . "$key = (\n" );
409     unwrap($val,3+$off,$m) ;
410     print( (' ' x $off) .  ")\n" );
411   }
412   elsif (UNIVERSAL::isa($val,'HASH')) {
413     print( (' ' x $off) . "$key = (\n" );
414     unwrap($val,3+$off,$m) ;
415     print( (' ' x $off) .  ")\n" );
416   }
417   elsif (UNIVERSAL::isa($val,'IO')) {
418     print( (' ' x $off) .  "FileHandle($key) => fileno($fileno)\n" );
419   }
420   #  No lexical subroutines yet...
421   #  elsif (UNIVERSAL::isa($val,'CODE')) {
422   #    dumpsub($off, $$val);
423   #  }
424   else {
425     print( (' ' x $off) . &unctrl($key), " = " );
426     DumpElem $$val, 3+$off, $m;
427   }
428 }
429
430 sub CvGV_name_or_bust {
431   my $in = shift;
432   return if $skipCvGV;          # Backdoor to avoid problems if XS broken...
433   $in = \&$in;                  # Hard reference...
434   eval {require Devel::Peek; 1} or return;
435   my $gv = Devel::Peek::CvGV($in) or return;
436   *$gv{PACKAGE} . '::' . *$gv{NAME};
437 }
438
439 sub dumpsub {
440     my ($off,$sub) = @_;
441     my $ini = $sub;
442     my $s;
443     $sub = $1 if $sub =~ /^\{\*(.*)\}$/;
444     my $subref = defined $1 ? \&$sub : \&$ini;
445     my $place = $DB::sub{$sub} || (($s = $subs{"$subref"}) && $DB::sub{$s})
446       || (($s = CvGV_name_or_bust($subref)) && $DB::sub{$s})
447       || ($subdump && ($s = findsubs("$subref")) && $DB::sub{$s});
448     $place = '???' unless defined $place;
449     $s = $sub unless defined $s;
450     print( (' ' x $off) .  "&$s in $place\n" );
451 }
452
453 sub findsubs {
454   return undef unless %DB::sub;
455   my ($addr, $name, $loc);
456   while (($name, $loc) = each %DB::sub) {
457     $addr = \&$name;
458     $subs{"$addr"} = $name;
459   }
460   $subdump = 0;
461   $subs{ shift() };
462 }
463
464 sub main::dumpvar {
465     my ($package,$m,@vars) = @_;
466     local(%address,$key,$val,$^W);
467     $package .= "::" unless $package =~ /::$/;
468     *stab = *{"main::"};
469     while ($package =~ /(\w+?::)/g){
470       *stab = $ {stab}{$1};
471     }
472     local $TotalStrings = 0;
473     local $Strings = 0;
474     local $CompleteTotal = 0;
475     while (($key,$val) = each(%stab)) {
476       return if $DB::signal;
477       next if @vars && !grep( matchvar($key, $_), @vars );
478       if ($usageOnly) {
479         globUsage(\$val, $key)
480           if ($package ne 'dumpvar' or $key ne 'stab')
481              and ref(\$val) eq 'GLOB';
482       } else {
483        dumpglob(0,$key, $val, 0, $m);
484       }
485     }
486     if ($usageOnly) {
487       print "String space: $TotalStrings bytes in $Strings strings.\n";
488       $CompleteTotal += $TotalStrings;
489       print "Grand total = $CompleteTotal bytes (1 level deep) + overhead.\n";
490     }
491 }
492
493 sub scalarUsage {
494   my $size = length($_[0]);
495   $TotalStrings += $size;
496   $Strings++;
497   $size;
498 }
499
500 sub arrayUsage {                # array ref, name
501   my $size = 0;
502   map {$size += scalarUsage($_)} @{$_[0]};
503   my $len = @{$_[0]};
504   print "\@$_[1] = $len item", ($len > 1 ? "s" : ""),
505     " (data: $size bytes)\n"
506       if defined $_[1];
507   $CompleteTotal +=  $size;
508   $size;
509 }
510
511 sub hashUsage {         # hash ref, name
512   my @keys = keys %{$_[0]};
513   my @values = values %{$_[0]};
514   my $keys = arrayUsage \@keys;
515   my $values = arrayUsage \@values;
516   my $len = @keys;
517   my $total = $keys + $values;
518   print "\%$_[1] = $len item", ($len > 1 ? "s" : ""),
519     " (keys: $keys; values: $values; total: $total bytes)\n"
520       if defined $_[1];
521   $total;
522 }
523
524 sub globUsage {                 # glob ref, name
525   local *name = *{$_[0]};
526   $total = 0;
527   $total += scalarUsage $name if defined $name;
528   $total += arrayUsage \@name, $_[1] if @name;
529   $total += hashUsage \%name, $_[1] if %name and $_[1] ne "main::" 
530     and $_[1] ne "DB::";   #and !($package eq "dumpvar" and $key eq "stab"));
531   $total;
532 }
533
534 sub packageUsage {
535   my ($package,@vars) = @_;
536   $package .= "::" unless $package =~ /::$/;
537   local *stab = *{"main::"};
538   while ($package =~ /(\w+?::)/g){
539     *stab = $ {stab}{$1};
540   }
541   local $TotalStrings = 0;
542   local $CompleteTotal = 0;
543   my ($key,$val);
544   while (($key,$val) = each(%stab)) {
545     next if @vars && !grep($key eq $_,@vars);
546     globUsage \$val, $key unless $package eq 'dumpvar' and $key eq 'stab';
547   }
548   print "String space: $TotalStrings.\n";
549   $CompleteTotal += $TotalStrings;
550   print "\nGrand total = $CompleteTotal bytes\n";
551 }
552
553 1;
554