blib/lib/Games/Hack/Live.pm untested

filter: Statementstmt 0.0% 0 / 482 Branchbran 0.0% 0 / 134 Conditioncond 0.0% 0 / 39 MC/DCmcdc 0.0% 0 / 23 Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 28 totaltotal 0.0% 0 / 737 CC 68 SCAR 39.3
CC
68
Cov
0%
KillWriteCallBack
132.0
String2Bin
132.0
PatchBin
110.0
CRAP 50.8
1 #!/usr/bin/perl
2 # vim: set sw=2 expandtab : #
3 # Master version is at https://developer.berlios.de/projects/games-hack/
4  
5  
6 package Games::Hack::Live;
7  
8 use Expect;
9 use Getopt::Std;
10  
11 require Exporter;
12 @ISA = qw(Exporter);
13 @EXPORT = qw(Run);
14  
15  
16 $VERSION=0.62;
17  
18  
19 # Client program name
20 our($prg,
21 # Client PID
22 $prg_pid,
23 # Timeout for GDB's answers
24 $TIMEOUT,
25 # The Expect object connected to GDB
26 $gdb,
27 # The STDIN Expect object
28 $input,
29 # Whether the program should currently be running
30 $should_be_running,
31 # Which extra strings we look for
32 $callbacks,
33 # Patch commands
34 @summary,
35 # Base path for file dumps
36 $dumppath,
37 # Dump start number
38 $dump,
39 # Patches to the program image
40 @patches,
41 # GDB Prompt variables
42 $gdb_prompt_base,
43 $gdb_prompt_count,
44 %cmd_opts);
45  
46  
47 sub Run
48 {
49 Inits();
50 StartDebuggee();
51 GDBStart();
52  
53  
54 # For debugging ...
55 #$gdb->log_file("/tmp/expect-log", "w");
56 #$gdb->debug(2);
57  
58  
59 $quit=0;
60 while (!$quit)
61 {
62 print "---> ";
63 (undef, $error) = expect( undef,
64 '-i', [ $input ],
65 [ qr/^\s*dumpall(?:\s+(.+))?/i, \&DumpAll, ],
66 [ qr/^\s*#/, sub { return 0; print "comment ignored\n"; 0; }, ],
67 [ qr/^\s*cleanup/i, \&CleanUp, ],
68 [ qr/^\s*help/i, \&Help, ],
69 [ qr/^\s*find\s+(.+)/i, \&Find, ],
70 [ qr/^\s*find/i, \&ShowMatches, ],
71 [ qr/^\s*patch\s+(\S+)/i, \&PatchBin, ],
72 [ qr/^\s*
73 keepvalueat \s+ # command name
74 (\S+) # address,
75 (?:\s+|\s*=\s*) # = or whitespace
76 (?: \( ([\w ]+) \) \s* )? # opt. type
77 (\S+) # value
78 (?:\s+["'](.+?)["'])?
79 /ix, \&KeepValueAt, ],
80 [ qr/^\s*
81 killwrites \s+
82 (\S+) # address
83 (?: \s+
84 (["'])(.+)\3 # opt. name
85 )?
86 (?: \s+
87 (ask) # opt. flag to ask for description
88 )?/ix, \&KillWrites, ],
89 [ qr/^\s*(.+?)\s*$/, \&PassThru, ],
90 [ 'eof', sub { $quit=1; 0; }, ],
91 '-i', [ $gdb ],
92 GDBmatches(1),
93 );
94 }
95  
96 print "\n\nQuitting ...\n";
97 $gdb->send("kill\n");
98 $gdb->send("q\n");
99 $gdb->hard_close();
100  
101 # Print results.
102 print @summary;
103 }
104  
105 ################################### The end.
106 ###################################****************************
107  
108  
109 ###################################****************************
110 ### ### ### ### ### ### ### ### ### Initialization functions
111  
112 # Set initial variables.
113 sub Inits
114 {
115 $input = Expect->init(\*STDIN);
116  
117 $SIG{"INT"} = sub {
118 $should_be_running=0;
119 DebuggeeBreak();
120 print "\nDebuggee stopped.\n";
121 };
122  
123 # Could we do the conversion using gdb?
124 # We can find out how many bytes that type has (print sizeof(...)),
125 # but how do we get the representation? (for searching)
126 %type_convs = (
127 "long" => [ "l", 0 ],
128  
129 "char" => [ "C", 0 ],
130 "unsigned char" => [ "C", 0 ],
131 "signed char" => [ "c", 0 ],
132  
133 "short" => [ "s", 0 ],
134 "signed short" => [ "s", 0 ],
135 "unsigned short" => [ "S", 0 ],
136  
137 "int" => [ "i", 0 ],
138  
139 "unsigned" => [ "I", 0 ],
140 "unsigned int" => [ "I", 0 ],
141 "unsigned long" => [ "L", 0 ],
142  
143 "long long" => [ "q", 0 ],
144 "unsigned long long" => [ "Q", 0 ],
145  
146 "float" => [ "f", 0.01 ],
147 "double" => [ "d", 0.01 ],
148 "long double" => [ "D", 0.01 ],
149 );
150  
151 $|=1;
152  
153 # Parse options
154 # Getopt::Std uses unqualified @ARGV, so that must be copied here.
155 @ARGV=@main::ARGV;
156 $Getopt::Std::STANDARD_HELP_VERSION=1;
157 $main::VERSION=$VERSION;
158 getopts("p:h", \%cmd_opts);
159  
160  
161 $TIMEOUT=15;
162 $should_be_running=0;
163 $callbacks=();
164 $dumppath="/tmp";
165 $dump=0;
166 $gdb_prompt_base="GDB-delim-$$-" . time;
167 $gdb_prompt_count="a000000";
168  
169  
170 chomp($machine=`uname -m`);
171 print "Loading patch library for $machine...\n";
172 $machine =~ s#\W#_#;
173  
174 eval "use Games::Hack::Patch::$machine;";
175 die $@ if $@;
176 }
177  
178  
179 # Start the program to-be-debugged
180 sub StartDebuggee
181 {
182 $prg_pid=$cmd_opts{"p"};
183 if ($prg_pid)
184 {
185 # program already started? find executable.
186 }
187 else
188 {
189 $prg=shift(@ARGV) || die "What should be debugged?\n";
190  
191 $prg_pid=fork();
192 die "fork(): $!\n" unless defined($prg_pid);
193  
194 if (!$prg_pid)
195 {
196 exec($prg);
197 die "exec($prg): $!\n";
198 }
199  
200 print "Started $prg as $prg_pid.\n";
201 # Wait for exec() to replace the binary.
202 for(0 .. 3)
203 {
204 select(undef,undef,undef, 0.2);
205 last if readlink("/proc/$prg_pid/exe") ne readlink("/proc/$$/exe");
206 }
207 }
208  
209 # The program may have been found via $PATH.
210 # For some things (like patching) we need the full path.
211 # TODO: works only on linux.
212 $prg=readlink("/proc/$prg_pid/exe") ||
213 die "Executable of pid $prg_pid not determined: $!\n" . `ls -la "/proc/$prg_pid" ; ps fax`;
214  
215 print "Using $prg with pid $prg_pid\n";
216 }
217  
218  
219 # Start gdb, and attach to debuggee
220 sub GDBStart
221 {
222 my($type);
223  
224 $gdb = new Expect;
225 $gdb->raw_pty(1);
226 $gdb->log_stdout(0);
227 $gdb->spawn("gdb 2>&1", ()) or die "Cannot spawn gdb: $!\n";
228  
229  
230 GDBSync($gdb);
231 GDBSend("set pagination off");
232 GDBSend("attach $prg_pid");
233  
234 CleanUp();
235  
236 # Determine machine word sizes
237 for $type (qw(short int long char), "long long")
238 {
239 print "print sizeof($type)\n";
240 GDBSend("print sizeof($type)", GDBmatches(0));
241 ($len) = ($gdb->before =~ m#\$\d+\s+=\s+(\d+)\s+#);
242 $type_has_length{$type}=$len;
243 $length_to_type[$len]=$type;
244 print "got $type as $len\n";
245 }
246  
247 # We need to be able to write single bytes; more would be better, but is
248 # not strictly necessary.
249 die "No type with length 1 found!\n"
250 unless $length_to_type[1];
251  
252 $should_be_running=1;
253 DebuggeeCont();
254 }
255  
256  
257 ###################################****************************
258 ### ### ### ### ### ### ### ### ### GDB I/O
259  
260 # Returns an array with currently allowed matches
261 # $cbs: include callbacks?
262 sub GDBmatches
263 {
264 my($cbs)=@_;
265 my(@a);
266  
267 @a=();
268 map { push @a, [ $_, @{$callbacks{$_}} ]; } keys %callbacks
269 if $cbs;
270  
271 push @a,
272 [ $gdb_prompt_delimiter, sub { $is_running=0; }, ],
273 [ "Continuing", sub { $is_running=1; }, ];
274 return @a;
275 }
276  
277  
278 # Change the GDB Prompt, and re-sync
279 # The debuggee must be stopped when calling that.
280 sub GDBSync
281 {
282 my($obj)=@_;
283  
284 $gdb_prompt_count++;
285 $gdb_prompt_delimiter = $gdb_prompt_base . "-" . $gdb_prompt_count . "-ZZ";
286 $obj->print_log_file("new prompt set to $gdb_prompt_delimiter\n");
287 $obj->send("set prompt $gdb_prompt_delimiter\\n\n");
288 # We allow *only* that single string, so that all previous data gets consumed.
289 $obj->expect($TIMEOUT, $gdb_prompt_delimiter);
290 }
291  
292  
293 # Look for the expected prompt, or other specified strings.
294 sub GDBPrompt
295 {
296 # $no_cbs??? TODO
297 my(@others)=@_;
298 my($obj);
299  
300 $obj=ref($others[0]) eq "Expect" ? shift(@others) : $gdb;
301 @others=GDBmatches(1) if !@others;
302 if (!$obj->expect($TIMEOUT, @others))
303 {
304 $obj->print_log_file(">>> NO MATCH ... expected $gdb_prompt_delimiter, Continuing, or @others\n");
305 $obj->print_log_file("got ", $obj->clear_accum());
306 die "No match\n";
307 }
308 }
309  
310  
311 # Send a command to GDB, and wait for answer.
312 sub GDBSend
313 {
314 my(@parm)=@_;
315 my($stg, @mat);
316 my($obj);
317  
318 $obj=ref($parm[0]) eq "Expect" ? shift(@parm) : $gdb;
319 ($stg, @mat)=@parm;
320 if ($stg)
321 {
322 $obj->print_log_file(">>> SENDING: $stg\n");
323 $obj->send($stg . "\n");
324 $obj->clear_accum();
325 }
326 GDBPrompt($obj, @mat);
327 $obj->print_log_file(">>> after sending: run=$is_running ",
328 "should=$should_be_running\n");
329 }
330  
331  
332 ###################################****************************
333 ### ### ### ### ### ### ### ### ### User commands
334  
335 # Unknown string - just pass to GDB
336 sub PassThru
337 {
338 my($self)=@_;
339 my($cmd);
340  
341  
342 $cmd=($self->matchlist())[0];
343 $should_be_running=1 if $cmd =~ m#^\s*c(o(nt?)?)?#i;
344  
345 $gdb->print_log_file(">>> passing '$cmd' $is_running $should_be_running");
346 return if ($should_be_running && $is_running);
347  
348 DebuggeeBreak($gdb);
349 GDBSync($gdb);
350 GDBSend($gdb, $cmd, GDBmatches(0));
351 print $gdb->before,"\n";
352 DebuggeeCont() if ($should_be_running);
353 0;
354 }
355  
356  
357 # show help
358 sub Help
359 {
360 local(*F);
361 my($t);
362  
363 # Sucks on debian, when the dummy perldoc is installed.
364 # Should we do open(F, "perldoc ... |") and count the lines?
365 if (system("perldoc Games::Hack::Live"))
366 {
367 # map { print $_, " ", $INC{$_},"\n" } keys %INC;
368 $t=$INC{"Games/Hack/Live.pm"};
369 if ($t && open(F, "< $t"))
370 {
371 $t=0;
372 while (<F>)
373 {
374 last if m#^=head1 DESCRIPTION#;
375  
376 $t += $t || m#^=head1 SYNOPSIS#;
377 print if $t>1;
378 }
379 close(F);
380 print "\nHTH.\n";
381 }
382 else
383 {
384 print "Sorry, cannot show any help. I can't even find myself.\n";
385 }
386 }
387 }
388  
389  
390 # Clean up search history
391 sub CleanUp
392 {
393 @findlist=();
394 %find_adr=();
395  
396 %callbacks=();
397  
398 DebuggeeBreak($gdb);
399 GDBSend($gdb, "delete", GDBmatches(0));
400 DebuggeeCont() if ($should_be_running);
401 }
402  
403  
404 sub PatchBin
405 {
406 my($self)=@_;
407 my($name);
408 my($base, $end, $ret);
409 local(*F);
410  
411 $name=($self->matchlist())[0];
412  
413 print "Patching $prg into $name\n";
414  
415 # find virtual start and end address
416 $base=0;
417  
418 DebuggeeBreak($gdb);
419 GDBSend($gdb, "info proc stat", GDBmatches(0));
420 $data=$gdb->before();
421 DebuggeeCont() if ($should_be_running);
422  
423 ($base) = ($data =~ /Start of text: (0x\w+)/m);
424 ($end) = ($data =~ /End of text: (0x\w+)/m);
425 print("Cannot get start address\n"), return unless $base;
426 print("Cannot get end address\n"), return unless $end;
427  
428 print " start is $base, end is $end\n";
429  
430 $base=oct($base) if $base =~ m#^0#;
431 $end=oct($end) if $end =~ m#^0#;
432  
433 unlink($name) || die "cannot remove $name: $!"
434 if (-e $name);
435  
436 # A fast copy, plus the small modifications, is likely faster than trying
437 # to copy here ...
438 print " copying.\n";
439 $ret=system('cp',$prg,$name);
440 print("copying failed with $?\n"),return if ($ret);
441  
442 # apply patches ...
443 print " patching:\n";
444 print("cannot open $name for patching: $!\n"),return
445 if (!open(F, "+< $name"));
446  
447 for $patch (@patches)
448 {
449 ($adr, $val)=@$patch;
450 if ($adr >= $base && $adr < $end)
451 {
452 printf " 0x%x (file offset %d): %s\n",
453 $adr, $adr-$base, unpack("H*", $val);
454 seek(F, $adr-$base, 0) || die "cannot seek on $name: $!\n";
455 print F $val;
456 }
457 else
458 {
459 # TODO: patch shared objects, too
460 printf "Warning: cannot patch address 0x%X - not in image.\n",
461 $adr;
462 }
463 }
464  
465 chmod 0755, *F;
466 close(F);
467 }
468  
469  
470 sub ShowMatches
471 {
472 my(@most);
473  
474 # Find best matches
475 @most=sort { $find_adr{$b} <=> $find_adr{$a}; } keys %find_adr;
476  
477 print "\nMost wanted:\n ";
478 map { printf "0x%08X(%d) ", $_,$find_adr{$_}; } splice(@most, 0, 5);
479 print "\n";
480 }
481  
482  
483 # Find some value in the program
484 sub Find
485 {
486 my($self)=@_;
487 my($parm);
488 my($ref, $bin, @most);
489  
490 $parm=($self->matchlist())[0];
491  
492 ($len, $re)=String2Bin($parm);
493  
494 DebuggeeBreak($gdb);
495  
496 # use a reference, so that the callback can give us data.
497 $ref=[];
498 push @findlist, [$parm, $len, $re, $ref];
499  
500 print "Searching for $re\n";
501 $gdb->print_log_file("Searching for ". unpack("H*", $bin)."\n");
502  
503 forEachRWMem(\&FindCallBack, $len, $re, $ref);
504  
505 # Count matches
506 map { $find_adr{$_}++; } @$ref;
507  
508 ShowMatches();
509  
510 DebuggeeCont() if ($should_be_running);
511 }
512  
513  
514 # Register a watchpoint for the memory location, and when it's triggered
515 # kill the write command.
516 sub KillWrites
517 {
518 my($self)=@_;
519 my($adr, $name, $always_ask, @opt);
520  
521 $adr=oct(($self->matchlist())[0]);
522 $name=($self->matchlist())[2];
523  
524 $always_ask=0;
525 # "3 .. " as index doesn't work, splice doesn't take a subroutine call..
526 @opt=$self->matchlist();
527 splice(@opt, 0, 3);
528 for (grep(/\w/,@opt))
529 {
530 if ($_ eq "ask") { $always_ask=1; }
531 else {
532 print "Unknown option '$_'\n";
533 return;
534 }
535 }
536  
537 DebuggeeBreak();
538 GDBSend("watch *(int*)$adr", GDBmatches(0));
539 $gdb->before =~ m#(watchpoint \d+:)#i || die;
540 if (!$1)
541 {
542 print "Watchpoint could not be set:\n",$gdb->before,"\n";
543 return;
544 }
545  
546 print "Using ", $1," killing writes to $adr.\n";
547  
548 $gdb->print_log_file("Registering callback for '$1':");
549 $callbacks{$1}= [ \&KillWriteCallBack,
550 $adr, $name,
551 { "ask" => $always_ask, }, ];
552 DebuggeeCont() if ($should_be_running);
553 }
554  
555  
556 # Register a watchpoint for the memory location, and tell GDB to change the
557 # value back.
558 sub KeepValueAt
559 {
560 my($self)=@_;
561 my($adr,$val,$type,$name);
562 my($l1, $l2, $l3);
563  
564 ($adr, $type, $val, $name)=$self->matchlist();
565  
566
567 $type ||= AutoType($val);
568 ValType_to_BinCharHexTypedef($val, $type);
569  
570 DebuggeeBreak();
571 $l1="set *($type*)$adr=$val";
572 $l2="watch *($type*)$adr";
573 $l3=["commands",
574 "silent",
575 $l1,
576 "c",
577 "end"];
578 GDBSend($l1, GDBmatches(0));
579 GDBSend($l2, GDBmatches(0));
580 $gdb->before =~ m#(watchpoint \d+:)#i;
581 if (!$1)
582 {
583 print "Watchpoint could not be set:\n",$gdb->before,"\n";
584 return;
585 }
586  
587 print "Using ", $1," keeping value at $adr ($type) at $val.\n";
588  
589 $gdb->print_log_file("Registering actions for $name '$1':");
590 GDBSend(join("\n",@$l3), GDBmatches(0));
591 $gdb->print_log_file("Keeping $adr at $val -- $name\n");
592  
593 push @summary,
594 sprintf("# keeping \"%s\" (0x%x) at 0x%x (%d):\n\t%s\n\n",
595 $name, $adr, $val, $val, join("\n\t", $l1, $l2, @$l3));
596  
597 DebuggeeCont() if ($should_be_running);
598 }
599  
600  
601 # Dump each writeable memory area to a distinct file.
602 sub DumpAll
603 {
604 my($self)=@_;
605 my($dir, $desc, $c);
606  
607 $desc=($self->matchlist())[0];
608  
609 $dir=sprintf("%s/%d-%04d-%s", $dumppath, $prg_pid, $dump, $desc);
610 mkdir($dir) || die $!;
611 $dump++;
612 print "dumping into $dir...\n";
613  
614 $c=forEachRWMem(\&SaveMem, $dir);
615 print "Dumped $c mappings.\n";
616 0;
617 }
618  
619  
620 ###################################****************************
621 ### ### ### ### ### ### ### ### ### Break/Continue Debuggee
622  
623 sub DebuggeeCont
624 {
625 my($obj)=@_;
626 return if ($is_running);
627  
628 $obj=$gdb unless $obj;
629  
630 $obj->print_log_file("continuing: is_running=$is_running\n");
631 $obj->print_log_file(">>> continuing\n");
632 GDBSend($obj, "c", GDBmatches(0));
633 }
634  
635  
636 sub DebuggeeBreak
637 {
638 my($obj)=@_;
639 my(@a, $i);
640  
641 $obj=$gdb unless $obj;
642  
643 $obj->print_log_file("Try to stop: is_running=$is_running\n");
644 return if (!$is_running);
645  
646 $i=1;
647 $obj->print_log_file(">>> callstack($i): ", join("; ", @a), "\n"), $i++
648 while (@a = caller($i));
649  
650 $obj->print_log_file(">>> Stopping program via signal\n");
651 kill "INT", $prg_pid;
652 $obj->clear_accum();
653 $is_running=0;
654 select(undef, undef, undef, 0.01);
655 # GDBSend(undef, "Program received signal");
656 GDBSync($obj);
657 print $obj->clear_accum();
658 $obj->print_log_file("Should be stopped: is_running=$is_running\n");
659 }
660  
661  
662 ###################################****************************
663 ### ### ### ### ### ### ### ### ### Utility Functions
664  
665 # Write some memory block to a file.
666 sub SaveMemtoFile
667 {
668 my($start, $end, $name)=@_;
669  
670 $gdb->print_log_file(
671 sprintf(">>> dumping 0x%08x to 0x%08x into %s\n",
672 $start, $end, $name));
673 GDBSend("dump binary memory $name $start $end", GDBmatches(0));
674 }
675  
676  
677 # Wrapper function.
678 sub SaveMem
679 {
680 my($start, $end, $dir)=@_;
681  
682 SaveMemtoFile($start, $end,
683 sprintf("%s/0x%8X-0x%8X", $dir, $start, $end));
684 }
685  
686  
687 # Returns GDB commands that writes the bytes of $bin at $adr
688 sub GetGDBWriteCommands
689 {
690 my($adr, $bin)=@_;
691 my($tmp, $stg, $len, $ctype);
692  
693 $stg="";
694  
695  
696 while ( ($len=length($bin)) )
697 {
698 # Search for a type of the same or smaller length
699 $len-- while !($ctype=$length_to_type[$len]);
700  
701 $tmp=substr($bin, 0, $len);
702 substr($bin, 0, $len)="";
703  
704 # It doesn't matter that the byte order is host-specific ...
705 # the binaries are too, after all.
706 $stg .= sprintf("set *(%s*)0x%x=0x%x",
707 $ctype, $adr,
708 unpack($type_convs{$ctype}[0], $tmp));
709  
710 $adr += $len;
711 }
712  
713 return $stg;
714 }
715  
716  
717 # Worker function for KillWrites
718 sub KillWriteCallBack
719 {
720 my($exp, $data_adr, $name, $opt)=@_;
721 my($adr, $p1, $p2, $l, $cmd);
722 my($killer);
723  
724 # When we get here, the program has already stopped.
725 $is_running=0;
726  
727 ($old) = $exp->after() =~ m#Old value = (\d+)#;
728  
729 $exp->clear_accum();
730 $exp->print_log_file("### Got callback!\n");
731 DebuggeeBreak($exp);
732 # resync
733 GDBSync($exp);
734  
735 $exp->print_log_file("Got old value as $old\n");
736 GDBSend($exp, "set *(int*)$data_adr=$old", GDBmatches(0))
737 if ($old);
738  
739 GDBSend($exp, "info program", GDBmatches(0));
740 $quit=1,return
741 if ($exp->before =~
742 m#program being debugged is not being run.#i);
743  
744 $exp->before =~ m#Program stopped at ((0x)?[0-9a-f]+)#i;
745 $adr=oct($1);
746 $exp->print_log_file("### Program at $adr!\n");
747 GDBSync($exp);
748  
749 # We need the instruction immediately before, as on Intel EIP is already
750 # changed.
751 # Is there some more reliable way to get it? There may be aliasing issues ..
752 # Are there longer sequences than 16 Bytes?
753 # As a watchpoint works with memory, there must be a memory operand to this
754 # instruction, so there should be *at least* 2 bytes.
755 # Less wouldn't work with the relative jump anyway - we'd need to put NOPs.
756 $p1=0;
757 for $aliasing (2 .. 16)
758 {
759 # We start with some offset before, to let the disassembler synchronize.
760 $startadr=$adr-$aliasing-32;
761 GDBSend($exp, "disassemble $startadr, " . ($adr+1), GDBmatches(0));
762  
763 my $x = $exp->before;
764 $x =~ s/\n=> /\n /;
765  
766 # GDB prints the EIP without leading zeroes (info program), but the
767 # diassembly has it. Don't know now how it's printed on 64bit.
768 # We fetch an array, and the interesting parts should be the last two ...
769 # 0x00007fe627b742f3 <__mpn_submul_1+227>: mov %ebx,%eax
770 @found = ($x =~ m/\n\s*(0x\w+)\s+\<\S+\>:\s+(.*)/mg);
771  
772 unless (@found) {
773 # 0x0000000000414b13: sub 0x18(%rcx,%rdx,1),%eax
774 @found = ($x =~ m/\n\s*(0x\w+):\s+(\w.*)/mg);
775 }
776  
777 # print "??? @found \n";
778  
779 # Look whether we had the correct address at the end (instruction aliasing
780 # might prevent this)
781 $p1=oct($found[-4]), $cmd = $found[-3] if (oct($found[-2]) == $adr);
782  
783 # Length of instruction
784 $l=$adr - $p1;
785 $exp->print_log_file("### (aliasing $aliasing) $cmd: $p1-$adr=$l\n");
786 last if ($p1);
787 }
788  
789 die "cannot match opcode addresses for " . $exp->before unless $p1;
790  
791 $binary=GetNOP($p1, $adr, $cmd);
792 die "Patch is longer than instruction!\n"
793 if $l < length($binary);
794  
795 # Look how many bytes we need to write.
796 $killer = GetGDBWriteCommands($p1, $binary);
797  
798 push @patches, [ $p1, $binary ];
799  
800 GDBSend($exp, $killer, GDBmatches(0));
801  
802 # Remove tabs and similar
803 $cmd =~ s/\s+/ /g;
804  
805 printf "\nKilled a write to 0x%X (%s): %s\n\tpatched with %s\n",
806 $adr, $name, $cmd, unpack("H*", $binary);
807  
808 $desc="";
809 if ($opt->{"ask"})
810 {
811 print "Please enter a description of this event:\n";
812 $desc=<STDIN>;
813 $desc =~ s/^\s+//;
814 $desc =~ s/\s+$//;
815 }
816  
817 push @summary,
818 sprintf('# stopped at 0x%x for "%s" (at 0x%x); killing command "%s" ' .
819 "via\n\t%s\n\n",
820 $adr,
821 $name . ($desc ? " [" . $desc . "]" : ""),
822 $data_adr, $cmd, $killer);
823  
824 DebuggeeCont() if ($should_be_running);
825  
826 0;
827 # display prompt again.
828 # exp_continue;
829 }
830  
831  
832 # Main worker function for Find
833 sub FindCallBack
834 {
835 my($start, $end, $blen, $re, $foundref)=@_;
836 my($size, $buff, $offset, $l, $pos, $np, $adr);
837 my($tmp)="/tmp/xxx.$$." . rand();
838 my($count, $tmpc);
839  
840 SaveMemtoFile($start, $end, $tmp);
841  
842 # We read the (arbitrarily large) memory blobs in pieces, and keep
843 # the last few bytes from the previous round - in case the match would span
844 # two such blocks.
845  
846 # Size of each block
847 $size=128 * 1024;
848 $buff="";
849 $offset=0;
850 open(TMP, "< $tmp") || die "read $tmp: $!";
851 while (1)
852 {
853 $l=sysread(TMP, $buff, $size, length($buff));
854 $gdb->print_log_file(
855 sprintf("searching for %s at 0x%x (%d) + 0x%x (%d)\n",
856 unpack("H*", $bin),
857 $start, $start, $offset, $offset));
858 die $! unless defined($l);
859 last if !$l;
860  
861 $pos=0;
862 while ( $buff =~ m#$re#g )
863 {
864 $np=$-[0];
865 $adr=$start+$offset+$np;
866  
867 # Should we still print addresses?
868 $tmpc=($count++) -5;
869 printf " found at 0x%08x (0x%08x + 0x%x): %s\n",
870 $adr, $start, $np+$offset,
871 unpack("H*", substr($buff, $np, 8)),
872 if ($tmpc <0);
873  
874 # Should we print "more here..."?
875 printf " ...\n", $adr
876 if ($tmpc ==0);
877  
878 push @$foundref, $adr;
879 }
880  
881 # We advance the offset ...
882 $offset+=length($buff);
883 # and take only as much from the end as necessary for further matches
884 $buff=substr($buff, -$blen);
885 # but that many characters were kept.
886 $offset-=length($buff);
887 }
888 close(TMP);
889 unlink $tmp;
890 }
891  
892  
893 # For each writeable memory, do ...
894 sub forEachRWMem
895 {
896 my($func, @parm)=@_;
897 local(*MAP);
898 my($start, $end, $count);
899  
900 DebuggeeBreak();
901 # read writeable mappings
902 open(MAP, "/proc/$prg_pid/maps") || die $!;
903 $count=0;
904 while (<MAP>)
905 {
906 ($start,$end) = m#^(\w+)-(\w+) rw.. #;
907 # virtual address 0 would be invalid anyway
908 next unless $start;
909  
910 &$func(oct("0x$start"), oct("0x$end"), @parm);
911 $count++;
912 }
913  
914 DebuggeeCont() if ($should_be_running);
915  
916 close MAP;
917 return $count;
918 }
919  
920  
921 ###################################****************************
922 ### ### ### ### ### ### ### ### ### Conversion Functions
923  
924  
925 # Returns a default type for this string
926 sub AutoType
927 {
928 my($val1, $val2)=@_;
929  
930 return (length($val2) == 0 &&
931 $val1 =~ /^(\d+|0x[0-9a-f])$/i)
932 ? "int" : "float";
933 }
934  
935  
936 sub ValType_to_BinCharHexTypedef
937 {
938 my($value, $type)=@_;
939 my($stg, $char, @chars, @hex);
940  
941 return undef if !$type_convs{$type};
942  
943 ($char)=@{$type_convs{$type}};
944  
945 $stg=pack($char, $value);
946 @chars=unpack("C*", $stg);
947 @hex=map { sprintf("\\x%02X", $_); } @chars;
948  
949 return
950 (
951 $stg, [ @chars ], [ @hex ],
952 @{$type_convs{$type}}
953 );
954 }
955  
956 # Returns a regex describing the data the user wants to find.
957 # Format see in documentation.
958 # Returns undef for invalid input; else
959 # ( $number_of_bytes, $regular_expression ).
960 sub String2Bin
961 {
962 my($stg)=@_;
963  
964 if ($stg =~ m/^\s*(["'])(.*?)\1?$/)
965 {
966 my($srch, $len);
967  
968 $srch=$2;
969 $len=length($srch);
970  
971 # escape special characters
972 $srch =~ s#(\W)#\\\1#g;
973  
974 return ($len, "(?-xism:$srch)" );
975 }
976  
977 # it might be nice to search for a regular expression ... but then we
978 # wouldn't know how many bytes to advance. simply go for 16 bytes?
979  
980  
981 my($type, $val1, $val2) = ($stg =~
982 m/^
983 (?: \( ([a-z ]+ ) \) )? # optional type, in ( )
984 \s*
985 (\S+) # number 1
986 (?: # optional 2nd number
987 (?: \s*\.\.\s* | \s*-\s* | \s+ ) # delimiter
988 (\S+) # number 2
989 )?
990 $/xi);
991  
992 # auto-type
993 $type ||= AutoType($val1, $val2);
994  
995 my $chars, $hex;
996 my $stg1, $range;
997  
998 ($stg1, $chars, $hex, $char, $range) =
999 ValType_to_BinCharHexTypedef($val1, $type);
1000  
1001 return undef unless $stg1;
1002  
1003 # Only a single value given?
1004 if (!$range)
1005 {
1006 return (
1007 length($stg1),
1008 join("", "(?-xism:", @$hex, ")" )
1009 );
1010 }
1011  
1012 # floating point type.
1013 # We do a fuzzy match, eg. for floating point values
1014 # Eg. if only a few digits are shown.
1015 if (length($val2) == 0)
1016 {
1017 my $o=$val1;
1018 my $m=$val1;
1019  
1020 $val2=$m*(1+$range);
1021 $val1=$m*(1-$range);
1022  
1023 # See documentation on find - take bigger range
1024 $m=int($o-1.0)+0.5;
1025 $val1=$m if ($m<$val1);
1026  
1027 $m=int($o+1);
1028 $val2=$m if ($m>$val2);
1029  
1030 print "Searching for the range [$val1 .. $val2]\n";
1031 }
1032  
1033 $val1 += 0;
1034 $val2 += 0;
1035  
1036 ($val1,$val2) = ($val2, $val1) if abs($val2) < abs($val1);
1037  
1038 my $stg1;
1039 # pack again, because the order could have changed.
1040 # TODO: use ValType_to_BinCharHexTypedef()
1041 $stg1=pack($char, $val1);
1042 $stg2=pack($char, $val2);
1043  
1044 # TODO machine-dependent - the IEEE formats are MSB
1045 # (exponent at higher addresses) (?)
1046  
1047 # Change all bytes left of different bytes.
1048  
1049 # convert to bit vector
1050 vec($stg1, 1, 2);
1051 print "1=", unpack("H*", $stg1), " ",
1052 "2=", unpack("H*", $stg2), "\n";
1053  
1054
1055 $xor= $stg1 ^ $stg2;
1056 $xor =~ m/(\0+)$/;
1057 $common_bytes=length( $1 );
1058 # TODO
1059 die "strings completely different" if $common_bytes==0;
1060  
1061 $to_chop=@$chars - $common_bytes;
1062 if ($to_chop>0)
1063 {
1064 # first different byte gets changed to range, rest ignored.
1065 # We have to re-calculate the characters, because we might have done
1066 # +-1% off the original value.
1067 splice(@$chars, 0, $to_chop);
1068 @hex=();
1069 if ($to_chop>1)
1070 {
1071 push @hex, sprintf("[\\x%02x-\\x%02x]",
1072 unpack("C*", substr($stg1, $to_chop-1, 1)),
1073 unpack("C*", substr($stg2, $to_chop-1, 1))
1074 );
1075 $to_chop--;
1076 }
1077  
1078 push @hex, map { sprintf("\\x%02X", $_); } @$chars;
1079 }
1080  
1081 # "." is not *any* character, sadly.
1082 # So we use "\C".
1083 return (
1084 length($stg1),
1085 join("", "(?-xism:", ("\\C" x $to_chop), @hex, ")" )
1086 );
1087 }
1088  
1089  
1090 ##### Success!
1091 1;
1092  
1093 ###################################****************************
1094 ### ### ### ### ### ### ### ### ###
1095 ### ### ### ### ### ### ### ### ### Really the end.
1096 ### ### ### ### ### ### ### ### ### Only documentation left.
1097 ### ### ### ### ### ### ### ### ###
1098 ###################################****************************
1099  
1100 __END__