28e180a9d46980d10667c568c12fd35c5ac550f2
[openssl.git] / util / mkerr.pl
1 #! /usr/bin/env perl
2 # Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
3 #
4 # Licensed under the OpenSSL license (the "License").  You may not use
5 # this file except in compliance with the License.  You can obtain a copy
6 # in the file LICENSE in the source distribution or at
7 # https://www.openssl.org/source/license.html
8
9 use strict;
10 use warnings;
11
12 my $config       = "crypto/err/openssl.ec";
13 my $debug        = 0;
14 my $internal     = 0;
15 my $nowrite      = 0;
16 my $rebuild      = 0;
17 my $reindex      = 0;
18 my $static       = 0;
19 my $unref        = 0;
20 my %modules         = ();
21
22 my $errors       = 0;
23 my @t            = localtime();
24 my $YEAR         = $t[5] + 1900;
25
26 sub phase
27 {
28     my $text = uc(shift);
29     print STDERR "\n---\n$text\n" if $debug;
30 }
31
32 sub help
33 {
34     print STDERR <<"EOF";
35 mkerr.pl [options] [files...]
36
37 Options:
38
39     -conf FILE  Use the named config file FILE instead of the default.
40
41     -debug      Verbose output debugging on stderr.
42
43     -internal   Generate code that is to be built as part of OpenSSL itself.
44                 Also scans internal list of files.
45
46     -module M   Only useful with -internal!
47                 Only write files for library module M.  Whether files are
48                 actually written or not depends on other options, such as
49                 -rebuild.
50                 Note: this option is cumulative.  If not given at all, all
51                 internal modules will be considered.
52
53     -nowrite    Do not write the header/source files, even if changed.
54
55     -rebuild    Rebuild all header and C source files, even if there
56                 were no changes.
57
58     -reindex    Ignore previously assigned values (except for R records in
59                 the config file) and renumber everything starting at 100.
60
61     -static     Make the load/unload functions static.
62
63     -unref      List all unreferenced function and reason codes on stderr;
64                 implies -nowrite.
65
66     -help       Show this help text.
67
68     ...         Additional arguments are added to the file list to scan,
69                 if '-internal' was NOT specified on the command line.
70
71 EOF
72 }
73
74 while ( @ARGV ) {
75     my $arg = $ARGV[0];
76     last unless $arg =~ /-.*/;
77     $arg = $1 if $arg =~ /-(-.*)/;
78     if ( $arg eq "-conf" ) {
79         $config = $ARGV[1];
80         shift @ARGV;
81     } elsif ( $arg eq "-debug" ) {
82         $debug = 1;
83         $unref = 1;
84     } elsif ( $arg eq "-internal" ) {
85         $internal = 1;
86     } elsif ( $arg eq "-nowrite" ) {
87         $nowrite = 1;
88     } elsif ( $arg eq "-rebuild" ) {
89         $rebuild = 1;
90     } elsif ( $arg eq "-reindex" ) {
91         $reindex = 1;
92     } elsif ( $arg eq "-static" ) {
93         $static = 1;
94     } elsif ( $arg eq "-unref" ) {
95         $unref = 1;
96         $nowrite = 1;
97     } elsif ( $arg eq "-module" ) {
98         shift @ARGV;
99         $modules{uc $ARGV[0]} = 1;
100     } elsif ( $arg =~ /-*h(elp)?/ ) {
101         &help();
102         exit;
103     } elsif ( $arg =~ /-.*/ ) {
104         die "Unknown option $arg; use -h for help.\n";
105     }
106     shift @ARGV;
107 }
108
109 my @source;
110 if ( $internal ) {
111     die "Cannot mix -internal and -static\n" if $static;
112     die "Extra parameters given.\n" if @ARGV;
113     @source = ( glob('crypto/*.c'), glob('crypto/*/*.c'),
114                 glob('ssl/*.c'), glob('ssl/*/*.c') );
115 } else {
116     die "-module isn't useful without -internal\n" if scalar keys %modules > 0;
117     @source = @ARGV;
118 }
119
120 # Data parsed out of the config and state files.
121 my %hinc;       # lib -> header
122 my %libinc;     # header -> lib
123 my %cskip;      # error_file -> lib
124 my %errorfile;  # lib -> error file name
125 my %fmax;       # lib -> max assigned function code
126 my %rmax;       # lib -> max assigned reason code
127 my %fassigned;  # lib -> colon-separated list of assigned function codes
128 my %rassigned;  # lib -> colon-separated list of assigned reason codes
129 my %fnew;       # lib -> count of new function codes
130 my %rnew;       # lib -> count of new reason codes
131 my %rextra;     # "extra" reason code -> lib
132 my %rcodes;     # reason-name -> value
133 my %ftrans;     # old name -> #define-friendly name (all caps)
134 my %fcodes;     # function-name -> value
135 my $statefile;  # state file with assigned reason and function codes
136 my %strings;    # define -> text
137
138 # Read and parse the config file
139 open(IN, "$config") || die "Can't open config file $config, $!,";
140 while ( <IN> ) {
141     next if /^#/ || /^$/;
142     if ( /^L\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
143         my $lib = $1;
144         my $hdr = $2;
145         my $err = $3;
146         $hinc{$lib}   = $hdr;
147         $libinc{$hdr} = $lib;
148         $cskip{$err}  = $lib;
149         next if $err eq 'NONE';
150         $errorfile{$lib} = $err;
151         $fmax{$lib}      = 100;
152         $rmax{$lib}      = 100;
153         $fassigned{$lib} = ":";
154         $rassigned{$lib} = ":";
155         $fnew{$lib}      = 0;
156         $rnew{$lib}      = 0;
157     } elsif ( /^R\s+(\S+)\s+(\S+)/ ) {
158         $rextra{$1} = $2;
159         $rcodes{$1} = $2;
160     } elsif ( /^S\s+(\S+)/ ) {
161         $statefile = $1;
162     } else {
163         die "Illegal config line $_\n";
164     }
165 }
166 close IN;
167
168 my $statefile_prolog = '';
169 if ( ! $statefile ) {
170     $statefile = $config;
171     $statefile =~ s/.ec/.txt/;
172 }
173
174 # The statefile has all the previous assignments.
175 &phase("Reading state");
176 my $skippedstate = 0;
177 if ( ! $reindex && $statefile ) {
178     open(STATE, "<$statefile") || die "Can't open $statefile, $!";
179
180     # Scan function and reason codes and store them: keep a note of the
181     # maximum code used.
182     my $collecting = 1;
183     while ( <STATE> ) {
184         $statefile_prolog .= $_ if $collecting && ( /^#/ || /^$/ );
185         next if /^#/ || /^$/;
186         my $name;
187         my $code;
188         if ( /^(.+):(\d+):\\$/ ) {
189             $name = $1;
190             $code = $2;
191             my $next = <STATE>;
192             $next =~ s/^\s*(.*)\s*$/$1/;
193             die "Duplicate define $name" if exists $strings{$name};
194             $strings{$name} = $next;
195         } elsif ( /^(\S+):(\d+):(.*)$/ ) {
196             $name = $1;
197             $code = $2;
198             die "Duplicate define $name" if exists $strings{$name};
199             $strings{$name} = $3;
200         } else {
201             die "Bad line in $statefile:\n$_\n";
202         }
203         $collecting = 0;
204         my $lib = $name;
205         $lib =~ s/_.*//;
206         $lib = "SSL" if $lib =~ /TLS/;
207         if ( !defined $errorfile{$lib} ) {
208             print "Skipping $_";
209             $skippedstate++;
210             next;
211         }
212         if ( $name =~ /^[A-Z0-9]+_R_/ ) {
213             die "$lib reason code $code collision at $name\n"
214                 if $rassigned{$lib} =~ /:$code:/;
215             $rassigned{$lib} .= "$code:";
216             if ( !exists $rextra{$name} ) {
217                 $rmax{$lib} = $code if $code > $rmax{$lib};
218             }
219             $rcodes{$name} = $code;
220         } elsif ( $name =~ /^[A-Z0-9]+_F_/ ) {
221             die "$lib function code $code collision at $name\n"
222                 if $fassigned{$lib} =~ /:$code:/;
223             $fassigned{$lib} .= "$code:";
224             $fmax{$lib} = $code if $code > $fmax{$lib};
225             $fcodes{$name} = $code;
226         } else {
227             die "Bad line in $statefile:\n$_\n";
228         }
229     }
230     close(STATE);
231
232     if ( $debug ) {
233         foreach my $lib ( sort keys %rmax ) {
234             print STDERR "Reason codes for ${lib}:\n";
235             if ( $rassigned{$lib} =~ m/^:(.*):$/ ) {
236                 my @rassigned = sort { $a <=> $b } split( ":", $1 );
237                 print STDERR "  ", join(' ', @rassigned), "\n";
238             } else {
239                 print STDERR "  --none--\n";
240             }
241         }
242         print STDERR "\n";
243         foreach my $lib ( sort keys %fmax ) {
244             print STDERR "Function codes for ${lib}:\n";
245             if ( $fassigned{$lib} =~ m/^:(.*):$/ ) {
246                 my @fassigned = sort { $a <=> $b } split( ":", $1 );
247                 print STDERR "  ", join(' ', @fassigned), "\n";
248             } else {
249                 print STDERR "  --none--\n";
250             }
251         }
252     }
253 }
254
255 # Scan each header file and make a list of error codes
256 # and function names
257 &phase("Scanning headers");
258 while ( ( my $hdr, my $lib ) = each %libinc ) {
259     next if $hdr eq "NONE";
260     print STDERR " ." if $debug;
261     my $line = "";
262     my $def = "";
263     my $linenr = 0;
264     my $cpp = 0;
265
266     open(IN, "<$hdr") || die "Can't open $hdr, $!,";
267     while ( <IN> ) {
268         $linenr++;
269
270         if ( $line ne '' ) {
271             $_    = $line . $_;
272             $line = '';
273         }
274
275         if ( /\\$/ ) {
276             $line = $_;
277             next;
278         }
279
280         if ( /\/\*/ ) {
281             if ( not /\*\// ) {    # multiline comment...
282                 $line = $_;        # ... just accumulate
283                 next;
284             } else {
285                 s/\/\*.*?\*\///gs;    # wipe it
286             }
287         }
288
289         if ( $cpp ) {
290             $cpp++ if /^#\s*if/;
291             $cpp-- if /^#\s*endif/;
292             next;
293         }
294         $cpp = 1 if /^#.*ifdef.*cplusplus/;    # skip "C" declaration
295
296         next if /^\#/;    # skip preprocessor directives
297
298         s/{[^{}]*}//gs;     # ignore {} blocks
299
300         if ( /\{|\/\*/ ) {    # Add a so editor works...
301             $line = $_;
302         } else {
303             $def .= $_;
304         }
305     }
306
307     # Delete any DECLARE_ macros
308     my $defnr = 0;
309     $def =~ s/DECLARE_\w+\([\w,\s]+\)//gs;
310     foreach ( split /;/, $def ) {
311         $defnr++;
312         # The goal is to collect function names from function declarations.
313
314         s/^[\n\s]*//g;
315         s/[\n\s]*$//g;
316
317         # Skip over recognized non-function declarations
318         next if /typedef\W/ or /DECLARE_STACK_OF/ or /TYPEDEF_.*_OF/;
319
320         # Remove STACK_OF(foo)
321         s/STACK_OF\(\w+\)/void/;
322
323         # Reduce argument lists to empty ()
324         # fold round brackets recursively: (t(*v)(t),t) -> (t{}{},t) -> {}
325         while ( /\(.*\)/s ) {
326             s/\([^\(\)]+\)/\{\}/gs;
327             s/\(\s*\*\s*(\w+)\s*\{\}\s*\)/$1/gs;    #(*f{}) -> f
328         }
329
330         # pretend as we didn't use curly braces: {} -> ()
331         s/\{\}/\(\)/gs;
332
333         # Last token just before the first () is a function name.
334         if ( /(\w+)\s*\(\).*/s ) {
335             my $name = $1;
336             $name =~ tr/[a-z]/[A-Z]/;
337             $ftrans{$name} = $1;
338         } elsif ( /[\(\)]/ and not(/=/) ) {
339             print STDERR "Header $hdr: cannot parse: $_;\n";
340         }
341     }
342
343     next if $reindex;
344
345     if ( $lib eq "SSL" && $rmax{$lib} >= 1000 ) {
346         print STDERR "SSL error codes 1000+ are reserved for alerts.\n";
347         print STDERR "Any new alerts must be added to $config.\n";
348         $errors++;
349     }
350     close IN;
351 }
352 print STDERR "\n" if $debug;
353
354 # Scan each C source file and look for function and reason codes
355 # This is done by looking for strings that "look like" function or
356 # reason codes: basically anything consisting of all upper case and
357 # numerics which has _F_ or _R_ in it and which has the name of an
358 # error library at the start.  This seems to work fine except for the
359 # oddly named structure BIO_F_CTX which needs to be ignored.
360 # If a code doesn't exist in list compiled from headers then mark it
361 # with the value "X" as a place holder to give it a value later.
362 # Store all function and reason codes found in %usedfuncs and %usedreasons
363 # so all those unreferenced can be printed out.
364 &phase("Scanning source");
365 my %usedfuncs;
366 my %usedreasons;
367 foreach my $file ( @source ) {
368     # Don't parse the error source file.
369     next if exists $cskip{$file};
370     open( IN, "<$file" ) || die "Can't open $file, $!,";
371     my $func;
372     my $linenr = 0;
373     print STDERR "$file:\n" if $debug;
374     while ( <IN> ) {
375
376         # skip obsoleted source files entirely!
377         last if /^#error\s+obsolete/;
378         $linenr++;
379         if ( !/;$/ && /^\**([a-zA-Z_].*[\s*])?([A-Za-z_0-9]+)\(.*([),]|$)/ ) {
380             /^([^()]*(\([^()]*\)[^()]*)*)\(/;
381             $1 =~ /([A-Za-z_0-9]*)$/;
382             $func = $1;
383         }
384
385         if ( /(([A-Z0-9]+)_F_([A-Z0-9_]+))/ ) {
386             next unless exists $errorfile{$2};
387             next if $1 eq "BIO_F_BUFFER_CTX";
388             $usedfuncs{$1} = 1;
389             if ( !exists $fcodes{$1} ) {
390                 print STDERR "  New function $1\n" if $debug;
391                 $fcodes{$1} = "X";
392                 $fnew{$2}++;
393             }
394             $ftrans{$3} = $func unless exists $ftrans{$3};
395             if ( uc($func) ne $3 ) {
396                 print STDERR "ERROR: mismatch $file:$linenr $func:$3\n";
397                 $errors++;
398             }
399             print STDERR "  Function $1 = $fcodes{$1}\n"
400               if $debug;
401         }
402         if ( /(([A-Z0-9]+)_R_[A-Z0-9_]+)/ ) {
403             next unless exists $errorfile{$2};
404             $usedreasons{$1} = 1;
405             if ( !exists $rcodes{$1} ) {
406                 print STDERR "  New reason $1\n" if $debug;
407                 $rcodes{$1} = "X";
408                 $rnew{$2}++;
409             }
410             print STDERR "  Reason $1 = $rcodes{$1}\n" if $debug;
411         }
412     }
413     close IN;
414 }
415 print STDERR "\n" if $debug;
416
417 # Now process each library in turn.
418 &phase("Writing files");
419 my $newstate = 0;
420 foreach my $lib ( keys %errorfile ) {
421     if ( ! $fnew{$lib} && ! $rnew{$lib} ) {
422         next unless $rebuild;
423     }
424     next if scalar keys %modules > 0 && !$modules{$lib};
425     next if $nowrite;
426     print STDERR "$lib: $fnew{$lib} new functions\n" if $fnew{$lib};
427     print STDERR "$lib: $rnew{$lib} new reasons\n" if $rnew{$lib};
428     $newstate = 1;
429
430     # If we get here then we have some new error codes so we
431     # need to rebuild the header file and C file.
432
433     # Make a sorted list of error and reason codes for later use.
434     my @function = sort grep( /^${lib}_/, keys %fcodes );
435     my @reasons  = sort grep( /^${lib}_/, keys %rcodes );
436
437     # Rewrite the header file
438
439     my $hfile = $hinc{$lib};
440     $hfile =~ s/.h$/err.h/ if $internal;
441     open( OUT, ">$hfile" ) || die "Can't write to $hfile, $!,";
442     print OUT <<"EOF";
443 /*
444  * Generated by util/mkerr.pl DO NOT EDIT
445  * Copyright 1995-$YEAR The OpenSSL Project Authors. All Rights Reserved.
446  *
447  * Licensed under the OpenSSL license (the \"License\").  You may not use
448  * this file except in compliance with the License.  You can obtain a copy
449  * in the file LICENSE in the source distribution or at
450  * https://www.openssl.org/source/license.html
451  */
452
453 #ifndef HEADER_${lib}ERR_H
454 # define HEADER_${lib}ERR_H
455
456 EOF
457     if ( $internal ) {
458         # Declare the load function because the generate C file
459         # includes "fooerr.h" not "foo.h"
460         print OUT <<"EOF";
461 # ifdef  __cplusplus
462 extern \"C\" {
463 # endif
464 int ERR_load_${lib}_strings(void);
465 # ifdef  __cplusplus
466 }
467 # endif
468 EOF
469     } else {
470         print OUT <<"EOF";
471 # define ${lib}err(f, r) ERR_${lib}_error((f), (r), OPENSSL_FILE, OPENSSL_LINE)
472
473 EOF
474         if ( ! $static ) {
475             print OUT <<"EOF";
476
477 # ifdef  __cplusplus
478 extern \"C\" {
479 # endif
480 int ERR_load_${lib}_strings(void);
481 void ERR_unload_${lib}_strings(void);
482 void ERR_${lib}_error(int function, int reason, char *file, int line);
483 # ifdef  __cplusplus
484 }
485 # endif
486 EOF
487         }
488     }
489
490     print OUT "\n/*\n * $lib function codes.\n */\n";
491     foreach my $i ( @function ) {
492         my $z = 48 - length($i);
493         if ( $fcodes{$i} eq "X" ) {
494             $fassigned{$lib} =~ m/^:([^:]*):/;
495             my $findcode = $1;
496             $findcode = $fmax{$lib} if !defined $findcode;
497             while ( $fassigned{$lib} =~ m/:$findcode:/ ) {
498                 $findcode++;
499             }
500             $fcodes{$i} = $findcode;
501             $fassigned{$lib} .= "$findcode:";
502             print STDERR "New Function code $i\n" if $debug;
503         }
504         printf OUT "# define $i%s $fcodes{$i}\n", " " x $z;
505     }
506
507     print OUT "\n/*\n * $lib reason codes.\n */\n";
508     foreach my $i ( @reasons ) {
509         my $z = 48 - length($i);
510         if ( $rcodes{$i} eq "X" ) {
511             $rassigned{$lib} =~ m/^:([^:]*):/;
512             my $findcode = $1;
513             $findcode = $rmax{$lib} if !defined $findcode;
514             while ( $rassigned{$lib} =~ m/:$findcode:/ ) {
515                 $findcode++;
516             }
517             $rcodes{$i} = $findcode;
518             $rassigned{$lib} .= "$findcode:";
519             print STDERR "New Reason code $i\n" if $debug;
520         }
521         printf OUT "# define $i%s $rcodes{$i}\n", " " x $z;
522     }
523     print OUT "\n";
524
525     print OUT "#endif\n";
526
527     # Rewrite the C source file containing the error details.
528
529     # First, read any existing reason string definitions:
530     my $cfile = $errorfile{$lib};
531     my $pack_lib = $internal ? "ERR_LIB_${lib}" : "0";
532     my $hincf = $hfile;
533     $hincf =~ s|.*include/||;
534     if ( $hincf =~ m|^openssl/| ) {
535         $hincf = "<${hincf}>";
536     } else {
537         $hincf = "\"${hincf}\"";
538     }
539
540     open( OUT, ">$cfile" )
541         || die "Can't open $cfile for writing, $!, stopped";
542
543     my $const = $internal ? 'const ' : '';
544
545     print OUT <<"EOF";
546 /*
547  * Generated by util/mkerr.pl DO NOT EDIT
548  * Copyright 1995-$YEAR The OpenSSL Project Authors. All Rights Reserved.
549  *
550  * Licensed under the OpenSSL license (the "License").  You may not use
551  * this file except in compliance with the License.  You can obtain a copy
552  * in the file LICENSE in the source distribution or at
553  * https://www.openssl.org/source/license.html
554  */
555
556 #include <openssl/err.h>
557 #include $hincf
558
559 #ifndef OPENSSL_NO_ERR
560
561 static ${const}ERR_STRING_DATA ${lib}_str_functs[] = {
562 EOF
563
564     # Add each function code: if a function name is found then use it.
565     foreach my $i ( @function ) {
566         my $fn;
567         if ( exists $strings{$i} and $strings{$i} ne '' ) {
568             $fn = $strings{$i};
569             $fn = "" if $fn eq '*';
570         } else {
571             $i =~ /^${lib}_F_(\S+)$/;
572             $fn = $1;
573             $fn = $ftrans{$fn} if exists $ftrans{$fn};
574             $strings{$i} = $fn;
575         }
576         my $short = "    {ERR_PACK($pack_lib, $i, 0), \"$fn\"},";
577         if ( length($short) <= 80 ) {
578             print OUT "$short\n";
579         } else {
580             print OUT "    {ERR_PACK($pack_lib, $i, 0),\n     \"$fn\"},\n";
581         }
582     }
583     print OUT <<"EOF";
584     {0, NULL}
585 };
586
587 static ${const}ERR_STRING_DATA ${lib}_str_reasons[] = {
588 EOF
589
590     # Add each reason code.
591     foreach my $i ( @reasons ) {
592         my $rn;
593         if ( exists $strings{$i} ) {
594             $rn = $strings{$i};
595             $rn = "" if $rn eq '*';
596         } else {
597             $i =~ /^${lib}_R_(\S+)$/;
598             $rn = $1;
599             $rn =~ tr/_[A-Z]/ [a-z]/;
600             $strings{$i} = $rn;
601         }
602         my $short = "    {ERR_PACK($pack_lib, 0, $i), \"$rn\"},";
603         if ( length($short) <= 80 ) {
604             print OUT "$short\n";
605         } else {
606             print OUT "    {ERR_PACK($pack_lib, 0, $i),\n    \"$rn\"},\n";
607         }
608     }
609     print OUT <<"EOF";
610     {0, NULL}
611 };
612
613 #endif
614 EOF
615     if ( $internal ) {
616         print OUT <<"EOF";
617
618 int ERR_load_${lib}_strings(void)
619 {
620 #ifndef OPENSSL_NO_ERR
621     if (ERR_func_error_string(${lib}_str_functs[0].error) == NULL) {
622         ERR_load_strings_const(${lib}_str_functs);
623         ERR_load_strings_const(${lib}_str_reasons);
624     }
625 #endif
626     return 1;
627 }
628 EOF
629     } else {
630         my $st = $static ? "static " : "";
631         print OUT <<"EOF";
632
633 static int lib_code = 0;
634 static int error_loaded = 0;
635
636 ${st}int ERR_load_${lib}_strings(void)
637 {
638     if (lib_code == 0)
639         lib_code = ERR_get_next_error_library();
640
641     if (!error_loaded) {
642 #ifndef OPENSSL_NO_ERR
643         ERR_load_strings(lib_code, ${lib}_str_functs);
644         ERR_load_strings(lib_code, ${lib}_str_reasons);
645 #endif
646         error_loaded = 1;
647     }
648     return 1;
649 }
650
651 ${st}void ERR_unload_${lib}_strings(void)
652 {
653     if (error_loaded) {
654 #ifndef OPENSSL_NO_ERR
655         ERR_unload_strings(lib_code, ${lib}_str_functs);
656         ERR_unload_strings(lib_code, ${lib}_str_reasons);
657 #endif
658         error_loaded = 0;
659     }
660 }
661
662 ${st}void ERR_${lib}_error(int function, int reason, char *file, int line)
663 {
664     if (lib_code == 0)
665         lib_code = ERR_get_next_error_library();
666     ERR_PUT_error(lib_code, function, reason, file, line);
667 }
668 EOF
669
670     }
671
672     close OUT;
673 }
674
675 &phase("Ending");
676 # Make a list of unreferenced function and reason codes
677 if ( $unref ) {
678     my @funref;
679     foreach ( keys %fcodes ) {
680         push( @funref, $_ ) unless exists $usedfuncs{$_};
681     }
682     my @runref;
683     foreach ( keys %rcodes ) {
684         push( @runref, $_ ) unless exists $usedreasons{$_};
685     }
686     if ( @funref ) {
687         print STDERR "The following function codes were not referenced:\n";
688         foreach ( sort @funref ) {
689             print STDERR "  $_\n";
690         }
691     }
692     if ( @runref ) {
693         print STDERR "The following reason codes were not referenced:\n";
694         foreach ( sort @runref ) {
695             print STDERR "  $_\n";
696         }
697     }
698 }
699
700 die "Found $errors errors, quitting" if $errors;
701
702 # Update the state file
703 if ( $newstate )  {
704     open(OUT, ">$statefile.new")
705         || die "Can't write $statefile.new, $!";
706     print OUT $statefile_prolog;
707     print OUT "# Function codes\n";
708     foreach my $i ( sort keys %fcodes ) {
709         my $short = "$i:$fcodes{$i}:";
710         my $t = exists $strings{$i} ? $strings{$i} : "";
711         $t = "\\\n\t" . $t if length($short) + length($t) > 80;
712         print OUT "$short$t\n";
713     }
714     print OUT "\n#Reason codes\n";
715     foreach my $i ( sort keys %rcodes ) {
716         my $short = "$i:$rcodes{$i}:";
717         my $t = exists $strings{$i} ? "$strings{$i}" : "";
718         $t = "\\\n\t" . $t if length($short) + length($t) > 80;
719         print OUT "$short$t\n" if !exists $rextra{$i};
720     }
721     close(OUT);
722     if ( $skippedstate ) {
723         print "Skipped state, leaving update in $statefile.new";
724     } else {
725         rename "$statefile", "$statefile.old"
726             || die "Can't backup $statefile to $statefile.old, $!";
727         rename "$statefile.new", "$statefile"
728             || die "Can't rename $statefile to $statefile.new, $!";
729     }
730 }
731
732 exit;