blib/lib/Devel/Trepan/CmdProcessor/Command/Deparse.pm untested

filter: Statementstmt 0.0% 0 / 261 Branchbran 0.0% 0 / 84 Conditioncond 0.0% 0 / 24 MC/DCmcdc 0.0% 0 / 15 Subroutinesub 0.0% 0 / 32 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 421 CC 42 SCAR 68.0
CC
42
Cov
0%
run
1640.0
address_options
12.0
complete
2.0
CRAP 899.9
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2014-2015, 2018 Rocky Bernstein <rocky@cpan.org>
3  
4 use rlib '../../../..';
5  
6  
7 use warnings; no warnings 'redefine';
8 use B;
9 use Data::Printer;
10 use 5.010;
11  
12 package Devel::Trepan::CmdProcessor::Command::Deparse;
13  
14 use B::DeparseTree::Fragment;
15 use Devel::Trepan::Deparse;
16 use Devel::Trepan::DB::LineCache;
17  
18 use Scalar::Util qw(looks_like_number);
19 use English qw( -no_match_vars );
20 use Getopt::Long qw(GetOptionsFromArray);
21 Getopt::Long::Configure("pass_through");
22  
23 use constant CATEGORY => 'data';
24 use constant SHORT_HELP => 'Deparse source code via B::DeparseTree';
25 use constant MIN_ARGS => 0; # Need at least this many
26 use constant MAX_ARGS => undef;
27 use constant NEED_STACK => 0;
28  
29  
30 use Devel::Trepan::CmdProcessor::Command qw(@CMD_ISA @CMD_VARS set_name);
31  
32 use strict;
33 # require 64-bit since we may have 64-bit hexadecimal-numbers as
34 # addresses
35 no warnings 'portable';
36  
37 use vars qw(@ISA @EXPORT);
38 @ISA = qw(Devel::Trepan::CmdProcessor::Command);
39  
40 use vars @CMD_VARS; # Value inherited from parent
41  
42 our $NAME = set_name();
43 =head2 Synopsis:
44  
45 =cut
46 our $HELP = <<'HELP';
47 =pod
48  
49 B<deparse> [I<address options>] [0xOP-address | . ]
50  
51 B<deparse> [I<B::DeparseTree-options>] {I<filename> | I<subroutine>}
52  
53 In the first form with an OP address, "," or no arguments, deparse
54 around where the program is currently stopped. If "dump" or "tree" is
55 given we show lower-level output from L<B::DeparseTree::Print>. In
56 the former case, just for the opcode and in the later case for the
57 deparsed tree.
58  
59 In the second form with a function or filename, L<B::DeparseTree>
60 shows information for that file or function.
61  
62 B::DeparseTree options:
63  
64 -t | --tree Show full optree
65 -l | --line Add '# line' comment
66 --offsets show all offsets
67 -a | --address Add 'OP addresses in '# line' comment
68 -f | --function Set function to look up offset
69 -p | --parent <n> Show parent text to level <n>
70 -q | --quote Expand double-quoted strings
71 -d | --debug Show debug information
72 -h | --help run 'help deparse' (this text)
73  
74  
75 Deparse Perl source code using L<B::DeparseTree>.
76  
77 Without arguments, deparses the current statement, if we can.
78  
79 =head2 Examples:
80  
81 deparse # deparse current statement
82 deparse -a # deparse current statement showing
83 # line and OP address
84 deparse 0xcafebabe # decode an opcode address.
85 deparse @0xcafebabe # same as above
86 deparse file.pm
87 deparse -l file.pm
88  
89 =head2 See also:
90  
91 L<C<list>|Devel::Trepan::CmdProcessor::Command::List>, and
92 L<B::DeparseTree> for more information on deparse options.
93  
94 =cut
95 HELP
96  
97 # FIXME: Should we include all files?
98 # Combine with BREAK completion.
99 sub complete($$)
100 {
101 my ($self, $prefix) = @_;
102 my $filename = $self->{proc}->filename;
103 # For line numbers we'll use stoppable line number even though one
104 # can enter line numbers that don't have breakpoints associated with them
105 my @completions = sort DB::subs();
106 Devel::Trepan::Complete::complete_token(\@completions, $prefix);
107 }
108  
109 sub parse_options($$)
110 {
111 my ($self, $args) = @_;
112 $Getopt::Long::autoabbrev = 1;
113 my $opts = {};
114 my $result =
115 &GetOptionsFromArray($args,
116 'h|help' => \$opts->{'help'},
117 't|tree' => \$opts->{'tree'},
118 'l|line' => \$opts->{'line'},
119 'offsets' => \$opts->{'offsets'},
120 'p|parent:i' => \$opts->{'parent'},
121 'P|previous' => \$opts->{'previous'},
122 'a|address' => \$opts->{'address'},
123 'f|function:s' => \$opts->{'function'},
124 'q|quote' => \$opts->{'quote'},
125 'debug' => \$opts->{'debug'}
126 );
127 $opts;
128 }
129  
130 sub address_options($$$)
131 {
132 my ($proc, $op_info, $what) = @_;
133 if ($what eq 'dump') {
134 $proc->msg(B::DeparseTree::Printer::format_info($op_info));
135 } elsif ($what eq 'tree') {
136 $proc->msg(B::DeparseTree::Printer::format_info_walk($op_info, 0));
137 }
138  
139 }
140  
141 # FIXME combine with Command::columnize_commands
142 use Array::Columnize;
143 sub columnize_addrs($$)
144 {
145 my ($proc, $commands) = @_;
146 my $width = $proc->{settings}->{maxwidth};
147 my $r = Array::Columnize::columnize($commands,
148 {displaywidth => $width,
149 colsep => ' ',
150 ljust => 1,
151 lineprefix => ' '});
152 chomp $r;
153 return $r;
154 }
155  
156 # This method runs the command
157 sub run($$)
158 {
159 my ($self, $args) = @_;
160 my @args = @$args;
161 @args = splice(@args, 1, scalar(@args), -2);
162 my $options = parse_options($self, \@args);
163  
164 my $proc = $self->{proc};
165 if ($options->{'help'}) {
166 my $help_cmd = $proc->{commands}{help};
167 $help_cmd->run( ['help', 'deparse'] );
168 return;
169 }
170  
171 # Get frame information
172 my $have_frame = exists($proc->{frame_index});
173 my ($frame_num, $frame, $funcname, $filename, $pkg);
174 if ($have_frame) {
175 $frame_num = $proc->{frame_index};
176 my $is_last = $frame_num == $proc->{stack_size}-1;
177 $frame = $proc->{frame};
178 $filename = $frame->{file};
179 unless ($is_last) {
180 $funcname = $frame->{fn};
181 } else {
182 $funcname = "DB::DB";
183 }
184 $pkg = $frame->{pkg};
185 }
186  
187 $funcname = $options->{'function'} if $options->{'function'};
188  
189 my $addr;
190 my $want_runtime_position = 0;
191 my $want_prev_position = $have_frame &&
192 ($frame_num != 0) || $options->{'previous'};
193 if (scalar @args == 0) {
194 # Use function if there is one. Otherwise use
195 # the current file.
196 if ($have_frame) {
197 $want_runtime_position = 1;
198 $addr = $frame->{addr};
199 }
200 } elsif (scalar @args <= 2) {
201 if ($args[0] =~ /^@?(0x[0-9a-fA-F]+)/) {
202 $want_runtime_position = 1;
203 $addr = hex($1);
204 } elsif ($args[0] eq '.') {
205 $want_runtime_position = 1;
206 $addr = $proc->{op_addr};
207 } else {
208 $filename = $args[0];
209 my $subname = $filename;
210 $subname = "main::$subname" if index($subname, '::') == -1;
211 my $matches = $self->{dbgr}->subs($subname);
212 if ($matches >= 1) {
213 $funcname = $subname;
214 $want_runtime_position = 1;
215 } else {
216 my $canonic_name = map_file($filename);
217 if (is_cached($canonic_name)) {
218 $filename = $canonic_name;
219 }
220 }
221 }
222 } else {
223 $proc->errmsg('Expecting and address or one file or function name');
224 return;
225 }
226  
227 if ($options->{'tree'} || $options->{'offsets'}) {
228 my $deparse = B::DeparseTree->new();
229 # if ($funcname eq "DB::DB") {
230 # $funcname = "main::main";
231 # }
232 $deparse->coderef2info(\&$funcname);
233 if ($options->{'tree'}) {
234 Data::Printer::p $deparse->{optree};
235 } elsif ($options->{'offsets'}) {
236 my @addrs = sort keys %{$deparse->{optree}};
237 @addrs = map sprintf("0x%x", $_), @addrs;
238 my $msg = columnize_addrs($proc, \@addrs);
239 $proc->section("Addresses in $funcname");
240 $proc->msg($msg);
241 }
242 return;
243 }
244  
245 my $text;
246 # FIXME: we assume func below, add parse options like filename, and
247 if ($want_runtime_position) {
248 # FIXME: ideally the variable $deparse would be internal only
249 # to deparse_offset However some branches need $deparse is
250 # used for other purposes rather than duplicate this code, it
251 # is here once, on the most likely branches it is not used.
252 my $deparse = B::DeparseTree->new();
253  
254 if ($addr) {
255 my $op_info = deparse_offset($funcname, $addr);
256 if (!$op_info) {
257 $proc->errmsg(sprintf("Can't find info for op at 0x%x in $funcname", $addr));
258 return;
259 }
260 if ($want_prev_position) {
261 $op_info = get_prev_addr_info($op_info);
262 }
263 if ($op_info) {
264 my $parent_count = $options->{parent};
265 if (looks_like_number($options->{parent})) {
266 my $maxwidth = $proc->{settings}->{maxwidth};
267 my $sep = ' -' x ($maxwidth / 2 > 20 ? 20 : $maxwidth / 2);
268 for (my $i=0; $i <= $parent_count && $op_info; $i++) {
269 $proc->msg($proc->bolden(sprintf("%02d %s:", $i, $op_info->{type})));
270 pmsg($proc, $op_info->{text});
271 $op_info = get_parent_addr_info($op_info);
272 $proc->msg($sep) if $i <= ($parent_count-1) && $op_info;
273 }
274 return;
275 }
276  
277 my $parent_info = get_parent_addr_info($op_info);
278 if ($op_info->{parent}) {
279 if ($options->{debug}) {
280 use Data::Printer;
281 p $op_info ;
282 $proc->msg('- -' x 20);
283 p $parent_info;
284 }
285 my $op = $op_info->{op};
286  
287 my $mess = '';
288 if ($addr != $op_info->{addr}) {
289 $mess .= "a subchild of ";
290 }
291  
292 $mess .= $op_info->{type};
293  
294 if ($op->can('name')) {
295 $mess .= sprintf(', %s ', $op->name);
296 } else {
297 $mess .= ', '
298 }
299 if ($proc->{op_addr} and $addr == $proc->{op_addr}) {
300 $mess .= sprintf("%s\n\tat address 0x%x:", $op, $proc->{op_addr});
301 }
302 $proc->msg($mess);
303 my $extract_texts = extract_node_info($op_info);
304 if ($extract_texts) {
305 pmsg($proc, join("\n", @$extract_texts))
306 } else {
307 pmsg($proc, $op_info->{text});
308 }
309 } else {
310 pmsg($proc, $op_info->{text});
311 }
312 address_options($proc, $op_info, $args[1]) if $args[1];
313 return;
314 } else {
315 $proc->errmsg(sprintf("Can't find info for op at 0x%x", $addr));
316 # use Data::Printer; Data::Printer::p $deparse->{optree};
317 }
318 return;
319 } elsif (scalar @args >= 1 and ($args[0]) =~ /^@?(0x[0-9a-fA-F]+)/) {
320 my $addr = hex($1);
321 my ($op_info) = deparse_offset($funcname, $addr);
322 if ($op_info) {
323 if (scalar(@args) == 2 ) {
324 address_options($proc, $op_info, $args[1])
325 } else {
326 my $parent_info = deparse_offset($funcname, $op_info->{parent});
327 if ($parent_info) {
328 pmsg_info($proc, $options, '', $op_info);
329 pmsg_info($proc, $options, ' contained in', $parent_info);
330 return;
331 }
332 pmsg_info($proc, $options, 'code to run next', $op_info);
333 }
334 address_options($proc, $op_info, $args[1]) if $args[1];
335 } else {
336 $proc->errmsg(sprintf("Can't find info for op at %s", $addr));
337 }
338 } else {
339 my @package_parts = split(/::/, $funcname);
340 my $prefix = '';
341 $prefix = join('::', @package_parts[0..scalar(@package_parts) - 1])
342 if @package_parts;
343 my $short_func = $package_parts[-1];
344 $text = "package $prefix;\nsub $short_func" . $deparse->coderef2text(\&$funcname);
345 pmsg($proc, $text, 0);
346 return;
347 }
348 } else {
349 my $deparse_opts='';
350 foreach my $opt ('dumper', 'line', 'address') {
351 if ($options->{$opt}) {
352 $deparse_opts .= ('-' . substr($deparse_opts, 0, 1))
353 }
354 }
355 if ($filename && !-r $filename) {
356 $proc->errmsg("No readable perl script: " . $filename)
357 } else {
358 my $deparse_opts = '';
359 my $cmd="$EXECUTABLE_NAME -MO=DeparseTree,-sC,$deparse_opts $filename";
360 $text = `$cmd 2>&1`;
361 if ($? >> 8 == 0) {
362 pmsg($proc, $text, 0);
363 } else {
364 $proc->errmsg("Error running $cmd");
365 $proc->errmsg($text);
366 }
367 }
368 return;
369 }
370 }
371  
372 unless (caller) {
373 require Devel::Trepan::CmdProcessor;
374 my $proc = Devel::Trepan::CmdProcessor->new(undef, 'bogus');
375 my $cmd = __PACKAGE__->new($proc);
376 require Devel::Trepan::DB::Sub;
377 require Devel::Trepan::DB::LineCache;
378 # cache_file(__FILE__);
379 my $root_cv = B::main_root;
380 $proc->{frame} = {
381 line => __LINE__ - 1,
382 file => __FILE__,
383 fn => 'DB::DB',
384 pkg => __PACKAGE__,
385 addr => $$root_cv,
386 };
387 $proc->{frame_index} = 0;
388 $proc->{stack_size} = 1,
389 $cmd->run([$NAME]);
390 print '-' x 30, "\n";
391 # $cmd->run([$NAME, '-l']);
392 # print '-' x 30, "\n";
393 $proc->{frame}{fn} = 'run';
394 $proc->{settings}{highlight} = 'dark';
395 $cmd->run([$NAME]);
396 }
397  
398 1;