]> git.xonotic.org Git - xonotic/xonotic.git/blob - misc/tools/progs-analyzer.pl
only WARN about invalid opcodes, and guess their signature
[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->{isjump})
273                         {
274                                 if($c->{isconditional})
275                                 {
276                                         if(rand 2)
277                                         {
278                                                 if(($ret = $nfa->($ip+$s->{$c->{isjump}}, $copy_handler->($state))) < 0)
279                                                 {
280                                                         last;
281                                                 }
282                                                 $ip += 1;
283                                         }
284                                         else
285                                         {
286                                                 $nfa->($ip+1, $copy_handler->($state));
287                                                 $ip += $s->{$c->{isjump}};
288                                         }
289                                 }
290                                 else
291                                 {
292                                         $ip += $s->{$c->{isjump}};
293                                 }
294                         }
295                         else
296                         {
297                                 $ip += 1;
298                         }
299                 }
300
301                 return $ret;
302         };
303
304         $nfa->($ip, $copy_handler->($state));
305 }
306
307 sub get_constant($$)
308 {
309         my ($progs, $g) = @_;
310         if($g->{int} == 0)
311         {
312                 return undef;
313         }
314         elsif($g->{int} > 0 && $g->{int} < 16777216)
315         {
316                 if($g->{int} < length $progs->{strings} && $g->{int} > 0)
317                 {
318                         return str($progs->{getstring}->($g->{int}));
319                 }
320                 else
321                 {
322                         return $g->{int} . "i";
323                 }
324         }
325         else
326         {
327                 return $g->{float};
328         }
329 }
330
331 use constant PRE_MARK_STATEMENT => "";
332 use constant POST_MARK_STATEMENT => "";
333 use constant PRE_MARK_OPERAND => "*** ";
334 use constant POST_MARK_OPERAND => " ***";
335
336 use constant INSTRUCTION_FORMAT => "%8s %3s | %-12s ";
337 use constant OPERAND_FORMAT => "%s";
338 use constant OPERAND_SEPARATOR => ", ";
339 use constant INSTRUCTION_SEPARATOR => "\n";
340
341 sub str($)
342 {
343         my ($str) = @_;
344         $str =~ s/[\000-\037\\\"\177-\377]/sprintf "\\%03o", ord $&/ge;
345         return "\"$str\"";
346 }
347
348 sub disassemble_function($$;$)
349 {
350         my ($progs, $func, $highlight) = @_;
351
352         print "$func->{debugname}:\n";
353
354         my $initializer = sub
355         {
356                 my ($ofs) = @_;
357                 my $g = get_constant($progs, $progs->{globals}[$ofs]{v});
358                 print " = $g"
359                         if defined $g;
360         };
361
362         printf INSTRUCTION_FORMAT, '', '', '.PARM_START';
363         printf OPERAND_FORMAT, "$func->{parm_start}";
364         print INSTRUCTION_SEPARATOR;
365
366         printf INSTRUCTION_FORMAT, '', '', '.LOCALS';
367         printf OPERAND_FORMAT, "$func->{locals}";
368         print INSTRUCTION_SEPARATOR;
369
370         my %override_locals = ();
371         my $p = $func->{parm_start};
372         for(0..($func->{numparms}-1))
373         {
374                 $override_locals{$p} //= "argv_$_";
375                 for my $comp(0..($func->{parm_size}[$_]-1))
376                 {
377                         $override_locals{$p} //= "argv_$_\[$comp]";
378                         ++$p;
379                 }
380                 printf INSTRUCTION_FORMAT, '', '', '.ARG';
381                 printf OPERAND_FORMAT, "argv_$_";
382                 print OPERAND_SEPARATOR;
383                 printf OPERAND_FORMAT, $func->{parm_size}[$_];
384                 print INSTRUCTION_SEPARATOR;
385         }
386         for($func->{parm_start}..($func->{parm_start} + $func->{locals} - 1))
387         {
388                 next
389                         if exists $override_locals{$_};
390                 $override_locals{$_} = "local_$_";
391
392                 printf INSTRUCTION_FORMAT, '', '', '.LOCAL';
393                 printf OPERAND_FORMAT, "local_$_";
394                 $initializer->($_);
395                 print INSTRUCTION_SEPARATOR;
396         }
397
398         my $getname = sub
399         {
400                 my ($ofs) = @_;
401                 $ofs &= 0xFFFF;
402                 return $override_locals{$ofs}
403                         if exists $override_locals{$ofs};
404                 my $def = $progs->{globaldef_byoffset}->($ofs);
405                 return $def->{debugname};
406         };
407
408         my $operand = sub
409         {
410                 my ($ip, $type, $operand) = @_;
411                 if($type eq 'inglobal')
412                 {
413                         my $name = $getname->($operand);
414                         printf OPERAND_FORMAT, "$name";
415                 }
416                 elsif($type eq 'outglobal')
417                 {
418                         my $name = $getname->($operand);
419                         printf OPERAND_FORMAT, "&$name";
420                 }
421                 elsif($type eq 'inglobalvec')
422                 {
423                         my $name = $getname->($operand);
424                         printf OPERAND_FORMAT, "$name\[\]";
425                 }
426                 elsif($type eq 'outglobalvec')
427                 {
428                         my $name = $getname->($operand);
429                         printf OPERAND_FORMAT, "&$name\[\]";
430                 }
431                 elsif($type eq 'inglobalfunc')
432                 {
433                         my $name = $getname->($operand);
434                         printf OPERAND_FORMAT, "$name()";
435                 }
436                 elsif($type eq 'ipoffset')
437                 {
438                         printf OPERAND_FORMAT, "@{[$ip + $operand]}" . sprintf ' ($%+d)', $operand;
439                 }
440                 else
441                 {
442                         die "unknown type: $type";
443                 }
444         };
445
446         my %statements = ();
447         my %come_from = ();
448         run_nfa $progs, $func->{first_statement}, "", id, nfa_default_state_checker,
449                 sub
450                 {
451                         my ($ip, $state, $s, $c) = @_;
452                         ++$statements{$ip};
453
454                         if(my $j = $c->{isjump})
455                         {
456                                 my $t = $ip + $s->{$j};
457                                 $come_from{$t}{$ip} = $c->{isconditional};
458                         }
459
460                         return 0;
461                 };
462
463         my $ipprev = undef;
464         for my $ip(sort { $a <=> $b } keys %statements)
465         {
466                 if($ip == $func->{first_statement})
467                 {
468                         printf INSTRUCTION_FORMAT, $ip, '', '.ENTRY';
469                         print INSTRUCTION_SEPARATOR;
470                 }
471                 if(defined $ipprev && $ip != $ipprev + 1)
472                 {
473                         printf INSTRUCTION_FORMAT, $ip, '', '.SKIP';
474                         printf OPERAND_FORMAT, $ip - $ipprev - 1;
475                         print INSTRUCTION_SEPARATOR;
476                 }
477                 if(my $cf = $come_from{$ip})
478                 {
479                         printf INSTRUCTION_FORMAT, $ip, '', '.XREF';
480                         my $cnt = 0;
481                         for(sort { $a <=> $b } keys %$cf)
482                         {
483                                 print OPERAND_SEPARATOR
484                                         if $cnt++;
485                                 printf OPERAND_FORMAT, ($cf->{$_} ? 'c' : 'j') . $_ . sprintf ' ($%+d)', $_ - $ip;
486                         }
487                         print INSTRUCTION_SEPARATOR;
488                 }
489
490                 my $op = $progs->{statements}[$ip]{op};
491                 my $ipt = $progs->{statements}[$ip];
492                 my $opprop = checkop $op;
493
494                 print PRE_MARK_STATEMENT
495                         if $highlight and $highlight->{$ip};
496
497                 my $showip = $opprop->{isjump};
498                 printf INSTRUCTION_FORMAT, $showip ? $ip : '', $highlight->{$ip} ? "<!>" : "", $op;
499
500                 my $cnt = 0;
501                 for my $o(qw(a b c))
502                 {
503                         next
504                                 if not defined $opprop->{$o};
505                         print OPERAND_SEPARATOR
506                                 if $cnt++;
507                         print PRE_MARK_OPERAND
508                                 if $highlight and $highlight->{$ip} and $highlight->{$ip}{$o};
509                         $operand->($ip, $opprop->{$o}, $ipt->{$o});
510                         print POST_MARK_OPERAND
511                                 if $highlight and $highlight->{$ip} and $highlight->{$ip}{$o};
512                 }
513
514                 print POST_MARK_STATEMENT
515                         if $highlight and $highlight->{$ip};
516
517                 print INSTRUCTION_SEPARATOR;
518         }
519 }
520
521 sub find_uninitialized_locals($$)
522 {
523         my ($progs, $func) = @_;
524
525
526         return
527                 if $func->{first_statement} < 0; # builtin
528
529         print STDERR "Checking $func->{debugname}...\n";
530
531         my $p = $func->{parm_start};
532         for(0..($func->{numparms}-1))
533         {
534                 $p += $func->{parm_size}[$_];
535         }
536
537         use constant WATCHME_R => 1;
538         use constant WATCHME_W => 2;
539         use constant WATCHME_X => 4;
540         use constant WATCHME_T => 8;
541         my %watchme = map { $_ => WATCHME_X } ($func->{parm_start} .. ($func->{parm_start} + $func->{locals} - 1));
542
543         for(keys %{$progs->{temps}})
544         {
545                 $watchme{$_} = WATCHME_T | WATCHME_X
546                         if not exists $watchme{$_};
547         }
548
549         my %write_places = ();
550         run_nfa $progs, $func->{first_statement}, "", id, nfa_default_state_checker,
551                 sub
552                 {
553                         my ($ip, $state, $s, $c) = @_;
554                         for(qw(a b c))
555                         {
556                                 my $type = $c->{$_};
557                                 next
558                                         unless defined $type;
559
560                                 my $ofs = $s->{$_};
561                                 if($type eq 'inglobal' || $type eq 'inglobalfunc')
562                                 {
563                                         $watchme{$ofs} |= WATCHME_R;
564                                 }
565                                 elsif($type eq 'inglobalvec')
566                                 {
567                                         $watchme{$ofs} |= WATCHME_R;
568                                         $watchme{$ofs+1} |= WATCHME_R;
569                                         $watchme{$ofs+2} |= WATCHME_R;
570                                 }
571                                 elsif($type eq 'outglobal')
572                                 {
573                                         $watchme{$ofs} |= WATCHME_W;
574                                         $write_places{$ip}{$_} = [$ofs]
575                                                 if $watchme{$ofs} & WATCHME_X;
576                                 }
577                                 elsif($type eq 'outglobalvec')
578                                 {
579                                         $watchme{$ofs} |= WATCHME_W;
580                                         $watchme{$ofs+1} |= WATCHME_W;
581                                         $watchme{$ofs+2} |= WATCHME_W;
582                                         my @l = grep { $watchme{$_} & WATCHME_X } $ofs .. ($ofs+2);
583                                         $write_places{$ip}{$_} = \@l
584                                                 if @l;
585                                 }
586                         }
587
588                         return 0;
589                 };
590
591         for(keys %watchme)
592         {
593                 delete $watchme{$_}
594                         if ($watchme{$_} & (WATCHME_R | WATCHME_W | WATCHME_X)) != (WATCHME_R | WATCHME_W | WATCHME_X);
595         }
596
597         return
598                 if not keys %watchme;
599
600         for(keys %watchme)
601         {
602                 $watchme{$_} = {
603                         flags => $watchme{$_},
604                         valid => [0, undef, undef]
605                 };
606         }
607
608         # mark parameters as initialized
609         for($func->{parm_start} .. ($p-1))
610         {
611                 $watchme{$_}{valid} = [1, undef, undef]
612                         if defined $watchme{$_};
613         }
614         # an initial run of STORE instruction is for receiving extra parameters
615         # (beyond 8). Only possible if the function is declared as having 8 params.
616         # Extra parameters behave otherwise like temps, but are initialized at
617         # startup.
618         for($func->{first_statement} .. (@{$progs->{statements}}-1))
619         {
620                 my $s = $progs->{statements}[$_];
621                 if($s->{op} eq 'STORE_V')
622                 {
623                         $watchme{$s->{a}}{valid} = [1, undef, undef]
624                                 if defined $watchme{$s->{a}};
625                         $watchme{$s->{a}+1}{valid} = [1, undef, undef]
626                                 if defined $watchme{$s->{a}+1};
627                         $watchme{$s->{a}+2}{valid} = [1, undef, undef]
628                                 if defined $watchme{$s->{a}+2};
629                 }
630                 elsif($s->{op} =~ /^STORE_/)
631                 {
632                         $watchme{$s->{a}}{valid} = [1, undef, undef]
633                                 if defined $watchme{$s->{a}};
634                 }
635                 else
636                 {
637                         last;
638                 }
639         }
640
641         my %warned = ();
642         my %ip_seen = ();
643         run_nfa $progs, $func->{first_statement}, \%watchme,
644                 sub {
645                         my ($h) = @_;
646                         return { map { $_ => { %{$h->{$_}} } } keys %$h };
647                 },
648                 sub {
649                         my ($ip, $state) = @_;
650
651                         my $s = $ip_seen{$ip};
652                         if($s)
653                         {
654                                 # if $state is stronger or equal to $s, return 1
655
656                                 for(keys %$state)
657                                 {
658                                         if($state->{$_}{valid}[0] < $s->{$_})
659                                         {
660                                                 # The current state is LESS valid than the previously run one. We NEED to run this.
661                                                 # The saved state can safely become the intersection [citation needed].
662                                                 for(keys %$state)
663                                                 {
664                                                         $s->{$_} = $state->{$_}{valid}[0]
665                                                                 if $state->{$_}{valid}[0] < $s->{$_};
666                                                 }
667                                                 return 0;
668                                         }
669                                 }
670                                 # if we get here, $state is stronger or equal. No need to try it.
671                                 return 1;
672                         }
673                         else
674                         {
675                                 # Never seen this IP yet.
676                                 $ip_seen{$ip} = { map { ($_ => $state->{$_}{valid}[0]); } keys %$state };
677                                 return 0;
678                         }
679                 },
680                 sub {
681                         my ($ip, $state, $s, $c) = @_;
682                         my $op = $s->{op};
683
684                         my $return_hack = $c->{isreturn} // 0;
685
686                         for(qw(a b c))
687                         {
688                                 my $type = $c->{$_};
689                                 next
690                                         unless defined $type;
691
692                                 my $ofs = $s->{$_};
693
694                                 my $read = sub
695                                 {
696                                         my ($ofs) = @_;
697                                         ++$return_hack
698                                                 if $return_hack;
699                                         return
700                                                 if not exists $state->{$ofs};
701                                         my $valid = $state->{$ofs}{valid};
702                                         if($valid->[0] == 0)
703                                         {
704                                                 if($return_hack <= 2 and ($op ne 'OR' && $op ne 'AND' || $_ ne 'b')) # fteqcc logicops cause this
705                                                 {
706                                                         print "; Use of uninitialized value $ofs in $func->{debugname} at $ip.$_\n";
707                                                         ++$warned{$ip}{$_};
708                                                 }
709                                         }
710                                         elsif($valid->[0] < 0)
711                                         {
712                                                 if($return_hack <= 2 and ($op ne 'OR' && $op ne 'AND' || $_ ne 'b')) # fteqcc logicops cause this
713                                                 {
714                                                         print "; Use of temporary $ofs across CALL in $func->{debugname} at $ip.$_\n";
715                                                         ++$warned{$ip}{$_};
716                                                 }
717                                         }
718                                         else
719                                         {
720                                                 # it's VALID
721                                                 if(defined $valid->[1])
722                                                 {
723                                                         delete $write_places{$valid->[1]}{$valid->[2]};
724                                                 }
725                                         }
726                                 };
727                                 my $write = sub
728                                 {
729                                         my ($ofs) = @_;
730                                         $state->{$ofs}{valid} = [1, $ip, $_]
731                                                 if exists $state->{$ofs};
732                                 };
733
734                                 if($type eq 'inglobal' || $type eq 'inglobalfunc')
735                                 {
736                                         $read->($ofs);
737                                 }
738                                 elsif($type eq 'inglobalvec')
739                                 {
740                                         $read->($ofs);
741                                         $read->($ofs+1);
742                                         $read->($ofs+2);
743                                 }
744                                 elsif($type eq 'outglobal')
745                                 {
746                                         $write->($ofs);
747                                 }
748                                 elsif($type eq 'outglobalvec')
749                                 {
750                                         $write->($ofs);
751                                         $write->($ofs+1);
752                                         $write->($ofs+2);
753                                 }
754                         }
755                         if($c->{iscall})
756                         {
757                                 # builtin calls may clobber stuff
758                                 my $func = $s->{a};
759                                 my $funcid = $progs->{globals}[$func]{v}{int};
760                                 my $funcobj = $progs->{functions}[$funcid];
761                                 if(!$funcobj || $funcobj->{first_statement} >= 0)
762                                 {
763                                         # invalidate temps
764                                         for(values %$state)
765                                         {
766                                                 if($_->{flags} & WATCHME_T)
767                                                 {
768                                                         $_->{valid} = [-1, undef, undef];
769                                                 }
770                                         }
771                                 }
772                                 else # builtin
773                                 {
774                                         my $def = $progs->{globaldef_byoffset}->($func);
775                                         return 1
776                                                 if $def->{debugname} eq 'error';
777                                 }
778                         }
779
780                         return 0;
781                 };
782
783         for my $ip(keys %write_places)
784         {
785                 for my $operand(keys %{$write_places{$ip}})
786                 {
787                         # TODO verify it
788                         my %left = map { $_ => 1 } @{$write_places{$ip}{$operand}};
789                         my $isread = 0;
790
791                         my %writeplace_seen = ();
792                         run_nfa $progs, $ip+1, \%left,
793                                 sub
794                                 {
795                                         return { %{$_[0]} };
796                                 },
797                                 sub
798                                 {
799                                         my ($ip, $state) = @_;
800                                         return $writeplace_seen{"$ip " . join " ", sort keys %$state}++;
801                                 },
802                                 sub
803                                 {
804                                         my ($ip, $state, $s, $c) = @_;
805                                         for(qw(a b c))
806                                         {
807                                                 my $type = $c->{$_};
808                                                 next
809                                                         unless defined $type;
810
811                                                 my $ofs = $s->{$_};
812                                                 if($type eq 'inglobal' || $type eq 'inglobalfunc')
813                                                 {
814                                                         if($state->{$ofs})
815                                                         {
816                                                                 $isread = 1;
817                                                                 return -1; # exit TOTALLY
818                                                         }
819                                                 }
820                                                 elsif($type eq 'inglobalvec')
821                                                 {
822                                                         if($state->{$ofs} || $state->{$ofs+1} || $state->{$ofs+2})
823                                                         {
824                                                                 $isread = 1;
825                                                                 return -1; # exit TOTALLY
826                                                         }
827                                                 }
828                                                 elsif($type eq 'outglobal')
829                                                 {
830                                                         delete $state->{$ofs};
831                                                         return 1
832                                                                 if !%$state;
833                                                 }
834                                                 elsif($type eq 'outglobalvec')
835                                                 {
836                                                         delete $state->{$ofs};
837                                                         delete $state->{$ofs+1};
838                                                         delete $state->{$ofs+2};
839                                                         return 1
840                                                                 if !%$state;
841                                                 }
842                                         }
843                                         return 0;
844                                 };
845
846                         if(!$isread)
847                         {
848                                 print "; Value is never used in $func->{debugname} at $ip.$operand\n";
849                                 ++$warned{$ip}{$operand};
850                         }
851                 }
852         }
853         
854         disassemble_function($progs, $func, \%warned)
855                 if keys %warned;
856 }
857
858 use constant DEFAULTGLOBALS => [
859         "OFS_NULL",
860         "OFS_RETURN",
861         "OFS_RETURN[1]",
862         "OFS_RETURN[2]",
863         "OFS_PARM0",
864         "OFS_PARM0[1]",
865         "OFS_PARM0[2]",
866         "OFS_PARM1",
867         "OFS_PARM1[1]",
868         "OFS_PARM1[2]",
869         "OFS_PARM2",
870         "OFS_PARM2[1]",
871         "OFS_PARM2[2]",
872         "OFS_PARM3",
873         "OFS_PARM3[1]",
874         "OFS_PARM3[2]",
875         "OFS_PARM4",
876         "OFS_PARM4[1]",
877         "OFS_PARM4[2]",
878         "OFS_PARM5",
879         "OFS_PARM5[1]",
880         "OFS_PARM5[2]",
881         "OFS_PARM6",
882         "OFS_PARM6[1]",
883         "OFS_PARM6[2]",
884         "OFS_PARM7",
885         "OFS_PARM7[1]",
886         "OFS_PARM7[2]"
887 ];
888
889 sub defaultglobal($)
890 {
891         my ($ofs) = @_;
892         if($ofs < @{(DEFAULTGLOBALS)})
893         {
894                 return { ofs => $ofs, s_name => undef, debugname => DEFAULTGLOBALS->[$ofs], type => undef };
895         }
896         return { ofs => $ofs, s_name => undef, debugname => "<undefined>\@$ofs", type => undef };
897 }
898
899 sub parse_progs($)
900 {
901         my ($fh) = @_;
902
903         my %p = ();
904
905         print STDERR "Parsing header...\n";
906         $p{header} = parse_section $fh, DPROGRAMS_T, 0, undef, 1;
907         
908         print STDERR "Parsing strings...\n";
909         $p{strings} = get_section $fh, $p{header}{ofs_strings}, $p{header}{numstrings};
910         $p{getstring} = sub
911         {
912                 my ($startpos) = @_;
913                 my $endpos = index $p{strings}, "\0", $startpos;
914                 return substr $p{strings}, $startpos, $endpos - $startpos;
915         };
916
917         print STDERR "Parsing statements...\n";
918         $p{statements} = [parse_section $fh, DSTATEMENT_T, $p{header}{ofs_statements}, undef, $p{header}{numstatements}];
919
920         print STDERR "Parsing globaldefs...\n";
921         $p{globaldefs} = [parse_section $fh, DDEF_T, $p{header}{ofs_globaldefs}, undef, $p{header}{numglobaldefs}];
922
923         print STDERR "Parsing fielddefs...\n";
924         $p{fielddefs} = [parse_section $fh, DDEF_T, $p{header}{ofs_fielddefs}, undef, $p{header}{numfielddefs}];
925
926         print STDERR "Parsing globals...\n";
927         $p{globals} = [parse_section $fh, DGLOBAL_T, $p{header}{ofs_globals}, undef, $p{header}{numglobals}];
928
929         print STDERR "Parsing functions...\n";
930         $p{functions} = [parse_section $fh, DFUNCTION_T, $p{header}{ofs_functions}, undef, $p{header}{numfunctions}];
931
932         print STDERR "Detecting temps...\n";
933         my %offsets_saved = ();
934         for(@{$p{globaldefs}})
935         {
936                 my $type = $_->{type};
937                 my $name = $p{getstring}->($_->{s_name});
938                 next
939                         unless $type->{save} or $name ne "";
940                 for my $i(0..(typesize($_->{type}{type})-1))
941                 {
942                         ++$offsets_saved{$_->{ofs}+$i};
943                 }
944         }
945         my %offsets_initialized = ();
946         for(0..(@{$p{globals}}-1))
947         {
948                 if($p{globals}[$_]{v}{int})
949                 {
950                         ++$offsets_initialized{$_};
951                 }
952         }
953         my %istemp = ();
954         my %isconst = ();
955         for(0..(@{$p{globals}}-1))
956         {
957                 next
958                         if $_ < @{(DEFAULTGLOBALS)};
959                 ++$isconst{$_}
960                         if !$offsets_saved{$_} and $offsets_initialized{$_};
961                 ++$istemp{$_}
962                         if !$offsets_saved{$_} and !$offsets_initialized{$_};
963         }
964         $p{temps} = \%istemp;
965         $p{consts} = \%isconst;
966
967         print STDERR "Naming...\n";
968
969         # globaldefs
970         my @globaldefs = ();
971         for(@{$p{globaldefs}})
972         {
973                 my $s = $p{getstring}->($_->{s_name});
974                 $_->{debugname} //= "_$s"
975                         if length $s;
976         }
977         for(@{$p{globaldefs}})
978         {
979                 $globaldefs[$_->{ofs}] //= $_
980                         if defined $_->{debugname};
981         }
982         for(@{$p{globaldefs}})
983         {
984                 $globaldefs[$_->{ofs}] //= $_;
985         }
986         for(0..(@{$p{globals}}-1))
987         {
988                 $globaldefs[$_] //= {
989                         ofs => $_,
990                         s_name => undef,
991                         debugname => undef
992                 };
993         }
994         my %globaldefs = ();
995         for(@globaldefs)
996         {
997                 if(!defined $_->{debugname})
998                 {
999                         if($istemp{$_->{ofs}})
1000                         {
1001                                 $_->{debugname} = "temp_$_->{ofs}";
1002                         }
1003                         elsif($isconst{$_->{ofs}})
1004                         {
1005                                 $_->{debugname} = "(" . get_constant(\%p, $p{globals}[$_->{ofs}]{v}) . ")";
1006                         }
1007                         else
1008                         {
1009                                 $_->{debugname} = "global_$_->{ofs}";
1010                         }
1011                 }
1012                 ++$globaldefs{$_->{debugname}};
1013         }
1014         for(@globaldefs)
1015         {
1016                 next
1017                         if $globaldefs{$_->{debugname}} <= 1;
1018                 print "Not unique: $_->{debugname} at $_->{ofs}\n";
1019                 $_->{debugname} .= "\@$_->{ofs}";
1020         }
1021         $p{globaldef_byoffset} = sub
1022         {
1023                 my ($ofs) = @_;
1024                 $ofs &= 0xFFFF;
1025                 if($ofs >= 0 && $ofs < @{(DEFAULTGLOBALS)})
1026                 {
1027                         return { ofs => $ofs, s_name => undef, debugname => DEFAULTGLOBALS->[$ofs], type => undef };
1028                 }
1029                 my $def = $globaldefs[$ofs];
1030                 return $def;
1031         };
1032
1033         # functions
1034         my %functions = ();
1035         for(@{$p{functions}})
1036         {
1037                 my $file = $p{getstring}->($_->{s_file});
1038                 my $name = $p{getstring}->($_->{s_name});
1039                 $name = "$file:$name"
1040                         if length $file;
1041                 $_->{debugname} = $name;
1042                 $functions{$_->{first_statement}} = $_;
1043         }
1044         $p{function_byoffset} = sub
1045         {
1046                 my ($ofs) = @_;
1047                 return $functions{$ofs};
1048         };
1049
1050         # what do we want to do?
1051         my $checkfunc = \&find_uninitialized_locals;
1052         #my $checkfunc = \&disassemble_function;
1053         for(sort { $a->{debugname} cmp $b->{debugname} } @{$p{functions}})
1054         {
1055                 $checkfunc->(\%p, $_);
1056         }
1057 }
1058
1059 open my $fh, '<', $ARGV[0];
1060 parse_progs $fh;