]> git.xonotic.org Git - xonotic/xonotic.git/blob - misc/tools/progs-analyzer.pl
fix two typos
[xonotic/xonotic.git] / misc / tools / progs-analyzer.pl
1 use strict;
2 use warnings;
3 use Digest::SHA;
4
5 sub id()
6 {
7         return sub { $_[0]; };
8 }
9
10 sub signed($)
11 {
12         my ($bits) = @_;
13         return sub { $_[0] >= (2**($bits-1)) ? $_[0]-(2**$bits) : $_[0]; };
14 }
15
16 use constant OPCODE_E => [qw[
17         DONE
18         MUL_F MUL_V MUL_FV MUL_VF
19         DIV_F
20         ADD_F ADD_V
21         SUB_F SUB_V
22         EQ_F EQ_V EQ_S EQ_E EQ_FNC
23         NE_F NE_V NE_S NE_E NE_FNC
24         LE GE LT GT
25         LOAD_F LOAD_V LOAD_S LOAD_ENT LOAD_FLD LOAD_FNC
26         ADDRESS
27         STORE_F STORE_V STORE_S STORE_ENT STORE_FLD STORE_FNC
28         STOREP_F STOREP_V STOREP_S STOREP_ENT STOREP_FLD STOREP_FNC
29         RETURN
30         NOT_F NOT_V NOT_S NOT_ENT NOT_FNC
31         IF IFNOT
32         CALL0 CALL1 CALL2 CALL3 CALL4 CALL5 CALL6 CALL7 CALL8
33         STATE
34         GOTO
35         AND OR
36         BITAND BITOR
37 ]];
38 use constant ETYPE_E => [qw[
39         void
40         string
41         float
42         vector
43         entity
44         field
45         function
46         pointer
47 ]];
48 use constant DEF_SAVEGLOBAL => 32768;
49 sub typesize($)
50 {
51         my ($type) = @_;
52         return 3 if $type eq 'vector';
53         return 1;
54 }
55
56 sub checkop($)
57 {
58         my ($op) = @_;
59         if($op =~ /^IF.*_V$/)
60         {
61                 return { a => 'inglobalvec', b => 'ipoffset', isjump => 'b', isconditional => 1 };
62         }
63         if($op =~ /^IF/)
64         {
65                 return { a => 'inglobal', b => 'ipoffset', isjump => 'b', isconditional => 1 };
66         }
67         if($op eq 'GOTO')
68         {
69                 return { a => 'ipoffset', isjump => 'a', isconditional => 0 };
70         }
71         if($op =~ /^ADD_V$|^SUB_V$/)
72         {
73                 return { a => 'inglobalvec', b => 'inglobalvec', c => 'outglobalvec' };
74         }
75         if($op =~ /^MUL_V$|^EQ_V$|^NE_V$/)
76         {
77                 return { a => 'inglobalvec', b => 'inglobalvec', c => 'outglobal' };
78         }
79         if($op eq 'MUL_FV')
80         {
81                 return { a => 'inglobal', b => 'inglobalvec', c => 'outglobalvec' };
82         }
83         if($op eq 'MUL_VF')
84         {
85                 return { a => 'inglobalvec', b => 'inglobal', c => 'outglobalvec' };
86         }
87         if($op eq 'LOAD_V')
88         {
89                 return { a => 'inglobal', b => 'inglobal', c => 'outglobalvec' };
90         }
91         if($op =~ /^NOT_V/)
92         {
93                 return { a => 'inglobalvec', c => 'outglobal' };
94         }
95         if($op =~ /^NOT_/)
96         {
97                 return { a => 'inglobal', c => 'outglobal' };
98         }
99         if($op eq 'STOREP_V')
100         {
101                 return { a => 'inglobalvec', b => 'inglobal' };
102         }
103         if($op eq 'STORE_V')
104         {
105                 return { a => 'inglobalvec', b => 'outglobalvec' };
106         }
107         if($op =~ /^STOREP_/)
108         {
109                 return { a => 'inglobal', b => 'inglobal' };
110         }
111         if($op =~ /^STORE_/)
112         {
113                 return { a => 'inglobal', b => 'outglobal' };
114         }
115         if($op =~ /^CALL/)
116         {
117                 return { a => 'inglobalfunc', iscall => 1 };
118         }
119         if($op =~ /^DONE$|^RETURN$/)
120         {
121                 return { a => 'inglobalvec', isreturn => 1 };
122         }
123         return { a => 'inglobal', b => 'inglobal', c => 'outglobal' };
124 }
125
126 use constant TYPES => {
127         int => ['V', 4, signed 32],
128         ushort => ['v', 2, id],
129         short => ['v', 2, signed 16],
130         opcode => ['v', 2, sub { OPCODE_E->[$_[0]] or do { warn "Invalid opcode: $_[0]"; "INVALID#$_[0]"; }; }],
131         float => ['f', 4, id],
132         uchar8 => ['a8', 8, sub { [unpack 'C8', $_[0]] }],
133         global => ['i', 4, sub { { int => $_[0], float => unpack "f", pack "L", $_[0] }; }],
134         deftype => ['v', 2, sub { { type => ETYPE_E->[$_[0] & ~DEF_SAVEGLOBAL], save => !!($_[0] & DEF_SAVEGLOBAL) }; }],
135 };
136
137 use constant DPROGRAMS_T => [
138         [int => 'version'],
139         [int => 'crc'],
140         [int => 'ofs_statements'],
141         [int => 'numstatements'],
142         [int => 'ofs_globaldefs'],
143         [int => 'numglobaldefs'],
144         [int => 'ofs_fielddefs'],
145         [int => 'numfielddefs'],
146         [int => 'ofs_functions'],
147         [int => 'numfunctions'],
148         [int => 'ofs_strings'],
149         [int => 'numstrings'],
150         [int => 'ofs_globals'],
151         [int => 'numglobals'],
152         [int => 'entityfields']
153 ];
154
155 use constant DSTATEMENT_T => [
156         [opcode => 'op'],
157         [short => 'a'],
158         [short => 'b'],
159         [short => 'c']
160 ];
161
162 use constant DDEF_T => [
163         [deftype => 'type'],
164         [ushort => 'ofs'],
165         [int => 's_name']
166 ];
167
168 use constant DGLOBAL_T => [
169         [global => 'v'],
170 ];
171
172 use constant DFUNCTION_T => [
173         [int => 'first_statement'],
174         [int => 'parm_start'],
175         [int => 'locals'],
176         [int => 'profile'],
177         [int => 's_name'],
178         [int => 's_file'],
179         [int => 'numparms'],
180         [uchar8 => 'parm_size'],
181 ];
182
183 sub get_section($$$)
184 {
185         my ($fh, $start, $len) = @_;
186         seek $fh, $start, 0
187                 or die "seek: $!";
188         $len == read $fh, my $buf, $len
189                 or die "short read";
190         return $buf;
191 }
192
193 sub parse_section($$$$$)
194 {
195         my ($fh, $struct, $start, $len, $cnt) = @_;
196
197         my $itemlen = 0;
198         $itemlen += TYPES->{$_->[0]}->[1]
199                 for @$struct;
200         my $packspec = join '', map { TYPES->{$_->[0]}->[0]; } @$struct;
201         my @packnames = map { $_->[1]; } @$struct;
202
203         $len = $cnt * $itemlen
204                 if not defined $len and defined $cnt;
205         $cnt = int($len / $itemlen)
206                 if not defined $cnt and defined $len;
207         die "Invalid length specification"
208                 unless defined $len and defined $cnt and $len == $cnt * $itemlen;
209         die "Invalid length specification in scalar context"
210                 unless wantarray or $cnt == 1;
211
212         seek $fh, $start, 0
213                 or die "seek: $!";
214         my @out = map
215         {
216                 $itemlen == read $fh, my $buf, $itemlen
217                         or die "short read";
218                 my %h = ();
219                 @h{@packnames} = unpack $packspec, $buf;
220                 $h{$_->[1]} = TYPES->{$_->[0]}->[2]->($h{$_->[1]})
221                         for @$struct;
222                 \%h;
223         }
224         0..($cnt-1);
225         return @out
226                 if wantarray;
227         return $out[0];
228 }
229
230 sub nfa_default_state_checker()
231 {
232         my %seen;
233         return sub
234         {
235                 my ($ip, $state) = @_;
236                 return $seen{"$ip $state"}++;
237         };
238 }
239
240 sub run_nfa($$$$$$)
241 {
242         my ($progs, $ip, $state, $copy_handler, $state_checker, $instruction_handler) = @_;
243
244         my $statements = $progs->{statements};
245
246         my $nfa;
247         $nfa = sub
248         {
249                 no warnings 'recursion';
250
251                 my ($ip, $state) = @_;
252                 my $ret = 0;
253
254                 for(;;)
255                 {
256                         return $ret
257                                 if $state_checker->($ip, $state);
258
259                         my $s = $statements->[$ip];
260                         my $c = checkop $s->{op};
261
262                         if(($ret = $instruction_handler->($ip, $state, $s, $c)))
263                         {
264                                 # abort execution
265                                 last;
266                         }
267
268                         if($c->{isreturn})
269                         {
270                                 last;
271                         }
272                         elsif($c->{iscall})
273                         {
274                                 my $func = $s->{a};
275                                 my $funcid = $progs->{globals}[$func]{v}{int};
276                                 my $funcobj = $progs->{functions}[$funcid];
277                                 if($funcobj && $funcobj->{first_statement} < 0) # builtin
278                                 {
279                                         my $def = $progs->{globaldef_byoffset}->($func);
280                                         last
281                                                 if $def->{debugname} eq '_error';
282                                 }
283                                 $ip += 1;
284                         }
285                         elsif($c->{isjump})
286                         {
287                                 if($c->{isconditional})
288                                 {
289                                         if(rand 2)
290                                         {
291                                                 if(($ret = $nfa->($ip+$s->{$c->{isjump}}, $copy_handler->($state))) < 0)
292                                                 {
293                                                         last;
294                                                 }
295                                                 $ip += 1;
296                                         }
297                                         else
298                                         {
299                                                 $nfa->($ip+1, $copy_handler->($state));
300                                                 $ip += $s->{$c->{isjump}};
301                                         }
302                                 }
303                                 else
304                                 {
305                                         $ip += $s->{$c->{isjump}};
306                                 }
307                         }
308                         else
309                         {
310                                 $ip += 1;
311                         }
312                 }
313
314                 return $ret;
315         };
316
317         $nfa->($ip, $copy_handler->($state));
318 }
319
320 sub get_constant($$)
321 {
322         my ($progs, $g) = @_;
323         if($g->{int} == 0)
324         {
325                 return undef;
326         }
327         elsif($g->{int} > 0 && $g->{int} < 16777216)
328         {
329                 if($g->{int} < length $progs->{strings} && $g->{int} > 0)
330                 {
331                         return str($progs->{getstring}->($g->{int}));
332                 }
333                 else
334                 {
335                         return $g->{int} . "i";
336                 }
337         }
338         else
339         {
340                 return $g->{float};
341         }
342 }
343
344 use constant PRE_MARK_STATEMENT => "";
345 use constant POST_MARK_STATEMENT => "";
346 use constant PRE_MARK_OPERAND => "*** ";
347 use constant POST_MARK_OPERAND => " ***";
348
349 use constant INSTRUCTION_FORMAT => "%8s %3s | %-12s ";
350 use constant OPERAND_FORMAT => "%s";
351 use constant OPERAND_SEPARATOR => ", ";
352 use constant INSTRUCTION_SEPARATOR => "\n";
353
354 sub str($)
355 {
356         my ($str) = @_;
357         $str =~ s/[\000-\037\\\"\177-\377]/sprintf "\\%03o", ord $&/ge;
358         return "\"$str\"";
359 }
360
361 sub disassemble_function($$;$)
362 {
363         my ($progs, $func, $highlight) = @_;
364
365         print "$func->{debugname}:\n";
366
367         my $initializer = sub
368         {
369                 my ($ofs) = @_;
370                 my $g = get_constant($progs, $progs->{globals}[$ofs]{v});
371                 print " = $g"
372                         if defined $g;
373         };
374
375         printf INSTRUCTION_FORMAT, '', '', '.PARM_START';
376         printf OPERAND_FORMAT, "$func->{parm_start}";
377         print INSTRUCTION_SEPARATOR;
378
379         printf INSTRUCTION_FORMAT, '', '', '.LOCALS';
380         printf OPERAND_FORMAT, "$func->{locals}";
381         print INSTRUCTION_SEPARATOR;
382
383         my %override_locals = ();
384         my $p = $func->{parm_start};
385         for(0..($func->{numparms}-1))
386         {
387                 $override_locals{$p} //= "argv_$_";
388                 for my $comp(0..($func->{parm_size}[$_]-1))
389                 {
390                         $override_locals{$p} //= "argv_$_\[$comp]";
391                         ++$p;
392                 }
393                 printf INSTRUCTION_FORMAT, '', '', '.ARG';
394                 printf OPERAND_FORMAT, "argv_$_";
395                 print OPERAND_SEPARATOR;
396                 printf OPERAND_FORMAT, $func->{parm_size}[$_];
397                 print INSTRUCTION_SEPARATOR;
398         }
399         for($func->{parm_start}..($func->{parm_start} + $func->{locals} - 1))
400         {
401                 next
402                         if exists $override_locals{$_};
403                 $override_locals{$_} = "local_$_";
404
405                 printf INSTRUCTION_FORMAT, '', '', '.LOCAL';
406                 printf OPERAND_FORMAT, "local_$_";
407                 $initializer->($_);
408                 print INSTRUCTION_SEPARATOR;
409         }
410
411         my $getname = sub
412         {
413                 my ($ofs) = @_;
414                 $ofs &= 0xFFFF;
415                 return $override_locals{$ofs}
416                         if exists $override_locals{$ofs};
417                 my $def = $progs->{globaldef_byoffset}->($ofs);
418                 return $def->{debugname};
419         };
420
421         my $operand = sub
422         {
423                 my ($ip, $type, $operand) = @_;
424                 if($type eq 'inglobal')
425                 {
426                         my $name = $getname->($operand);
427                         printf OPERAND_FORMAT, "$name";
428                 }
429                 elsif($type eq 'outglobal')
430                 {
431                         my $name = $getname->($operand);
432                         printf OPERAND_FORMAT, "&$name";
433                 }
434                 elsif($type eq 'inglobalvec')
435                 {
436                         my $name = $getname->($operand);
437                         printf OPERAND_FORMAT, "$name\[\]";
438                 }
439                 elsif($type eq 'outglobalvec')
440                 {
441                         my $name = $getname->($operand);
442                         printf OPERAND_FORMAT, "&$name\[\]";
443                 }
444                 elsif($type eq 'inglobalfunc')
445                 {
446                         my $name = $getname->($operand);
447                         printf OPERAND_FORMAT, "$name()";
448                 }
449                 elsif($type eq 'ipoffset')
450                 {
451                         printf OPERAND_FORMAT, "@{[$ip + $operand]}" . sprintf ' ($%+d)', $operand;
452                 }
453                 else
454                 {
455                         die "unknown type: $type";
456                 }
457         };
458
459         my %statements = ();
460         my %come_from = ();
461         run_nfa $progs, $func->{first_statement}, "", id, nfa_default_state_checker,
462                 sub
463                 {
464                         my ($ip, $state, $s, $c) = @_;
465                         ++$statements{$ip};
466
467                         if(my $j = $c->{isjump})
468                         {
469                                 my $t = $ip + $s->{$j};
470                                 $come_from{$t}{$ip} = $c->{isconditional};
471                         }
472
473                         return 0;
474                 };
475
476         my $ipprev = undef;
477         for my $ip(sort { $a <=> $b } keys %statements)
478         {
479                 if($ip == $func->{first_statement})
480                 {
481                         printf INSTRUCTION_FORMAT, $ip, '', '.ENTRY';
482                         print INSTRUCTION_SEPARATOR;
483                 }
484                 if(defined $ipprev && $ip != $ipprev + 1)
485                 {
486                         printf INSTRUCTION_FORMAT, $ip, '', '.SKIP';
487                         printf OPERAND_FORMAT, $ip - $ipprev - 1;
488                         print INSTRUCTION_SEPARATOR;
489                 }
490                 if(my $cf = $come_from{$ip})
491                 {
492                         printf INSTRUCTION_FORMAT, $ip, '', '.XREF';
493                         my $cnt = 0;
494                         for(sort { $a <=> $b } keys %$cf)
495                         {
496                                 print OPERAND_SEPARATOR
497                                         if $cnt++;
498                                 printf OPERAND_FORMAT, ($cf->{$_} ? 'c' : 'j') . $_ . sprintf ' ($%+d)', $_ - $ip;
499                         }
500                         print INSTRUCTION_SEPARATOR;
501                 }
502
503                 my $op = $progs->{statements}[$ip]{op};
504                 my $ipt = $progs->{statements}[$ip];
505                 my $opprop = checkop $op;
506
507                 print PRE_MARK_STATEMENT
508                         if $highlight and $highlight->{$ip};
509
510                 my $showip = $opprop->{isjump};
511                 printf INSTRUCTION_FORMAT, $showip ? $ip : '', $highlight->{$ip} ? "<!>" : "", $op;
512
513                 my $cnt = 0;
514                 for my $o(qw(a b c))
515                 {
516                         next
517                                 if not defined $opprop->{$o};
518                         print OPERAND_SEPARATOR
519                                 if $cnt++;
520                         print PRE_MARK_OPERAND
521                                 if $highlight and $highlight->{$ip} and $highlight->{$ip}{$o};
522                         $operand->($ip, $opprop->{$o}, $ipt->{$o});
523                         print POST_MARK_OPERAND
524                                 if $highlight and $highlight->{$ip} and $highlight->{$ip}{$o};
525                 }
526
527                 print POST_MARK_STATEMENT
528                         if $highlight and $highlight->{$ip};
529
530                 print INSTRUCTION_SEPARATOR;
531         }
532 }
533
534 sub find_uninitialized_locals($$)
535 {
536         my ($progs, $func) = @_;
537
538
539         return
540                 if $func->{first_statement} < 0; # builtin
541
542         print STDERR "Checking $func->{debugname}...\n";
543
544         my $p = $func->{parm_start};
545         for(0..($func->{numparms}-1))
546         {
547                 $p += $func->{parm_size}[$_];
548         }
549
550         use constant WATCHME_R => 1;
551         use constant WATCHME_W => 2;
552         use constant WATCHME_X => 4;
553         use constant WATCHME_T => 8;
554         my %watchme = map { $_ => WATCHME_X } ($func->{parm_start} .. ($func->{parm_start} + $func->{locals} - 1));
555
556         for(keys %{$progs->{temps}})
557         {
558                 $watchme{$_} = WATCHME_T | WATCHME_X
559                         if not exists $watchme{$_};
560         }
561
562         my %write_places = ();
563         run_nfa $progs, $func->{first_statement}, "", id, nfa_default_state_checker,
564                 sub
565                 {
566                         my ($ip, $state, $s, $c) = @_;
567                         for(qw(a b c))
568                         {
569                                 my $type = $c->{$_};
570                                 next
571                                         unless defined $type;
572
573                                 my $ofs = $s->{$_};
574                                 if($type eq 'inglobal' || $type eq 'inglobalfunc')
575                                 {
576                                         $watchme{$ofs} |= WATCHME_R;
577                                 }
578                                 elsif($type eq 'inglobalvec')
579                                 {
580                                         $watchme{$ofs} |= WATCHME_R;
581                                         $watchme{$ofs+1} |= WATCHME_R;
582                                         $watchme{$ofs+2} |= WATCHME_R;
583                                 }
584                                 elsif($type eq 'outglobal')
585                                 {
586                                         $watchme{$ofs} |= WATCHME_W;
587                                         $write_places{$ip}{$_} = [$ofs]
588                                                 if $watchme{$ofs} & WATCHME_X;
589                                 }
590                                 elsif($type eq 'outglobalvec')
591                                 {
592                                         $watchme{$ofs} |= WATCHME_W;
593                                         $watchme{$ofs+1} |= WATCHME_W;
594                                         $watchme{$ofs+2} |= WATCHME_W;
595                                         my @l = grep { $watchme{$_} & WATCHME_X } $ofs .. ($ofs+2);
596                                         $write_places{$ip}{$_} = \@l
597                                                 if @l;
598                                 }
599                         }
600
601                         return 0;
602                 };
603
604         for(keys %watchme)
605         {
606                 delete $watchme{$_}
607                         if ($watchme{$_} & (WATCHME_R | WATCHME_W | WATCHME_X)) != (WATCHME_R | WATCHME_W | WATCHME_X);
608         }
609
610         return
611                 if not keys %watchme;
612
613         for(keys %watchme)
614         {
615                 $watchme{$_} = {
616                         flags => $watchme{$_},
617                         valid => [0, undef, undef]
618                 };
619         }
620
621         # mark parameters as initialized
622         for($func->{parm_start} .. ($p-1))
623         {
624                 $watchme{$_}{valid} = [1, undef, undef]
625                         if defined $watchme{$_};
626         }
627         # an initial run of STORE instruction is for receiving extra parameters
628         # (beyond 8). Only possible if the function is declared as having 8 params.
629         # Extra parameters behave otherwise like temps, but are initialized at
630         # startup.
631         for($func->{first_statement} .. (@{$progs->{statements}}-1))
632         {
633                 my $s = $progs->{statements}[$_];
634                 if($s->{op} eq 'STORE_V')
635                 {
636                         $watchme{$s->{a}}{valid} = [1, undef, undef]
637                                 if defined $watchme{$s->{a}};
638                         $watchme{$s->{a}+1}{valid} = [1, undef, undef]
639                                 if defined $watchme{$s->{a}+1};
640                         $watchme{$s->{a}+2}{valid} = [1, undef, undef]
641                                 if defined $watchme{$s->{a}+2};
642                 }
643                 elsif($s->{op} =~ /^STORE_/)
644                 {
645                         $watchme{$s->{a}}{valid} = [1, undef, undef]
646                                 if defined $watchme{$s->{a}};
647                 }
648                 else
649                 {
650                         last;
651                 }
652         }
653
654         my %warned = ();
655         my %ip_seen = ();
656         run_nfa $progs, $func->{first_statement}, \%watchme,
657                 sub {
658                         my ($h) = @_;
659                         return { map { $_ => { %{$h->{$_}} } } keys %$h };
660                 },
661                 sub {
662                         my ($ip, $state) = @_;
663
664                         my $s = $ip_seen{$ip};
665                         if($s)
666                         {
667                                 # if $state is stronger or equal to $s, return 1
668
669                                 for(keys %$state)
670                                 {
671                                         if($state->{$_}{valid}[0] < $s->{$_})
672                                         {
673                                                 # The current state is LESS valid than the previously run one. We NEED to run this.
674                                                 # The saved state can safely become the intersection [citation needed].
675                                                 for(keys %$state)
676                                                 {
677                                                         $s->{$_} = $state->{$_}{valid}[0]
678                                                                 if $state->{$_}{valid}[0] < $s->{$_};
679                                                 }
680                                                 return 0;
681                                         }
682                                 }
683                                 # if we get here, $state is stronger or equal. No need to try it.
684                                 return 1;
685                         }
686                         else
687                         {
688                                 # Never seen this IP yet.
689                                 $ip_seen{$ip} = { map { ($_ => $state->{$_}{valid}[0]); } keys %$state };
690                                 return 0;
691                         }
692                 },
693                 sub {
694                         my ($ip, $state, $s, $c) = @_;
695                         my $op = $s->{op};
696
697                         my $return_hack = $c->{isreturn} // 0;
698
699                         for(qw(a b c))
700                         {
701                                 my $type = $c->{$_};
702                                 next
703                                         unless defined $type;
704
705                                 my $ofs = $s->{$_};
706
707                                 my $read = sub
708                                 {
709                                         my ($ofs) = @_;
710                                         ++$return_hack
711                                                 if $return_hack;
712                                         return
713                                                 if not exists $state->{$ofs};
714                                         my $valid = $state->{$ofs}{valid};
715                                         if($valid->[0] == 0)
716                                         {
717                                                 if($return_hack <= 2 and ($op ne 'OR' && $op ne 'AND' || $_ ne 'b')) # fteqcc logicops cause this
718                                                 {
719                                                         print "; Use of uninitialized value $ofs in $func->{debugname} at $ip.$_\n";
720                                                         ++$warned{$ip}{$_};
721                                                 }
722                                         }
723                                         elsif($valid->[0] < 0)
724                                         {
725                                                 if($return_hack <= 2 and ($op ne 'OR' && $op ne 'AND' || $_ ne 'b')) # fteqcc logicops cause this
726                                                 {
727                                                         print "; Use of temporary $ofs across CALL in $func->{debugname} at $ip.$_\n";
728                                                         ++$warned{$ip}{$_};
729                                                 }
730                                         }
731                                         else
732                                         {
733                                                 # it's VALID
734                                                 if(defined $valid->[1])
735                                                 {
736                                                         delete $write_places{$valid->[1]}{$valid->[2]};
737                                                 }
738                                         }
739                                 };
740                                 my $write = sub
741                                 {
742                                         my ($ofs) = @_;
743                                         $state->{$ofs}{valid} = [1, $ip, $_]
744                                                 if exists $state->{$ofs};
745                                 };
746
747                                 if($type eq 'inglobal' || $type eq 'inglobalfunc')
748                                 {
749                                         $read->($ofs);
750                                 }
751                                 elsif($type eq 'inglobalvec')
752                                 {
753                                         $read->($ofs);
754                                         $read->($ofs+1);
755                                         $read->($ofs+2);
756                                 }
757                                 elsif($type eq 'outglobal')
758                                 {
759                                         $write->($ofs);
760                                 }
761                                 elsif($type eq 'outglobalvec')
762                                 {
763                                         $write->($ofs);
764                                         $write->($ofs+1);
765                                         $write->($ofs+2);
766                                 }
767                         }
768                         if($c->{iscall})
769                         {
770                                 # builtin calls may clobber stuff
771                                 my $func = $s->{a};
772                                 my $funcid = $progs->{globals}[$func]{v}{int};
773                                 my $funcobj = $progs->{functions}[$funcid];
774                                 if(!$funcobj || $funcobj->{first_statement} >= 0)
775                                 {
776                                         # invalidate temps
777                                         for(values %$state)
778                                         {
779                                                 if($_->{flags} & WATCHME_T)
780                                                 {
781                                                         $_->{valid} = [-1, undef, undef];
782                                                 }
783                                         }
784                                 }
785                         }
786
787                         return 0;
788                 };
789
790         for my $ip(keys %write_places)
791         {
792                 for my $operand(keys %{$write_places{$ip}})
793                 {
794                         # TODO verify it
795                         my %left = map { $_ => 1 } @{$write_places{$ip}{$operand}};
796                         my $isread = 0;
797
798                         my %writeplace_seen = ();
799                         run_nfa $progs, $ip+1, \%left,
800                                 sub
801                                 {
802                                         return { %{$_[0]} };
803                                 },
804                                 sub
805                                 {
806                                         my ($ip, $state) = @_;
807                                         return $writeplace_seen{"$ip " . join " ", sort keys %$state}++;
808                                 },
809                                 sub
810                                 {
811                                         my ($ip, $state, $s, $c) = @_;
812                                         for(qw(a b c))
813                                         {
814                                                 my $type = $c->{$_};
815                                                 next
816                                                         unless defined $type;
817
818                                                 my $ofs = $s->{$_};
819                                                 if($type eq 'inglobal' || $type eq 'inglobalfunc')
820                                                 {
821                                                         if($state->{$ofs})
822                                                         {
823                                                                 $isread = 1;
824                                                                 return -1; # exit TOTALLY
825                                                         }
826                                                 }
827                                                 elsif($type eq 'inglobalvec')
828                                                 {
829                                                         if($state->{$ofs} || $state->{$ofs+1} || $state->{$ofs+2})
830                                                         {
831                                                                 $isread = 1;
832                                                                 return -1; # exit TOTALLY
833                                                         }
834                                                 }
835                                                 elsif($type eq 'outglobal')
836                                                 {
837                                                         delete $state->{$ofs};
838                                                         return 1
839                                                                 if !%$state;
840                                                 }
841                                                 elsif($type eq 'outglobalvec')
842                                                 {
843                                                         delete $state->{$ofs};
844                                                         delete $state->{$ofs+1};
845                                                         delete $state->{$ofs+2};
846                                                         return 1
847                                                                 if !%$state;
848                                                 }
849                                         }
850                                         return 0;
851                                 };
852
853                         if(!$isread)
854                         {
855                                 print "; Value is never used in $func->{debugname} at $ip.$operand\n";
856                                 ++$warned{$ip}{$operand};
857                         }
858                 }
859         }
860         
861         disassemble_function($progs, $func, \%warned)
862                 if keys %warned;
863 }
864
865 use constant DEFAULTGLOBALS => [
866         "OFS_NULL",
867         "OFS_RETURN",
868         "OFS_RETURN[1]",
869         "OFS_RETURN[2]",
870         "OFS_PARM0",
871         "OFS_PARM0[1]",
872         "OFS_PARM0[2]",
873         "OFS_PARM1",
874         "OFS_PARM1[1]",
875         "OFS_PARM1[2]",
876         "OFS_PARM2",
877         "OFS_PARM2[1]",
878         "OFS_PARM2[2]",
879         "OFS_PARM3",
880         "OFS_PARM3[1]",
881         "OFS_PARM3[2]",
882         "OFS_PARM4",
883         "OFS_PARM4[1]",
884         "OFS_PARM4[2]",
885         "OFS_PARM5",
886         "OFS_PARM5[1]",
887         "OFS_PARM5[2]",
888         "OFS_PARM6",
889         "OFS_PARM6[1]",
890         "OFS_PARM6[2]",
891         "OFS_PARM7",
892         "OFS_PARM7[1]",
893         "OFS_PARM7[2]"
894 ];
895
896 sub defaultglobal($)
897 {
898         my ($ofs) = @_;
899         if($ofs < @{(DEFAULTGLOBALS)})
900         {
901                 return { ofs => $ofs, s_name => undef, debugname => DEFAULTGLOBALS->[$ofs], type => undef };
902         }
903         return { ofs => $ofs, s_name => undef, debugname => "<undefined>\@$ofs", type => undef };
904 }
905
906 sub parse_progs($)
907 {
908         my ($fh) = @_;
909
910         my %p = ();
911
912         print STDERR "Parsing header...\n";
913         $p{header} = parse_section $fh, DPROGRAMS_T, 0, undef, 1;
914         
915         print STDERR "Parsing strings...\n";
916         $p{strings} = get_section $fh, $p{header}{ofs_strings}, $p{header}{numstrings};
917         $p{getstring} = sub
918         {
919                 my ($startpos) = @_;
920                 my $endpos = index $p{strings}, "\0", $startpos;
921                 return substr $p{strings}, $startpos, $endpos - $startpos;
922         };
923
924         print STDERR "Parsing statements...\n";
925         $p{statements} = [parse_section $fh, DSTATEMENT_T, $p{header}{ofs_statements}, undef, $p{header}{numstatements}];
926
927         print STDERR "Parsing globaldefs...\n";
928         $p{globaldefs} = [parse_section $fh, DDEF_T, $p{header}{ofs_globaldefs}, undef, $p{header}{numglobaldefs}];
929
930         print STDERR "Parsing fielddefs...\n";
931         $p{fielddefs} = [parse_section $fh, DDEF_T, $p{header}{ofs_fielddefs}, undef, $p{header}{numfielddefs}];
932
933         print STDERR "Parsing globals...\n";
934         $p{globals} = [parse_section $fh, DGLOBAL_T, $p{header}{ofs_globals}, undef, $p{header}{numglobals}];
935
936         print STDERR "Parsing functions...\n";
937         $p{functions} = [parse_section $fh, DFUNCTION_T, $p{header}{ofs_functions}, undef, $p{header}{numfunctions}];
938
939         print STDERR "Detecting temps...\n";
940         my %offsets_saved = ();
941         for(@{$p{globaldefs}})
942         {
943                 my $type = $_->{type};
944                 my $name = $p{getstring}->($_->{s_name});
945                 next
946                         unless $type->{save} or $name ne "";
947                 for my $i(0..(typesize($_->{type}{type})-1))
948                 {
949                         ++$offsets_saved{$_->{ofs}+$i};
950                 }
951         }
952         my %offsets_initialized = ();
953         for(0..(@{$p{globals}}-1))
954         {
955                 if($p{globals}[$_]{v}{int})
956                 {
957                         ++$offsets_initialized{$_};
958                 }
959         }
960         my %istemp = ();
961         my %isconst = ();
962         for(0..(@{$p{globals}}-1))
963         {
964                 next
965                         if $_ < @{(DEFAULTGLOBALS)};
966                 ++$isconst{$_}
967                         if !$offsets_saved{$_} and $offsets_initialized{$_};
968                 ++$istemp{$_}
969                         if !$offsets_saved{$_} and !$offsets_initialized{$_};
970         }
971         $p{temps} = \%istemp;
972         $p{consts} = \%isconst;
973
974         print STDERR "Naming...\n";
975
976         # globaldefs
977         my @globaldefs = ();
978         for(@{$p{globaldefs}})
979         {
980                 my $s = $p{getstring}->($_->{s_name});
981                 $_->{debugname} //= "_$s"
982                         if length $s;
983         }
984         for(@{$p{globaldefs}})
985         {
986                 $globaldefs[$_->{ofs}] //= $_
987                         if defined $_->{debugname};
988         }
989         for(@{$p{globaldefs}})
990         {
991                 $globaldefs[$_->{ofs}] //= $_;
992         }
993         for(0..(@{$p{globals}}-1))
994         {
995                 $globaldefs[$_] //= {
996                         ofs => $_,
997                         s_name => undef,
998                         debugname => undef
999                 };
1000         }
1001         my %globaldefs = ();
1002         for(@globaldefs)
1003         {
1004                 if(!defined $_->{debugname})
1005                 {
1006                         if($istemp{$_->{ofs}})
1007                         {
1008                                 $_->{debugname} = "temp_$_->{ofs}";
1009                         }
1010                         elsif($isconst{$_->{ofs}})
1011                         {
1012                                 $_->{debugname} = "(" . get_constant(\%p, $p{globals}[$_->{ofs}]{v}) . ")";
1013                         }
1014                         else
1015                         {
1016                                 $_->{debugname} = "global_$_->{ofs}";
1017                         }
1018                 }
1019                 ++$globaldefs{$_->{debugname}};
1020         }
1021         for(@globaldefs)
1022         {
1023                 next
1024                         if $globaldefs{$_->{debugname}} <= 1;
1025                 print "Not unique: $_->{debugname} at $_->{ofs}\n";
1026                 $_->{debugname} .= "\@$_->{ofs}";
1027         }
1028         $p{globaldef_byoffset} = sub
1029         {
1030                 my ($ofs) = @_;
1031                 $ofs &= 0xFFFF;
1032                 if($ofs >= 0 && $ofs < @{(DEFAULTGLOBALS)})
1033                 {
1034                         return { ofs => $ofs, s_name => undef, debugname => DEFAULTGLOBALS->[$ofs], type => undef };
1035                 }
1036                 my $def = $globaldefs[$ofs];
1037                 return $def;
1038         };
1039
1040         # functions
1041         my %functions = ();
1042         for(@{$p{functions}})
1043         {
1044                 my $file = $p{getstring}->($_->{s_file});
1045                 my $name = $p{getstring}->($_->{s_name});
1046                 $name = "$file:$name"
1047                         if length $file;
1048                 $_->{debugname} = $name;
1049                 $functions{$_->{first_statement}} = $_;
1050         }
1051         $p{function_byoffset} = sub
1052         {
1053                 my ($ofs) = @_;
1054                 return $functions{$ofs};
1055         };
1056
1057         # what do we want to do?
1058         my $checkfunc = \&find_uninitialized_locals;
1059         #my $checkfunc = \&disassemble_function;
1060         for(sort { $a->{debugname} cmp $b->{debugname} } @{$p{functions}})
1061         {
1062                 $checkfunc->(\%p, $_);
1063         }
1064 }
1065
1066 open my $fh, '<', $ARGV[0];
1067 parse_progs $fh;