
gnix
Novice
Feb 19, 2009, 3:02 AM
Post #5 of 5
(3215 views)
|
Re: [lisa sangu] Edit C program using perl - help needed
[In reply to]
|
Can't Post
|
|
Hi, I changed some lines of my previous solution to your problem.
#!/usr/bin/perl -w # Check @ARGV if(@ARGV != 1) { print "[!] Usage: perl script.pl <file.c>\n"; exit(-1); } # Open files open(OLDFILE, "<$ARGV[0]") || die "[!] Cannot open $ARGV[0]!\n"; open(NEWFILE, ">new_$ARGV[0]") || die "[!] Cannot open new_$ARGV[0]!\n"; # Read file content @lines = <OLDFILE>; print "$ARGV[0]\n\n"; # Parse each line for($i=0; $i < @lines; $i++) { if($lines[$i] =~ m/(\w+)\s+<<=\s+(\w+)/) { ($var1, $var2) = ($1, $2); print "[+] line ". ($i + 1) .": Found var1=$var1 and var2=$var2\n"; $type1 = findType($var1, $i); if(!$type1) { print "[+] line ". ($i + 1) .": Type for $var1 not found!\n\n"; exit(-1); } else { print "[+] line ". ($i + 1) .": Type found: $type1\n\n"; } $lines[$i] =~ s/$var1\s+<<=\s+$var2\s*;/$var1 = ($type1)((unsigned $type1)$var1 << $var2);/g; } print NEWFILE $lines[$i]; } # Close files close(OLDFILE); close(NEWFILE); exit(0); # This function try to find the declaration reading the lines before. sub findType { my $var = shift; my $i = shift; for(; $i >= 0; $i--) { return $1 if ($lines[$i] =~ m/(char|int|long|float|double)\s+$var[^\(]/); } return undef; } The code seems to work correctly, but is not a generic solution. At the moment, this code try to find a declaration (e.g. "int a;" or "int b=0;") reading the lines before the "var1 <<= var2" line. To do that, it uses the following regex:
m/(char|int|long|float|double)\s+$var[^\(]/ this regex can find only the types specified and is not capable to understand if the declaration is contained in a struct or in a string. In any case, I hope you can solve your problem with the help of this code. gnix ps: Sorry for my English.
|