]> git.xonotic.org Git - xonotic/xonotic.git/blob - misc/tools/progs-analyzer.pl
LNO support.
[xonotic/xonotic.git] / misc / tools / progs-analyzer.pl
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5 use Digest::SHA;
6 use Carp;
7
8 sub id()
9 {
10         return sub { $_[0]; };
11 }
12
13 sub signed($)
14 {
15         my ($bits) = @_;
16         return sub { $_[0] >= (2**($bits-1)) ? $_[0]-(2**$bits) : $_[0]; };
17 }
18
19 use constant OPCODE_E => [qw[
20         DONE
21         MUL_F MUL_V MUL_FV MUL_VF
22         DIV_F
23         ADD_F ADD_V
24         SUB_F SUB_V
25         EQ_F EQ_V EQ_S EQ_E EQ_FNC
26         NE_F NE_V NE_S NE_E NE_FNC
27         LE GE LT GT
28         LOAD_F LOAD_V LOAD_S LOAD_ENT LOAD_FLD LOAD_FNC
29         ADDRESS
30         STORE_F STORE_V STORE_S STORE_ENT STORE_FLD STORE_FNC
31         STOREP_F STOREP_V STOREP_S STOREP_ENT STOREP_FLD STOREP_FNC
32         RETURN
33         NOT_F NOT_V NOT_S NOT_ENT NOT_FNC
34         IF IFNOT
35         CALL0 CALL1 CALL2 CALL3 CALL4 CALL5 CALL6 CALL7 CALL8
36         STATE
37         GOTO
38         AND OR
39         BITAND BITOR
40 ]];
41 use constant ETYPE_E => [qw[
42         void
43         string
44         float
45         vector
46         entity
47         field
48         function
49         pointer
50 ]];
51 use constant DEF_SAVEGLOBAL => 32768;
52 sub typesize($)
53 {
54         my ($type) = @_;
55         return 3 if $type eq 'vector';
56         return 1;
57 }
58
59 sub checkop($)
60 {
61         my ($op) = @_;
62         if($op =~ /^IF.*_V$/)
63         {
64                 return { a => 'inglobalvec', b => 'ipoffset', isjump => 'b', isconditional => 1 };
65         }
66         if($op =~ /^IF/)
67         {
68                 return { a => 'inglobal', b => 'ipoffset', isjump => 'b', isconditional => 1 };
69         }
70         if($op eq 'GOTO')
71         {
72                 return { a => 'ipoffset', isjump => 'a', isconditional => 0 };
73         }
74         if($op =~ /^ADD_V$|^SUB_V$/)
75         {
76                 return { a => 'inglobalvec', b => 'inglobalvec', c => 'outglobalvec' };
77         }
78         if($op =~ /^MUL_V$|^EQ_V$|^NE_V$/)
79         {
80                 return { a => 'inglobalvec', b => 'inglobalvec', c => 'outglobal' };
81         }
82         if($op eq 'MUL_FV')
83         {
84                 return { a => 'inglobal', b => 'inglobalvec', c => 'outglobalvec' };
85         }
86         if($op eq 'MUL_VF')
87         {
88                 return { a => 'inglobalvec', b => 'inglobal', c => 'outglobalvec' };
89         }
90         if($op eq 'LOAD_V')
91         {
92                 return { a => 'inglobal', b => 'inglobal', c => 'outglobalvec' };
93         }
94         if($op =~ /^NOT_V/)
95         {
96                 return { a => 'inglobalvec', c => 'outglobal' };
97         }
98         if($op =~ /^NOT_/)
99         {
100                 return { a => 'inglobal', c => 'outglobal' };
101         }
102         if($op eq 'STOREP_V')
103         {
104                 return { a => 'inglobalvec', b => 'inglobal' };
105         }
106         if($op eq 'STORE_V')
107         {
108                 return { a => 'inglobalvec', b => 'outglobalvec' };
109         }
110         if($op =~ /^STOREP_/)
111         {
112                 return { a => 'inglobal', b => 'inglobal' };
113         }
114         if($op =~ /^STORE_/)
115         {
116                 return { a => 'inglobal', b => 'outglobal' };
117         }
118         if($op =~ /^CALL/)
119         {
120                 return { a => 'inglobalfunc', iscall => 1 };
121         }
122         if($op =~ /^DONE$|^RETURN$/)
123         {
124                 return { a => 'inglobalvec', isreturn => 1 };
125         }
126         if($op eq 'STATE')
127         {
128                 return { a => 'inglobal', b => 'inglobalfunc' };
129         }
130         if($op =~ /^INVALID#/)
131         {
132                 return { isinvalid => 1 };
133         }
134         return { a => 'inglobal', b => 'inglobal', c => 'outglobal' };
135 }
136
137 use constant TYPES => {
138         int => ['V', 4, signed 32],
139         ushort => ['v', 2, id],
140         short => ['v', 2, signed 16],
141         opcode => ['v', 2, sub { OPCODE_E->[$_[0]] or do { warn "Invalid opcode: $_[0]"; "INVALID#$_[0]"; }; }],
142         float => ['f', 4, id],
143         uchar8 => ['a8', 8, sub { [unpack 'C8', $_[0]] }],
144         global => ['i', 4, sub { { int => $_[0], float => unpack "f", pack "L", $_[0] }; }],
145         deftype => ['v', 2, sub { { type => ETYPE_E->[$_[0] & ~DEF_SAVEGLOBAL], save => !!($_[0] & DEF_SAVEGLOBAL) }; }],
146 };
147
148 use constant DPROGRAMS_T => [
149         [int => 'version'],
150         [int => 'crc'],
151         [int => 'ofs_statements'],
152         [int => 'numstatements'],
153         [int => 'ofs_globaldefs'],
154         [int => 'numglobaldefs'],
155         [int => 'ofs_fielddefs'],
156         [int => 'numfielddefs'],
157         [int => 'ofs_functions'],
158         [int => 'numfunctions'],
159         [int => 'ofs_strings'],
160         [int => 'numstrings'],
161         [int => 'ofs_globals'],
162         [int => 'numglobals'],
163         [int => 'entityfields']
164 ];
165
166 use constant DSTATEMENT_T => [
167         [opcode => 'op'],
168         [short => 'a'],
169         [short => 'b'],
170         [short => 'c']
171 ];
172
173 use constant DDEF_T => [
174         [deftype => 'type'],
175         [ushort => 'ofs'],
176         [int => 's_name']
177 ];
178
179 use constant DGLOBAL_T => [
180         [global => 'v'],
181 ];
182
183 use constant DFUNCTION_T => [
184         [int => 'first_statement'],
185         [int => 'parm_start'],
186         [int => 'locals'],
187         [int => 'profile'],
188         [int => 's_name'],
189         [int => 's_file'],
190         [int => 'numparms'],
191         [uchar8 => 'parm_size'],
192 ];
193
194 use constant LNOHEADER_T => [
195         [int => 'lnotype'],
196         [int => 'version'],
197         [int => 'numglobaldefs'],
198         [int => 'numglobals'],
199         [int => 'numfielddefs'],
200         [int => 'numstatements'],
201 ];
202
203 use constant LNO_T => [
204         [int => 'v'],
205 ];
206
207 sub get_section($$$)
208 {
209         my ($fh, $start, $len) = @_;
210         seek $fh, $start, 0
211                 or die "seek: $!";
212         $len == read $fh, my $buf, $len
213                 or die "short read from $start length $len (malformed progs header)";
214         return $buf;
215 }
216
217 sub parse_section($$$$$)
218 {
219         my ($fh, $struct, $start, $len, $cnt) = @_;
220
221         my $itemlen = 0;
222         $itemlen += TYPES->{$_->[0]}->[1]
223                 for @$struct;
224         my $packspec = join '', map { TYPES->{$_->[0]}->[0]; } @$struct;
225         my @packnames = map { $_->[1]; } @$struct;
226
227         $len = $cnt * $itemlen
228                 if not defined $len and defined $cnt;
229         $cnt = int($len / $itemlen)
230                 if not defined $cnt and defined $len;
231         die "Invalid length specification"
232                 unless defined $len and defined $cnt and $len == $cnt * $itemlen;
233         die "Invalid length specification in scalar context"
234                 unless wantarray or $cnt == 1;
235
236         seek $fh, $start, 0
237                 or die "seek: $!";
238         my @out = map
239         {
240                 $itemlen == read $fh, my $buf, $itemlen
241                         or die "short read from $start length $cnt * $itemlen $(malformed progs header)";
242                 my %h = ();
243                 @h{@packnames} = unpack $packspec, $buf;
244                 $h{$_->[1]} = TYPES->{$_->[0]}->[2]->($h{$_->[1]})
245                         for @$struct;
246                 \%h;
247         }
248         0..($cnt-1);
249         return @out
250                 if wantarray;
251         return $out[0];
252 }
253
254 sub nfa_default_state_checker()
255 {
256         my %seen;
257         return sub
258         {
259                 my ($ip, $state) = @_;
260                 return $seen{"$ip $state"}++;
261         };
262 }
263
264 sub run_nfa($$$$$$)
265 {
266         my ($progs, $ip, $state, $copy_handler, $state_checker, $instruction_handler) = @_;
267
268         my $statements = $progs->{statements};
269
270         my $nfa;
271         $nfa = sub
272         {
273                 no warnings 'recursion';
274
275                 my ($ip, $state) = @_;
276                 my $ret = 0;
277
278                 for(;;)
279                 {
280                         return $ret
281                                 if $state_checker->($ip, $state);
282
283                         my $s = $statements->[$ip];
284                         my $c = checkop $s->{op};
285
286                         if(($ret = $instruction_handler->($ip, $state, $s, $c)))
287                         {
288                                 # abort execution
289                                 last;
290                         }
291
292                         if($c->{isreturn})
293                         {
294                                 last;
295                         }
296                         elsif($c->{iscall})
297                         {
298                                 my $func = $s->{a};
299                                 my $funcid = $progs->{globals}[$func]{v}{int};
300                                 last
301                                         if $progs->{error_func}{$funcid};
302                                 $ip += 1;
303                         }
304                         elsif($c->{isjump})
305                         {
306                                 if($c->{isconditional})
307                                 {
308                                         if(rand 2)
309                                         {
310                                                 if(($ret = $nfa->($ip+$s->{$c->{isjump}}, $copy_handler->($state))) < 0)
311                                                 {
312                                                         last;
313                                                 }
314                                                 $ip += 1;
315                                         }
316                                         else
317                                         {
318                                                 $nfa->($ip+1, $copy_handler->($state));
319                                                 $ip += $s->{$c->{isjump}};
320                                         }
321                                 }
322                                 else
323                                 {
324                                         $ip += $s->{$c->{isjump}};
325                                 }
326                         }
327                         else
328                         {
329                                 $ip += 1;
330                         }
331                 }
332
333                 return $ret;
334         };
335
336         $nfa->($ip, $copy_handler->($state));
337 }
338
339 sub get_constant($$)
340 {
341         my ($progs, $g) = @_;
342         if($g->{int} == 0)
343         {
344                 return 0;
345         }
346         elsif($g->{int} > 0 && $g->{int} < 8388608)
347         {
348                 if($g->{int} < length $progs->{strings} && $g->{int} > 0)
349                 {
350                         return str($progs->{getstring}->($g->{int}));
351                 }
352                 else
353                 {
354                         return $g->{int} . "i";
355                 }
356         }
357         else
358         {
359                 return $g->{float};
360         }
361 }
362
363 use constant PRE_MARK_STATEMENT => "";
364 use constant POST_MARK_STATEMENT => "";
365 use constant PRE_MARK_OPERAND => "*** ";
366 use constant POST_MARK_OPERAND => " ***";
367
368 use constant INSTRUCTION_FORMAT => "%8s %3s | %-12s ";
369 use constant OPERAND_FORMAT => "%s";
370 use constant OPERAND_SEPARATOR => ", ";
371 use constant INSTRUCTION_SEPARATOR => "\n";
372
373 sub str($)
374 {
375         my ($str) = @_;
376         $str =~ s/[\000-\037\\\"\177-\377]/sprintf "\\%03o", ord $&/ge;
377         return "\"$str\"";
378 }
379
380 sub debugpos($$$) {
381         my ($progs, $func, $ip) = @_;
382         my $s = $func->{debugname};
383         if ($progs->{cno}) {
384                 my $column = $progs->{cno}[$ip]{v};
385                 $s =~ s/:/:$column:/;
386         }
387         if ($progs->{lno}) {
388                 my $line = $progs->{lno}[$ip]{v};
389                 $s =~ s/:/:$line:/;
390         }
391         return $s;
392 }
393
394 sub disassemble_function($$;$)
395 {
396         my ($progs, $func, $highlight) = @_;
397
398         print "$func->{debugname}:\n";
399
400         if($func->{first_statement} < 0) # builtin
401         {
402                 printf INSTRUCTION_FORMAT, '', '', '.BUILTIN';
403                 printf OPERAND_FORMAT, -$func->{first_statement};
404                 print INSTRUCTION_SEPARATOR;
405                 return;
406         }
407
408         my $initializer = sub
409         {
410                 my ($ofs) = @_;
411                 my $g = get_constant($progs, $progs->{globals}[$ofs]{v});
412                 print " = $g"
413                         if defined $g;
414         };
415
416         printf INSTRUCTION_FORMAT, '', '', '.PARM_START';
417         printf OPERAND_FORMAT, "$func->{parm_start}";
418         print INSTRUCTION_SEPARATOR;
419
420         printf INSTRUCTION_FORMAT, '', '', '.LOCALS';
421         printf OPERAND_FORMAT, "$func->{locals}";
422         print INSTRUCTION_SEPARATOR;
423
424         my %override_locals = ();
425         my $p = $func->{parm_start};
426         for(0..($func->{numparms}-1))
427         {
428                 $override_locals{$p} //= "argv_$_";
429                 for my $comp(0..($func->{parm_size}[$_]-1))
430                 {
431                         $override_locals{$p} //= "argv_$_\[$comp]";
432                         ++$p;
433                 }
434                 printf INSTRUCTION_FORMAT, '', '', '.ARG';
435                 printf OPERAND_FORMAT, "argv_$_";
436                 print OPERAND_SEPARATOR;
437                 printf OPERAND_FORMAT, $func->{parm_size}[$_];
438                 print INSTRUCTION_SEPARATOR;
439         }
440         for($func->{parm_start}..($func->{parm_start} + $func->{locals} - 1))
441         {
442                 next
443                         if exists $override_locals{$_};
444                 $override_locals{$_} = "local_$_";
445
446                 printf INSTRUCTION_FORMAT, '', '', '.LOCAL';
447                 printf OPERAND_FORMAT, "local_$_";
448                 $initializer->($_);
449                 print INSTRUCTION_SEPARATOR;
450         }
451
452         my $getname = sub
453         {
454                 my ($ofs) = @_;
455                 return $override_locals{$ofs}
456                         if exists $override_locals{$ofs};
457                 my $def = $progs->{globaldef_byoffset}->($ofs);
458                 return $def->{debugname};
459         };
460
461         my $operand = sub
462         {
463                 my ($ip, $type, $operand) = @_;
464                 if($type eq 'inglobal')
465                 {
466                         my $name = $getname->($operand);
467                         printf OPERAND_FORMAT, "$name";
468                 }
469                 elsif($type eq 'outglobal')
470                 {
471                         my $name = $getname->($operand);
472                         printf OPERAND_FORMAT, "&$name";
473                 }
474                 elsif($type eq 'inglobalvec')
475                 {
476                         my $name = $getname->($operand);
477                         printf OPERAND_FORMAT, "$name\[\]";
478                 }
479                 elsif($type eq 'outglobalvec')
480                 {
481                         my $name = $getname->($operand);
482                         printf OPERAND_FORMAT, "&$name\[\]";
483                 }
484                 elsif($type eq 'inglobalfunc')
485                 {
486                         my $name = $getname->($operand);
487                         printf OPERAND_FORMAT, "$name()";
488                 }
489                 elsif($type eq 'ipoffset')
490                 {
491                         printf OPERAND_FORMAT, "@{[$ip + $operand]}" . sprintf ' ($%+d)', $operand;
492                 }
493                 else
494                 {
495                         die "unknown type: $type";
496                 }
497         };
498
499         my $statements = $func->{statements};
500         my $come_from = $func->{come_from};
501
502         my $ipprev = undef;
503         for my $ip(sort { $a <=> $b } keys %$statements)
504         {
505                 if($ip == $func->{first_statement})
506                 {
507                         printf INSTRUCTION_FORMAT, $ip, '', '.ENTRY';
508                         print INSTRUCTION_SEPARATOR;
509                 }
510                 if(defined $ipprev && $ip != $ipprev + 1)
511                 {
512                         printf INSTRUCTION_FORMAT, $ip, '', '.SKIP';
513                         printf OPERAND_FORMAT, $ip - $ipprev - 1;
514                         print INSTRUCTION_SEPARATOR;
515                 }
516                 if(my $cf = $come_from->{$ip})
517                 {
518                         printf INSTRUCTION_FORMAT, $ip, '', '.XREF';
519                         my $cnt = 0;
520                         for(sort { $a <=> $b } keys %$cf)
521                         {
522                                 print OPERAND_SEPARATOR
523                                         if $cnt++;
524                                 printf OPERAND_FORMAT, ($cf->{$_} ? 'c' : 'j') . $_ . sprintf ' ($%+d)', $_ - $ip;
525                         }
526                         print INSTRUCTION_SEPARATOR;
527                 }
528
529                 my $op = $progs->{statements}[$ip]{op};
530                 my $ipt = $progs->{statements}[$ip];
531                 my $opprop = checkop $op;
532
533                 if($highlight and $highlight->{$ip})
534                 {
535                         for(values %{$highlight->{$ip}})
536                         {
537                                 for(sort keys %$_)
538                                 {
539                                         print PRE_MARK_STATEMENT;
540                                         printf INSTRUCTION_FORMAT, '', '<!>', '.WARN';
541                                         my $pos = debugpos $progs, $func, $ip;
542                                         printf OPERAND_FORMAT, "$_ (in $pos)";
543                                         print INSTRUCTION_SEPARATOR;
544                                 }
545                         }
546                 }
547
548                 print PRE_MARK_STATEMENT
549                         if $highlight and $highlight->{$ip};
550
551                 my $showip = $opprop->{isjump};
552                 printf INSTRUCTION_FORMAT, $showip ? $ip : '', $highlight->{$ip} ? '<!>' : '', $op;
553
554                 my $cnt = 0;
555                 for my $o(qw(a b c))
556                 {
557                         next
558                                 if not defined $opprop->{$o};
559                         print OPERAND_SEPARATOR
560                                 if $cnt++;
561                         print PRE_MARK_OPERAND
562                                 if $highlight and $highlight->{$ip} and $highlight->{$ip}{$o};
563                         $operand->($ip, $opprop->{$o}, $ipt->{$o});
564                         print POST_MARK_OPERAND
565                                 if $highlight and $highlight->{$ip} and $highlight->{$ip}{$o};
566                 }
567
568                 print POST_MARK_STATEMENT
569                         if $highlight and $highlight->{$ip};
570
571                 print INSTRUCTION_SEPARATOR;
572         }
573 }
574
575 sub find_uninitialized_locals($$)
576 {
577         my ($progs, $func) = @_;
578
579         return
580                 if $func->{first_statement} < 0; # builtin
581
582         print STDERR "Checking $func->{debugname}...\n";
583
584         my $p = $func->{parm_start};
585         for(0..($func->{numparms}-1))
586         {
587                 $p += $func->{parm_size}[$_];
588         }
589
590         use constant WATCHME_R => 1;
591         use constant WATCHME_W => 2;
592         use constant WATCHME_X => 4;
593         use constant WATCHME_T => 8;
594         my %watchme = map { $_ => WATCHME_X } ($func->{parm_start} .. ($func->{parm_start} + $func->{locals} - 1));
595
596         for(keys %{$progs->{temps}})
597         {
598                 next
599                         if exists $watchme{$_};
600                 if($progs->{temps}{$_})
601                 {
602                         # shared temp
603                         $watchme{$_} = WATCHME_T | WATCHME_X
604                 }
605                 else
606                 {
607                         # unique temp
608                         $watchme{$_} = WATCHME_X
609                 }
610         }
611
612         $watchme{$_} |= WATCHME_R
613                 for keys %{$func->{globals_read}};
614         $watchme{$_} |= WATCHME_W
615                 for keys %{$func->{globals_written}};
616
617         my %write_places = ();
618         for my $ofs(keys %{$func->{globals_written}})
619         {
620                 next
621                         unless exists $watchme{$ofs} and $watchme{$ofs} & WATCHME_X;
622                 for my $ip(keys %{$func->{globals_written}{$ofs}})
623                 {
624                         for my $op(keys %{$func->{globals_written}{$ofs}{$ip}})
625                         {
626                                 push @{$write_places{$ip}{$op}}, $ofs;
627                         }
628                 }
629         }
630
631         for(keys %watchme)
632         {
633                 delete $watchme{$_}
634                         if ($watchme{$_} & (WATCHME_R | WATCHME_W | WATCHME_X)) != (WATCHME_R | WATCHME_W | WATCHME_X);
635         }
636
637         return
638                 if not keys %watchme;
639
640         for(keys %watchme)
641         {
642                 $watchme{$_} = {
643                         flags => $watchme{$_},
644                         valid => [0, undef, undef]
645                 };
646         }
647
648         # mark parameters as initialized
649         for($func->{parm_start} .. ($p-1))
650         {
651                 $watchme{$_}{valid} = [1, undef, undef]
652                         if defined $watchme{$_};
653         }
654
655         my %warned = ();
656         my %ip_seen = ();
657         run_nfa $progs, $func->{first_statement}, \%watchme,
658                 sub {
659                         my ($h) = @_;
660                         return { map { $_ => { %{$h->{$_}} } } keys %$h };
661                 },
662                 sub {
663                         my ($ip, $state) = @_;
664
665                         my $s = $ip_seen{$ip};
666                         if($s)
667                         {
668                                 # if $state is stronger or equal to $s, return 1
669
670                                 for(keys %$state)
671                                 {
672                                         if($state->{$_}{valid}[0] < $s->{$_})
673                                         {
674                                                 # The current state is LESS valid than the previously run one. We NEED to run this.
675                                                 # The saved state can safely become the intersection [citation needed].
676                                                 for(keys %$state)
677                                                 {
678                                                         $s->{$_} = $state->{$_}{valid}[0]
679                                                                 if $state->{$_}{valid}[0] < $s->{$_};
680                                                 }
681                                                 return 0;
682                                         }
683                                 }
684                                 # if we get here, $state is stronger or equal. No need to try it.
685                                 return 1;
686                         }
687                         else
688                         {
689                                 # Never seen this IP yet.
690                                 $ip_seen{$ip} = { map { ($_ => $state->{$_}{valid}[0]); } keys %$state };
691                                 return 0;
692                         }
693                 },
694                 sub {
695                         my ($ip, $state, $s, $c) = @_;
696                         my $op = $s->{op};
697
698                         # QCVM BUG: RETURN always takes vector, there is no float equivalent
699                         my $return_hack = $c->{isreturn} // 0;
700
701                         if($op eq 'STORE_V')
702                         {
703                                 # COMPILER BUG of QCC: params are always copied using STORE_V
704                                 if($s->{b} >= 4 && $s->{b} < 28) # parameter range
705                                 {
706                                         $return_hack = 1;
707                                 }
708                         }
709
710                         if($c->{isinvalid})
711                         {
712                                 ++$warned{$ip}{''}{"Invalid opcode"};
713                         }
714                         for(qw(a b c))
715                         {
716                                 my $type = $c->{$_};
717                                 next
718                                         unless defined $type;
719
720                                 my $ofs = $s->{$_};
721
722                                 my $read = sub
723                                 {
724                                         my ($ofs) = @_;
725                                         ++$return_hack
726                                                 if $return_hack;
727                                         return
728                                                 if not exists $state->{$ofs};
729                                         my $valid = $state->{$ofs}{valid};
730                                         if($valid->[0] == 0)
731                                         {
732                                                 # COMPILER BUG of FTEQCC: AND and OR may take uninitialized as second argument (logicops)
733                                                 if($return_hack <= 2 and ($op ne 'OR' && $op ne 'AND' || $_ ne 'b'))
734                                                 {
735                                                         ++$warned{$ip}{$_}{"Use of uninitialized value"};
736                                                 }
737                                         }
738                                         elsif($valid->[0] < 0)
739                                         {
740                                                 # COMPILER BUG of FTEQCC: AND and OR may take uninitialized as second argument (logicops)
741                                                 if($return_hack <= 2 and ($op ne 'OR' && $op ne 'AND' || $_ ne 'b'))
742                                                 {
743                                                         ++$warned{$ip}{$_}{"Use of temporary across CALL"};
744                                                 }
745                                         }
746                                         else
747                                         {
748                                                 # it's VALID
749                                                 if(defined $valid->[1])
750                                                 {
751                                                         delete $write_places{$valid->[1]}{$valid->[2]};
752                                                 }
753                                         }
754                                 };
755                                 my $write = sub
756                                 {
757                                         my ($ofs) = @_;
758                                         $state->{$ofs}{valid} = [1, $ip, $_]
759                                                 if exists $state->{$ofs};
760                                 };
761
762                                 if($type eq 'inglobal' || $type eq 'inglobalfunc')
763                                 {
764                                         $read->($ofs);
765                                 }
766                                 elsif($type eq 'inglobalvec')
767                                 {
768                                         $read->($ofs);
769                                         $read->($ofs+1);
770                                         $read->($ofs+2);
771                                 }
772                                 elsif($type eq 'outglobal')
773                                 {
774                                         $write->($ofs);
775                                 }
776                                 elsif($type eq 'outglobalvec')
777                                 {
778                                         $write->($ofs);
779                                         $write->($ofs+1);
780                                         $write->($ofs+2);
781                                 }
782                                 elsif($type eq 'ipoffset')
783                                 {
784                                         ++$warned{$ip}{$_}{"Endless loop"}
785                                                 if $ofs == 0;
786                                         ++$warned{$ip}{$_}{"No-operation jump"}
787                                                 if $ofs == 1;
788                                 }
789                         }
790                         if($c->{iscall})
791                         {
792                                 # builtin calls may clobber stuff
793                                 my $func = $s->{a};
794                                 my $funcid = $progs->{globals}[$func]{v}{int};
795                                 my $funcobj = $progs->{functions}[$funcid];
796                                 if(!$funcobj || $funcobj->{first_statement} >= 0)
797                                 {
798                                         # invalidate temps
799                                         for(values %$state)
800                                         {
801                                                 if($_->{flags} & WATCHME_T)
802                                                 {
803                                                         $_->{valid} = [-1, undef, undef];
804                                                 }
805                                         }
806                                 }
807                         }
808
809                         return 0;
810                 };
811
812         for my $ip(keys %write_places)
813         {
814                 for my $operand(keys %{$write_places{$ip}})
815                 {
816                         # TODO verify it
817                         my %left = map { $_ => 1 } @{$write_places{$ip}{$operand}};
818                         my $isread = 0;
819
820                         my %writeplace_seen = ();
821                         run_nfa $progs, $ip+1, \%left,
822                                 sub
823                                 {
824                                         return { %{$_[0]} };
825                                 },
826                                 sub
827                                 {
828                                         my ($ip, $state) = @_;
829                                         return $writeplace_seen{"$ip " . join " ", sort keys %$state}++;
830                                 },
831                                 sub
832                                 {
833                                         my ($ip, $state, $s, $c) = @_;
834                                         for(qw(a b c))
835                                         {
836                                                 my $type = $c->{$_};
837                                                 next
838                                                         unless defined $type;
839
840                                                 my $ofs = $s->{$_};
841                                                 if($type eq 'inglobal' || $type eq 'inglobalfunc')
842                                                 {
843                                                         if($state->{$ofs})
844                                                         {
845                                                                 $isread = 1;
846                                                                 return -1; # exit TOTALLY
847                                                         }
848                                                 }
849                                                 elsif($type eq 'inglobalvec')
850                                                 {
851                                                         if($state->{$ofs} || $state->{$ofs+1} || $state->{$ofs+2})
852                                                         {
853                                                                 $isread = 1;
854                                                                 return -1; # exit TOTALLY
855                                                         }
856                                                 }
857                                                 elsif($type eq 'outglobal')
858                                                 {
859                                                         delete $state->{$ofs};
860                                                         return 1
861                                                                 if !%$state;
862                                                 }
863                                                 elsif($type eq 'outglobalvec')
864                                                 {
865                                                         delete $state->{$ofs};
866                                                         delete $state->{$ofs+1};
867                                                         delete $state->{$ofs+2};
868                                                         return 1
869                                                                 if !%$state;
870                                                 }
871                                         }
872                                         return 0;
873                                 };
874
875                         if(!$isread)
876                         {
877                                 ++$warned{$ip}{$operand}{"Value is never used"};
878                         }
879                 }
880         }
881         
882         disassemble_function($progs, $func, \%warned)
883                 if keys %warned;
884 }
885
886 use constant DEFAULTGLOBALS => [
887         "OFS_NULL",
888         "OFS_RETURN",
889         "OFS_RETURN[1]",
890         "OFS_RETURN[2]",
891         "OFS_PARM0",
892         "OFS_PARM0[1]",
893         "OFS_PARM0[2]",
894         "OFS_PARM1",
895         "OFS_PARM1[1]",
896         "OFS_PARM1[2]",
897         "OFS_PARM2",
898         "OFS_PARM2[1]",
899         "OFS_PARM2[2]",
900         "OFS_PARM3",
901         "OFS_PARM3[1]",
902         "OFS_PARM3[2]",
903         "OFS_PARM4",
904         "OFS_PARM4[1]",
905         "OFS_PARM4[2]",
906         "OFS_PARM5",
907         "OFS_PARM5[1]",
908         "OFS_PARM5[2]",
909         "OFS_PARM6",
910         "OFS_PARM6[1]",
911         "OFS_PARM6[2]",
912         "OFS_PARM7",
913         "OFS_PARM7[1]",
914         "OFS_PARM7[2]"
915 ];
916
917 sub defaultglobal($)
918 {
919         my ($ofs) = @_;
920         if($ofs < @{(DEFAULTGLOBALS)})
921         {
922                 return { ofs => $ofs, s_name => undef, debugname => DEFAULTGLOBALS->[$ofs], type => undef };
923         }
924         return { ofs => $ofs, s_name => undef, debugname => "<undefined>\@$ofs", type => undef };
925 }
926
927 sub detect_constants($)
928 {
929         my ($progs) = @_;
930         use constant GLOBALFLAG_R => 1; # read
931         use constant GLOBALFLAG_W => 2; # written
932         use constant GLOBALFLAG_S => 4; # saved
933         use constant GLOBALFLAG_I => 8; # initialized
934         use constant GLOBALFLAG_N => 16; # named
935         use constant GLOBALFLAG_Q => 32; # unique to function
936         use constant GLOBALFLAG_U => 64; # unused
937         use constant GLOBALFLAG_P => 128; # possibly parameter passing
938         use constant GLOBALFLAG_D => 256; # has a def
939         my @globalflags = (GLOBALFLAG_Q | GLOBALFLAG_U) x (@{$progs->{globals}} + 2);
940
941         for(@{$progs->{functions}})
942         {
943                 for(keys %{$_->{globals_used}})
944                 {
945                         if($globalflags[$_] & GLOBALFLAG_U)
946                         {
947                                 $globalflags[$_] &= ~GLOBALFLAG_U;
948                         }
949                         elsif($globalflags[$_] & GLOBALFLAG_Q)
950                         {
951                                 $globalflags[$_] &= ~GLOBALFLAG_Q;
952                         }
953                 }
954                 $globalflags[$_] |= GLOBALFLAG_R
955                         for keys %{$_->{globals_read}};
956                 $globalflags[$_] |= GLOBALFLAG_W
957                         for keys %{$_->{globals_written}};
958                 next
959                         if $_->{first_statement} < 0;
960                 for my $ip($_->{first_statement} .. (@{$progs->{statements}}-1))
961                 {
962                         my $s = $progs->{statements}[$ip];
963                         if($s->{op} eq 'STORE_V')
964                         {
965                                 $globalflags[$s->{a}] |= GLOBALFLAG_P
966                                         if $s->{b} >= $_->{parm_start} and $s->{b} < $_->{parm_start} + $_->{locals};
967                                 $globalflags[$s->{a}+1] |= GLOBALFLAG_P
968                                         if $s->{b}+1 >= $_->{parm_start} and $s->{b}+1 < $_->{parm_start} + $_->{locals};
969                                 $globalflags[$s->{a}+2] |= GLOBALFLAG_P
970                                         if $s->{b}+2 >= $_->{parm_start} and $s->{b}+2 < $_->{parm_start} + $_->{locals};
971                         }
972                         elsif($s->{op} =~ /^STORE_/)
973                         {
974                                 $globalflags[$s->{a}] |= GLOBALFLAG_P
975                                         if $s->{b} >= $_->{parm_start} and $s->{b} < $_->{parm_start} + $_->{locals};
976                         }
977                         else
978                         {
979                                 last;
980                         }
981                 }
982         }
983
984         # parameter passing globals are only ever used in STORE_ instructions
985         for my $s(@{$progs->{statements}})
986         {
987                 next
988                         if $s->{op} =~ /^STORE_/;
989
990                 my $c = checkop $s->{op};
991
992                 for(qw(a b c))
993                 {
994                         my $type = $c->{$_};
995                         next
996                                 unless defined $type;
997
998                         my $ofs = $s->{$_};
999                         if($type eq 'inglobal' || $type eq 'inglobalfunc' || $type eq 'outglobal')
1000                         {
1001                                 $globalflags[$ofs] &= ~GLOBALFLAG_P;
1002                         }
1003                         if($type eq 'inglobalvec' || $type eq 'outglobalvec')
1004                         {
1005                                 $globalflags[$ofs] &= ~GLOBALFLAG_P;
1006                                 $globalflags[$ofs+1] &= ~GLOBALFLAG_P;
1007                                 $globalflags[$ofs+2] &= ~GLOBALFLAG_P;
1008                         }
1009                 }
1010         }
1011
1012         my %offsets_saved = ();
1013         for(@{$progs->{globaldefs}})
1014         {
1015                 my $type = $_->{type};
1016                 my $name = $progs->{getstring}->($_->{s_name});
1017                 $name = ''
1018                         if $name eq 'IMMEDIATE' or $name =~ /^\./;
1019                 $_->{debugname} = $name
1020                         if $name ne '';
1021                 $globalflags[$_->{ofs}] |= GLOBALFLAG_D;
1022                 if($type->{save})
1023                 {
1024                         $globalflags[$_->{ofs}] |= GLOBALFLAG_S;
1025                 }
1026                 if(defined $_->{debugname})
1027                 {
1028                         $globalflags[$_->{ofs}] |= GLOBALFLAG_N;
1029                 }
1030         }
1031         # fix up vectors
1032         my @extradefs = ();
1033         for(@{$progs->{globaldefs}})
1034         {
1035                 my $type = $_->{type};
1036                 for my $i(1..(typesize($type->{type})-1))
1037                 {
1038                         # add missing def
1039                         if(!($globalflags[$_->{ofs}+$i] & GLOBALFLAG_D))
1040                         {
1041                                 print "Missing globaldef for a component@{[defined $_->{debugname} ? ' of ' . $_->{debugname} : '']} at $_->{ofs}+$i\n";
1042                                 push @extradefs, {
1043                                         type => {
1044                                                 saved => 0,
1045                                                 type => 'float'
1046                                         },
1047                                         ofs => $_->{ofs} + $i,
1048                                         debugname => defined $_->{debugname} ? $_->{debugname} . "[$i]" : undef
1049                                 };
1050                         }
1051                         # "saved" and "named" states hit adjacent globals too
1052                         $globalflags[$_->{ofs}+$i] |= $globalflags[$_->{ofs}] & (GLOBALFLAG_S | GLOBALFLAG_N | GLOBALFLAG_D);
1053                 }
1054         }
1055         push @{$progs->{globaldefs}}, @extradefs;
1056
1057         my %offsets_initialized = ();
1058         for(0..(@{$progs->{globals}}-1))
1059         {
1060                 if($progs->{globals}[$_]{v}{int})
1061                 {
1062                         $globalflags[$_] |= GLOBALFLAG_I;
1063                 }
1064         }
1065
1066         my @globaltypes = (undef) x @{$progs->{globals}};
1067
1068         my %istemp = ();
1069         for(0..(@{$progs->{globals}}-1))
1070         {
1071                 next
1072                         if $_ < @{(DEFAULTGLOBALS)};
1073                 if(($globalflags[$_] & (GLOBALFLAG_R | GLOBALFLAG_W)) == 0)
1074                 {
1075                         $globaltypes[$_] = "unused";
1076                 }
1077                 elsif(($globalflags[$_] & (GLOBALFLAG_R | GLOBALFLAG_W)) == GLOBALFLAG_R)
1078                 {
1079                         # so it is ro
1080                         if(($globalflags[$_] & GLOBALFLAG_N) == GLOBALFLAG_N)
1081                         {
1082                                 $globaltypes[$_] = "read_only";
1083                         }
1084                         elsif(($globalflags[$_] & GLOBALFLAG_S) == 0)
1085                         {
1086                                 $globaltypes[$_] = "const";
1087                         }
1088                         else
1089                         {
1090                                 $globaltypes[$_] = "read_only";
1091                         }
1092                 }
1093                 elsif(($globalflags[$_] & (GLOBALFLAG_R | GLOBALFLAG_W)) == GLOBALFLAG_W)
1094                 {
1095                         $globaltypes[$_] = "write_only";
1096                 }
1097                 else
1098                 {
1099                         # now we know it is rw
1100                         if(($globalflags[$_] & GLOBALFLAG_N) == GLOBALFLAG_N)
1101                         {
1102                                 $globaltypes[$_] = "global";
1103                         }
1104                         elsif(($globalflags[$_] & (GLOBALFLAG_S | GLOBALFLAG_I)) == 0)
1105                         {
1106                                 if($globalflags[$_] & GLOBALFLAG_P)
1107                                 {
1108                                         $globaltypes[$_] = "OFS_PARM";
1109                                 }
1110                                 elsif($globalflags[$_] & GLOBALFLAG_Q)
1111                                 {
1112                                         $globaltypes[$_] = "uniquetemp";
1113                                         $istemp{$_} = 0;
1114                                 }
1115                                 else
1116                                 {
1117                                         $globaltypes[$_] = "temp";
1118                                         $istemp{$_} = 1;
1119                                 }
1120                         }
1121                         elsif(($globalflags[$_] & (GLOBALFLAG_S | GLOBALFLAG_I)) == GLOBALFLAG_I)
1122                         {
1123                                 $globaltypes[$_] = "not_saved";
1124                         }
1125                         else
1126                         {
1127                                 $globaltypes[$_] = "global";
1128                         }
1129                 }
1130         }
1131         $progs->{temps} = \%istemp;
1132
1133         # globaldefs
1134         my @globaldefs = (undef) x @{$progs->{globals}};
1135         for(@{$progs->{globaldefs}})
1136         {
1137                 $globaldefs[$_->{ofs}] //= $_
1138                         if defined $_->{debugname};
1139         }
1140         for(@{$progs->{globaldefs}})
1141         {
1142                 $globaldefs[$_->{ofs}] //= $_;
1143         }
1144         for(0..(@{$progs->{globals}}-1))
1145         {
1146                 $globaldefs[$_] //= {
1147                         ofs => $_,
1148                         s_name => undef,
1149                         debugname => undef,
1150                         type => undef
1151                 };
1152         }
1153         for(0..(@{(DEFAULTGLOBALS)}-1))
1154         {
1155                 $globaldefs[$_] = { ofs => $_, s_name => undef, debugname => DEFAULTGLOBALS->[$_], type => undef };
1156                 $globaltypes[$_] = 'defglobal';
1157         }
1158         my %globaldefs_namecount = ();
1159         for(@globaldefs)
1160         {
1161                 $_->{globaltype} = $globaltypes[$_->{ofs}];
1162                 if(defined $_->{debugname})
1163                 {
1164                         # already has debugname
1165                 }
1166                 elsif($_->{globaltype} eq 'const')
1167                 {
1168                         $_->{debugname} = get_constant($progs, $progs->{globals}[$_->{ofs}]{v});
1169                 }
1170                 else
1171                 {
1172                         $_->{debugname} = "$_->{globaltype}_$_->{ofs}";
1173                 }
1174                 ++$globaldefs_namecount{$_->{debugname}};
1175         }
1176         for(@globaldefs)
1177         {
1178                 next
1179                         if $globaldefs_namecount{$_->{debugname}} <= 1 && !$ENV{FORCE_OFFSETS};
1180                 #print "Not unique: $_->{debugname} at $_->{ofs}\n";
1181                 $_->{debugname} .= "\@$_->{ofs}";
1182         }
1183         $progs->{globaldef_byoffset} = sub
1184         {
1185                 my ($ofs) = @_;
1186                 my $def = $globaldefs[$ofs];
1187                 return $def;
1188         };
1189 }
1190
1191 sub parse_progs($$)
1192 {
1193         my ($fh, $lnofh) = @_;
1194
1195         my %p = ();
1196
1197         print STDERR "Parsing header...\n";
1198         $p{header} = parse_section $fh, DPROGRAMS_T, 0, undef, 1;
1199         
1200         if (defined $lnofh) {
1201                 print STDERR "Parsing LNO...\n";
1202                 my $lnoheader = parse_section $lnofh, LNOHEADER_T, 0, undef, 1;
1203                 eval {
1204                         die "Not a LNOF"
1205                                 if $lnoheader->{lnotype} != unpack 'V', 'LNOF';
1206                         die "Not version 1"
1207                                 if $lnoheader->{version} != 1;
1208                         die "Not same count of globaldefs"
1209                                 if $lnoheader->{numglobaldefs} != $p{header}{numglobaldefs};
1210                         die "Not same count of globals"
1211                                 if $lnoheader->{numglobals} != $p{header}{numglobals};
1212                         die "Not same count of fielddefs"
1213                                 if $lnoheader->{numfielddefs} != $p{header}{numfielddefs};
1214                         die "Not same count of statements"
1215                                 if $lnoheader->{numstatements} != $p{header}{numstatements};
1216                         $p{lno} = [parse_section $lnofh, LNO_T, 24, undef, $lnoheader->{numstatements}];
1217                         eval {
1218                                 $p{lno} = [parse_section $lnofh, LNO_T, 24, undef, $lnoheader->{numstatements} * 2];
1219                                 $p{cno} = [splice $p{lno}, $lnoheader->{numstatements}];
1220                                 print STDERR "Cool, this LNO even has column number info!\n";
1221                         };
1222                 } or warn "Skipping LNO: $@";
1223         }
1224
1225         print STDERR "Parsing strings...\n";
1226         $p{strings} = get_section $fh, $p{header}{ofs_strings}, $p{header}{numstrings};
1227         $p{getstring} = sub
1228         {
1229                 my ($startpos) = @_;
1230                 my $endpos = index $p{strings}, "\0", $startpos;
1231                 return substr $p{strings}, $startpos, $endpos - $startpos;
1232         };
1233
1234         print STDERR "Parsing globals...\n";
1235         $p{globals} = [parse_section $fh, DGLOBAL_T, $p{header}{ofs_globals}, undef, $p{header}{numglobals}];
1236
1237         print STDERR "Parsing globaldefs...\n";
1238         $p{globaldefs} = [parse_section $fh, DDEF_T, $p{header}{ofs_globaldefs}, undef, $p{header}{numglobaldefs}];
1239
1240         print STDERR "Range checking globaldefs...\n";
1241         for(0 .. (@{$p{globaldefs}}-1))
1242         {
1243                 my $g = $p{globaldefs}[$_];
1244                 die "Out of range name in globaldef $_"
1245                         if $g->{s_name} < 0 || $g->{s_name} >= length $p{strings};
1246                 my $name = $p{getstring}->($g->{s_name});
1247                 die "Out of range ofs $g->{ofs} in globaldef $_ (name: \"$name\")"
1248                         if $g->{ofs} >= $p{globals};
1249         }
1250
1251         print STDERR "Parsing fielddefs...\n";
1252         $p{fielddefs} = [parse_section $fh, DDEF_T, $p{header}{ofs_fielddefs}, undef, $p{header}{numfielddefs}];
1253
1254         print STDERR "Range checking fielddefs...\n";
1255         for(0 .. (@{$p{fielddefs}}-1))
1256         {
1257                 my $g = $p{fielddefs}[$_];
1258                 die "Out of range name in fielddef $_"
1259                         if $g->{s_name} < 0 || $g->{s_name} >= length $p{strings};
1260                 my $name = $p{getstring}->($g->{s_name});
1261                 die "Out of range ofs $g->{ofs} in fielddef $_ (name: \"$name\")"
1262                         if $g->{ofs} >= $p{header}{entityfields};
1263         }
1264
1265         print STDERR "Parsing statements...\n";
1266         $p{statements} = [parse_section $fh, DSTATEMENT_T, $p{header}{ofs_statements}, undef, $p{header}{numstatements}];
1267
1268         print STDERR "Parsing functions...\n";
1269         $p{functions} = [parse_section $fh, DFUNCTION_T, $p{header}{ofs_functions}, undef, $p{header}{numfunctions}];
1270
1271         print STDERR "Range checking functions...\n";
1272         for(0 .. (@{$p{functions}} - 1))
1273         {
1274                 my $f = $p{functions}[$_];
1275                 die "Out of range name in function $_"
1276                         if $f->{s_name} < 0 || $f->{s_name} >= length $p{strings};
1277                 my $name = $p{getstring}->($f->{s_name});
1278                 die "Out of range file in function $_"
1279                         if $f->{s_file} < 0 || $f->{s_file} >= length $p{strings};
1280                 my $file = $p{getstring}->($f->{s_file});
1281                 die "Out of range first_statement in function $_ (name: \"$name\", file: \"$file\", first statement: $f->{first_statement})"
1282                         if $f->{first_statement} >= @{$p{statements}};
1283                 if($f->{first_statement} >= 0)
1284                 {
1285                         die "Out of range parm_start in function $_ (name: \"$name\", file: \"$file\", first statement: $f->{first_statement})"
1286                                 if $f->{parm_start} < 0 || $f->{parm_start} >= @{$p{globals}};
1287                         die "Out of range locals in function $_ (name: \"$name\", file: \"$file\", first statement: $f->{first_statement})"
1288                                 if $f->{locals} < 0 || $f->{parm_start} + $f->{locals} > @{$p{globals}};
1289                         die "Out of range numparms $f->{numparms} in function $_ (name: \"$name\", file: \"$file\", first statement: $f->{first_statement})"
1290                                 if $f->{numparms} < 0 || $f->{numparms} > 8;
1291                         my $totalparms = 0;
1292                         for(0..($f->{numparms}-1))
1293                         {
1294                                 die "Out of range parm_size[$_] in function $_ (name: \"$name\", file: \"$file\", first statement: $f->{first_statement})"
1295                                         unless { 0 => 1, 1 => 1, 3 => 1 }->{$f->{parm_size}[$_]};
1296                                 $totalparms += $f->{parm_size}[$_];
1297                         }
1298                         die "Out of range parms in function $_ (name: \"$name\", file: \"$file\", first statement: $f->{first_statement})"
1299                                 if $f->{parm_start} + $totalparms > @{$p{globals}};
1300                         die "More parms than locals in function $_ (name: \"$name\", file: \"$file\", first statement: $f->{first_statement})"
1301                                 if $totalparms > $f->{locals};
1302                 }
1303         }
1304
1305         print STDERR "Range checking statements...\n";
1306         for my $ip(0 .. (@{$p{statements}}-1))
1307         {
1308                 my $s = $p{statements}[$ip];
1309                 my $c = checkop $s->{op};
1310
1311                 for(qw(a b c))
1312                 {
1313                         my $type = $c->{$_};
1314                         next
1315                                 unless defined $type;
1316
1317                         if($type eq 'inglobal' || $type eq 'inglobalfunc')
1318                         {
1319                                 $s->{$_} &= 0xFFFF;
1320                                 die "Out of range global offset in statement $ip - cannot continue"
1321                                         if $s->{$_} >= @{$p{globals}};
1322                         }
1323                         elsif($type eq 'inglobalvec')
1324                         {
1325                                 $s->{$_} &= 0xFFFF;
1326                                 if($c->{isreturn})
1327                                 {
1328                                         die "Out of range global offset in statement $ip - cannot continue"
1329                                                 if $s->{$_} >= @{$p{globals}};
1330                                         print "Potentially out of range global offset in statement $ip - may crash engines"
1331                                                 if $s->{$_} >= @{$p{globals}}-2;
1332                                 }
1333                                 else
1334                                 {
1335                                         die "Out of range global offset in statement $ip - cannot continue"
1336                                                 if $s->{$_} >= @{$p{globals}}-2;
1337                                 }
1338                         }
1339                         elsif($type eq 'outglobal')
1340                         {
1341                                 $s->{$_} &= 0xFFFF;
1342                                 die "Out of range global offset in statement $ip - cannot continue"
1343                                         if $s->{$_} >= @{$p{globals}};
1344                         }
1345                         elsif($type eq 'outglobalvec')
1346                         {
1347                                 $s->{$_} &= 0xFFFF;
1348                                 die "Out of range global offset in statement $ip - cannot continue"
1349                                         if $s->{$_} >= @{$p{globals}}-2;
1350                         }
1351                         elsif($type eq 'ipoffset')
1352                         {
1353                                 die "Out of range GOTO/IF/IFNOT in statement $ip - cannot continue"
1354                                         if $ip + $s->{$_} < 0 || $ip + $s->{$_} >= @{$p{statements}};
1355                         }
1356                 }
1357         }
1358
1359         print STDERR "Looking for error()...\n";
1360         $p{error_func} = {};
1361         for(@{$p{globaldefs}})
1362         {
1363                 next
1364                         if $p{getstring}($_->{s_name}) ne 'error';
1365                 my $v = $p{globals}[$_->{ofs}]{v}{int};
1366                 next
1367                         if $v <= 0 || $v >= @{$p{functions}};
1368                 my $first = $p{functions}[$v]{first_statement};
1369                 next
1370                         if $first >= 0;
1371                 print STDERR "Detected error() at offset $_->{ofs} (builtin #@{[-$first]})\n";
1372                 $p{error_func}{$_->{ofs}} = 1;
1373         }
1374
1375         print STDERR "Scanning functions...\n";
1376         for(@{$p{functions}})
1377         {
1378                 my $file = $p{getstring}->($_->{s_file});
1379                 my $name = $p{getstring}->($_->{s_name});
1380                 $name = "$file:$name"
1381                         if length $file;
1382                 $_->{debugname} = $name;
1383
1384                 next
1385                         if $_->{first_statement} < 0;
1386
1387                 my %statements = ();
1388                 my %come_from = ();
1389                 my %go_to = ();
1390                 my %globals_read = ();
1391                 my %globals_written = ();
1392                 my %globals_used = ();
1393
1394                 if($_->{first_statement} >= 0)
1395                 {
1396                         run_nfa \%p, $_->{first_statement}, "", id, nfa_default_state_checker,
1397                                 sub
1398                                 {
1399                                         my ($ip, $state, $s, $c) = @_;
1400                                         ++$statements{$ip};
1401
1402                                         if(my $j = $c->{isjump})
1403                                         {
1404                                                 my $t = $ip + $s->{$j};
1405                                                 $come_from{$t}{$ip} = $c->{isconditional};
1406                                                 $go_to{$ip}{$t} = $c->{isconditional};
1407                                         }
1408
1409                                         for my $o(qw(a b c))
1410                                         {
1411                                                 my $type = $c->{$o}
1412                                                         or next;
1413                                                 my $ofs = $s->{$o};
1414
1415                                                 my $read = sub
1416                                                 {
1417                                                         my ($ofs) = @_;
1418                                                         $globals_read{$ofs}{$ip}{$o} = 1;
1419                                                         $globals_used{$ofs} = 1;
1420                                                 };
1421                                                 my $write = sub
1422                                                 {
1423                                                         my ($ofs) = @_;
1424                                                         $globals_written{$ofs}{$ip}{$o} = 1;
1425                                                         $globals_used{$ofs} = 1;
1426                                                 };
1427
1428                                                 if($type eq 'inglobal' || $type eq 'inglobalfunc')
1429                                                 {
1430                                                         $read->($ofs);
1431                                                 }
1432                                                 elsif($type eq 'inglobalvec')
1433                                                 {
1434                                                         $read->($ofs);
1435                                                         $read->($ofs+1);
1436                                                         $read->($ofs+2);
1437                                                 }
1438                                                 elsif($type eq 'outglobal')
1439                                                 {
1440                                                         $write->($ofs);
1441                                                 }
1442                                                 elsif($type eq 'outglobalvec')
1443                                                 {
1444                                                         $write->($ofs);
1445                                                         $write->($ofs+1);
1446                                                         $write->($ofs+2);
1447                                                 }
1448                                         }
1449
1450                                         return 0;
1451                                 };
1452                 }
1453
1454                 $_->{statements} = \%statements;
1455                 $_->{come_from} = \%come_from;
1456                 $_->{go_to} = \%go_to;
1457                 $_->{globals_read} = \%globals_read;
1458                 $_->{globals_written} = \%globals_written;
1459                 $_->{globals_used} = \%globals_used;
1460
1461                 # using this info, we could now identify basic blocks
1462         }
1463
1464         print STDERR "Detecting constants and temps, and naming...\n";
1465         detect_constants \%p;
1466
1467         if($ENV{DUMP})
1468         {
1469                 use Data::Dumper;
1470                 print Dumper \%p;
1471                 return;
1472         }
1473
1474         # what do we want to do?
1475         my $checkfunc = \&find_uninitialized_locals;
1476         if($ENV{DISASSEMBLE})
1477         {
1478                 $checkfunc = \&disassemble_function;
1479         }
1480         for(sort { $a->{debugname} cmp $b->{debugname} } @{$p{functions}})
1481         {
1482                 $checkfunc->(\%p, $_);
1483         }
1484 }
1485
1486 for my $progs (@ARGV) {
1487         my $lno = "$progs.lno";
1488         $lno =~ s/\.dat\.lno$/.lno/;
1489
1490         open my $fh, '<', $progs
1491                 or die "$progs: $!";
1492
1493         open my $lnofh, '<', $lno
1494                 or warn "$lno: $!";
1495
1496         parse_progs $fh, $lnofh;
1497 }