Add a simple method to run regression tests
[openssl.git] / util / mkdef.pl
1 #! /usr/bin/env perl
2 # Copyright 1995-2018 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 #
10 # generate a .def file
11 #
12 # It does this by parsing the header files and looking for the
13 # prototyped functions: it then prunes the output.
14 #
15 # Intermediary files are created, call libcrypto.num and libssl.num,
16 # The format of these files is:
17 #
18 #       routine-name    nnnn    vers    info
19 #
20 # The "nnnn" and "vers" fields are the numeric id and version for the symbol
21 # respectively. The "info" part is actually a colon-separated string of fields
22 # with the following meaning:
23 #
24 #       existence:platform:kind:algorithms
25 #
26 # - "existence" can be "EXIST" or "NOEXIST" depending on if the symbol is
27 #   found somewhere in the source,
28 # - "platforms" is empty if it exists on all platforms, otherwise it contains
29 #   comma-separated list of the platform, just as they are if the symbol exists
30 #   for those platforms, or prepended with a "!" if not.  This helps resolve
31 #   symbol name variants for platforms where the names are too long for the
32 #   compiler or linker, or if the systems is case insensitive and there is a
33 #   clash, or the symbol is implemented differently (see
34 #   EXPORT_VAR_AS_FUNCTION).  This script assumes renaming of symbols is found
35 #   in the file crypto/symhacks.h.
36 #   The semantics for the platforms is that every item is checked against the
37 #   environment.  For the negative items ("!FOO"), if any of them is false
38 #   (i.e. "FOO" is true) in the environment, the corresponding symbol can't be
39 #   used.  For the positive items, if all of them are false in the environment,
40 #   the corresponding symbol can't be used.  Any combination of positive and
41 #   negative items are possible, and of course leave room for some redundancy.
42 # - "kind" is "FUNCTION" or "VARIABLE".  The meaning of that is obvious.
43 # - "algorithms" is a comma-separated list of algorithm names.  This helps
44 #   exclude symbols that are part of an algorithm that some user wants to
45 #   exclude.
46 #
47
48 use lib ".";
49 use configdata;
50 use File::Spec::Functions;
51 use File::Basename;
52 use FindBin;
53 use lib "$FindBin::Bin/perl";
54 use OpenSSL::Glob;
55
56 # When building a "variant" shared library, with a custom SONAME, also customize
57 # all the symbol versions.  This produces a shared object that can coexist
58 # without conflict in the same address space as a default build, or an object
59 # with a different variant tag.
60 #
61 # For example, with a target definition that includes:
62 #
63 #         shlib_variant => "-opt",
64 #
65 # we build the following objects:
66 #
67 # $ perl -le '
68 #     for (@ARGV) {
69 #         if ($l = readlink) {
70 #             printf "%s -> %s\n", $_, $l
71 #         } else {
72 #             print
73 #         }
74 #     }' *.so*
75 # libcrypto-opt.so.1.1
76 # libcrypto.so -> libcrypto-opt.so.1.1
77 # libssl-opt.so.1.1
78 # libssl.so -> libssl-opt.so.1.1
79 #
80 # whose SONAMEs and dependencies are:
81 #
82 # $ for l in *.so; do
83 #     echo $l
84 #     readelf -d $l | egrep 'SONAME|NEEDED.*(ssl|crypto)'
85 #   done
86 # libcrypto.so
87 #  0x000000000000000e (SONAME)             Library soname: [libcrypto-opt.so.1.1]
88 # libssl.so
89 #  0x0000000000000001 (NEEDED)             Shared library: [libcrypto-opt.so.1.1]
90 #  0x000000000000000e (SONAME)             Library soname: [libssl-opt.so.1.1]
91 #
92 # We case-fold the variant tag to upper case and replace all non-alnum
93 # characters with "_".  This yields the following symbol versions:
94 #
95 # $ nm libcrypto.so | grep -w A
96 # 0000000000000000 A OPENSSL_OPT_1_1_0
97 # 0000000000000000 A OPENSSL_OPT_1_1_0a
98 # 0000000000000000 A OPENSSL_OPT_1_1_0c
99 # 0000000000000000 A OPENSSL_OPT_1_1_0d
100 # 0000000000000000 A OPENSSL_OPT_1_1_0f
101 # 0000000000000000 A OPENSSL_OPT_1_1_0g
102 # $ nm libssl.so | grep -w A
103 # 0000000000000000 A OPENSSL_OPT_1_1_0
104 # 0000000000000000 A OPENSSL_OPT_1_1_0d
105 #
106 (my $SO_VARIANT = qq{\U$target{"shlib_variant"}}) =~ s/\W/_/g;
107
108 my $debug=0;
109 my $trace=0;
110 my $verbose=0;
111
112 my $crypto_num= catfile($config{sourcedir},"util","libcrypto.num");
113 my $ssl_num=    catfile($config{sourcedir},"util","libssl.num");
114 my $libname;
115
116 my $do_update = 0;
117 my $do_rewrite = 1;
118 my $do_crypto = 0;
119 my $do_ssl = 0;
120 my $do_ctest = 0;
121 my $do_ctestall = 0;
122 my $do_checkexist = 0;
123
124 my $VMS=0;
125 my $W32=0;
126 my $NT=0;
127 my $UNIX=0;
128 my $linux=0;
129 # Set this to make typesafe STACK definitions appear in DEF
130 my $safe_stack_def = 0;
131
132 my @known_platforms = ( "__FreeBSD__", "PERL5",
133                         "EXPORT_VAR_AS_FUNCTION", "ZLIB", "_WIN32"
134                         );
135 my @known_ossl_platforms = ( "UNIX", "VMS", "WIN32", "WINNT", "OS2" );
136 my @known_algorithms = ( # These are algorithms we know are guarded in relevant
137                          # header files, but aren't actually disablable.
138                          # Without these, this script will warn a lot.
139                          "RSA", "MD5",
140                          # @disablables comes from configdata.pm
141                          map { (my $x = uc $_) =~ s|-|_|g; $x; } @disablables,
142                          # Deprecated functions.  Not really algorithmss, but
143                          # treated as such here for the sake of simplicity
144                          "DEPRECATEDIN_0_9_8",
145                          "DEPRECATEDIN_1_0_0",
146                          "DEPRECATEDIN_1_1_0",
147                          "DEPRECATEDIN_1_2_0",
148                      );
149
150 # %disabled comes from configdata.pm
151 my %disabled_algorithms =
152     map { (my $x = uc $_) =~ s|-|_|g; $x => 1; } keys %disabled;
153
154 my $apiv = sprintf "%x%02x%02x", split(/\./, $config{api});
155 foreach (@known_algorithms) {
156         if (/^DEPRECATEDIN_(\d+)_(\d+)_(\d+)$/) {
157                 my $depv = sprintf "%x%02x%02x", $1, $2, $3;
158                 $disabled_algorithms{$_} = 1 if $apiv ge $depv;
159         }
160 }
161
162 my $zlib;
163
164 foreach (@ARGV, split(/ /, $config{options}))
165         {
166         $debug=1 if $_ eq "debug";
167         $trace=1 if $_ eq "trace";
168         $verbose=1 if $_ eq "verbose";
169         $W32=1 if $_ eq "32";
170         die "win16 not supported" if $_ eq "16";
171         if($_ eq "NT") {
172                 $W32 = 1;
173                 $NT = 1;
174         }
175         if ($_ eq "linux") {
176                 $linux=1;
177                 $UNIX=1;
178         }
179         $VMS=1 if $_ eq "VMS";
180         if ($_ eq "zlib" || $_ eq "enable-zlib" || $_ eq "zlib-dynamic"
181                          || $_ eq "enable-zlib-dynamic") {
182                 $zlib = 1;
183         }
184
185         $do_crypto=1 if $_ eq "libcrypto" || $_ eq "crypto";
186         $do_ssl=1 if $_ eq "libssl" || $_ eq "ssl";
187
188         $do_update=1 if $_ eq "update";
189         $do_rewrite=1 if $_ eq "rewrite";
190         $do_ctest=1 if $_ eq "ctest";
191         $do_ctestall=1 if $_ eq "ctestall";
192         $do_checkexist=1 if $_ eq "exist";
193         }
194 $libname = $unified_info{sharednames}->{libcrypto} if $do_crypto;
195 $libname = $unified_info{sharednames}->{libssl} if $do_ssl;
196
197 if (!$libname) {
198         if ($do_ssl) {
199                 $libname="LIBSSL";
200         }
201         if ($do_crypto) {
202                 $libname="LIBCRYPTO";
203         }
204 }
205
206 # If no platform is given, assume WIN32
207 if ($W32 + $VMS + $linux == 0) {
208         $W32 = 1;
209 }
210 die "Please, only one platform at a time"
211     if ($W32 + $VMS + $linux > 1);
212
213 if (!$do_ssl && !$do_crypto)
214         {
215         print STDERR "usage: $0 ( ssl | crypto ) [ 16 | 32 | NT | OS2 | linux | VMS ]\n";
216         exit(1);
217         }
218
219 %ssl_list=&load_numbers($ssl_num);
220 $max_ssl = $max_num;
221 %crypto_list=&load_numbers($crypto_num);
222 $max_crypto = $max_num;
223
224 my $ssl="include/openssl/ssl.h";
225 $ssl.=" include/openssl/sslerr.h";
226 $ssl.=" include/openssl/tls1.h";
227 $ssl.=" include/openssl/srtp.h";
228
229 # When scanning include/openssl, skip all SSL files and some internal ones.
230 my %skipthese;
231 foreach my $f ( split(/\s+/, $ssl) ) {
232     $skipthese{$f} = 1;
233 }
234 $skipthese{'include/openssl/conf_api.h'} = 1;
235 $skipthese{'include/openssl/ebcdic.h'} = 1;
236 $skipthese{'include/openssl/opensslconf.h'} = 1;
237
238 # We use headers found in include/openssl and include/internal only.
239 # The latter is needed so libssl.so/.dll/.exe can link properly.
240 my $crypto ="include/internal/dso.h";
241 $crypto.=" include/internal/o_dir.h";
242 $crypto.=" include/internal/o_str.h";
243 $crypto.=" include/internal/err.h";
244 foreach my $f ( glob(catfile($config{sourcedir},'include/openssl/*.h')) ) {
245     my $fn = "include/openssl/" . lc(basename($f));
246     $crypto .= " $fn" if !defined $skipthese{$fn};
247 }
248
249 my $symhacks="include/openssl/symhacks.h";
250
251 my @ssl_symbols = &do_defs("LIBSSL", $ssl, $symhacks);
252 my @crypto_symbols = &do_defs("LIBCRYPTO", $crypto, $symhacks);
253
254 if ($do_update) {
255
256 if ($do_ssl == 1) {
257
258         &maybe_add_info("LIBSSL",*ssl_list,@ssl_symbols);
259         if ($do_rewrite == 1) {
260                 open(OUT, ">$ssl_num");
261                 &rewrite_numbers(*OUT,"LIBSSL",*ssl_list,@ssl_symbols);
262         } else {
263                 open(OUT, ">>$ssl_num");
264         }
265         &update_numbers(*OUT,"LIBSSL",*ssl_list,$max_ssl,@ssl_symbols);
266         close OUT;
267 }
268
269 if($do_crypto == 1) {
270
271         &maybe_add_info("LIBCRYPTO",*crypto_list,@crypto_symbols);
272         if ($do_rewrite == 1) {
273                 open(OUT, ">$crypto_num");
274                 &rewrite_numbers(*OUT,"LIBCRYPTO",*crypto_list,@crypto_symbols);
275         } else {
276                 open(OUT, ">>$crypto_num");
277         }
278         &update_numbers(*OUT,"LIBCRYPTO",*crypto_list,$max_crypto,@crypto_symbols);
279         close OUT;
280 }
281
282 } elsif ($do_checkexist) {
283         &check_existing(*ssl_list, @ssl_symbols)
284                 if $do_ssl == 1;
285         &check_existing(*crypto_list, @crypto_symbols)
286                 if $do_crypto == 1;
287 } elsif ($do_ctest || $do_ctestall) {
288
289         print <<"EOF";
290
291 /* Test file to check all DEF file symbols are present by trying
292  * to link to all of them. This is *not* intended to be run!
293  */
294
295 int main()
296 {
297 EOF
298         &print_test_file(*STDOUT,"LIBSSL",*ssl_list,$do_ctestall,@ssl_symbols)
299                 if $do_ssl == 1;
300
301         &print_test_file(*STDOUT,"LIBCRYPTO",*crypto_list,$do_ctestall,@crypto_symbols)
302                 if $do_crypto == 1;
303
304         print "}\n";
305
306 } else {
307
308         &print_def_file(*STDOUT,$libname,*ssl_list,@ssl_symbols)
309                 if $do_ssl == 1;
310
311         &print_def_file(*STDOUT,$libname,*crypto_list,@crypto_symbols)
312                 if $do_crypto == 1;
313
314 }
315
316
317 sub do_defs
318 {
319         my($name,$files,$symhacksfile)=@_;
320         my $file;
321         my @ret;
322         my %syms;
323         my %platform;           # For anything undefined, we assume ""
324         my %kind;               # For anything undefined, we assume "FUNCTION"
325         my %algorithm;          # For anything undefined, we assume ""
326         my %variant;
327         my %variant_cnt;        # To be able to allocate "name{n}" if "name"
328                                 # is the same name as the original.
329         my $cpp;
330         my %unknown_algorithms = ();
331         my $parens = 0;
332
333         foreach $file (split(/\s+/,$symhacksfile." ".$files))
334                 {
335                 my $fn = catfile($config{sourcedir},$file);
336                 print STDERR "DEBUG: starting on $fn:\n" if $debug;
337                 print STDERR "TRACE: start reading $fn\n" if $trace;
338                 open(IN,"<$fn") || die "Can't open $fn, $!,";
339                 my $line = "", my $def= "";
340                 my %tag = (
341                         (map { $_ => 0 } @known_platforms),
342                         (map { "OPENSSL_SYS_".$_ => 0 } @known_ossl_platforms),
343                         (map { "OPENSSL_NO_".$_ => 0 } @known_algorithms),
344                         (map { "OPENSSL_USE_".$_ => 0 } @known_algorithms),
345                         (grep /^DEPRECATED_/, @known_algorithms),
346                         NOPROTO         => 0,
347                         PERL5           => 0,
348                         _WINDLL         => 0,
349                         CONST_STRICT    => 0,
350                         TRUE            => 1,
351                 );
352                 my $symhacking = $file eq $symhacksfile;
353                 my @current_platforms = ();
354                 my @current_algorithms = ();
355
356                 # params: symbol, alias, platforms, kind
357                 # The reason to put this subroutine in a variable is that
358                 # it will otherwise create it's own, unshared, version of
359                 # %tag and %variant...
360                 my $make_variant = sub
361                 {
362                         my ($s, $a, $p, $k) = @_;
363                         my ($a1, $a2);
364
365                         print STDERR "DEBUG: make_variant: Entered with ",$s,", ",$a,", ",(defined($p)?$p:""),", ",(defined($k)?$k:""),"\n" if $debug;
366                         if (defined($p))
367                         {
368                                 $a1 = join(",",$p,
369                                            grep(!/^$/,
370                                                 map { $tag{$_} == 1 ? $_ : "" }
371                                                 @known_platforms));
372                         }
373                         else
374                         {
375                                 $a1 = join(",",
376                                            grep(!/^$/,
377                                                 map { $tag{$_} == 1 ? $_ : "" }
378                                                 @known_platforms));
379                         }
380                         $a2 = join(",",
381                                    grep(!/^$/,
382                                         map { $tag{"OPENSSL_SYS_".$_} == 1 ? $_ : "" }
383                                         @known_ossl_platforms));
384                         print STDERR "DEBUG: make_variant: a1 = $a1; a2 = $a2\n" if $debug;
385                         if ($a1 eq "") { $a1 = $a2; }
386                         elsif ($a1 ne "" && $a2 ne "") { $a1 .= ",".$a2; }
387                         if ($a eq $s)
388                         {
389                                 if (!defined($variant_cnt{$s}))
390                                 {
391                                         $variant_cnt{$s} = 0;
392                                 }
393                                 $variant_cnt{$s}++;
394                                 $a .= "{$variant_cnt{$s}}";
395                         }
396                         my $toadd = $a.":".$a1.(defined($k)?":".$k:"");
397                         my $togrep = $s.'(\{[0-9]+\})?:'.$a1.(defined($k)?":".$k:"");
398                         if (!grep(/^$togrep$/,
399                                   split(/;/, defined($variant{$s})?$variant{$s}:""))) {
400                                 if (defined($variant{$s})) { $variant{$s} .= ";"; }
401                                 $variant{$s} .= $toadd;
402                         }
403                         print STDERR "DEBUG: make_variant: Exit with variant of ",$s," = ",$variant{$s},"\n" if $debug;
404                 };
405
406                 print STDERR "DEBUG: parsing ----------\n" if $debug;
407                 while(<IN>) {
408                         s|\R$||; # Better chomp
409                         if($parens > 0) {
410                                 #Inside a DEPRECATEDIN
411                                 $stored_multiline .= $_;
412                                 print STDERR "DEBUG: Continuing multiline DEPRECATEDIN: $stored_multiline\n" if $debug;
413                                 $parens = count_parens($stored_multiline);
414                                 if ($parens == 0) {
415                                         $def .= do_deprecated($stored_multiline,
416                                                         \@current_platforms,
417                                                         \@current_algorithms);
418                                 }
419                                 next;
420                         }
421                         if (/\/\* Error codes for the \w+ functions\. \*\//)
422                                 {
423                                 undef @tag;
424                                 last;
425                                 }
426                         if ($line ne '') {
427                                 $_ = $line . $_;
428                                 $line = '';
429                         }
430
431                         if (/\\$/) {
432                                 $line = $`; # keep what was before the backslash
433                                 next;
434                         }
435
436                         if(/\/\*/) {
437                                 if (not /\*\//) {       # multi-line comment...
438                                         $line = $_;     # ... just accumulate
439                                         next;
440                                 } else {
441                                         s/\/\*.*?\*\///gs;# wipe it
442                                 }
443                         }
444
445                         if ($cpp) {
446                                 $cpp++ if /^#\s*if/;
447                                 $cpp-- if /^#\s*endif/;
448                                 next;
449                         }
450                         if (/^#.*ifdef.*cplusplus/) {
451                                 $cpp = 1;
452                                 next;
453                         }
454
455                         s/{[^{}]*}//gs;                      # ignore {} blocks
456                         print STDERR "DEBUG: \$def=\"$def\"\n" if $debug && $def ne "";
457                         print STDERR "DEBUG: \$_=\"$_\"\n" if $debug;
458                         if (/^\#\s*if\s+OPENSSL_API_COMPAT\s*(\S)\s*(0x[0-9a-fA-F]{8})L\s*$/) {
459                                 my $op = $1;
460                                 my $v = hex($2);
461                                 if ($op ne '<' && $op ne '>=') {
462                                     die "$file unacceptable operator $op: $_\n";
463                                 }
464                                 my ($one, $major, $minor) =
465                                     ( ($v >> 28) & 0xf,
466                                       ($v >> 20) & 0xff,
467                                       ($v >> 12) & 0xff );
468                                 my $t = "DEPRECATEDIN_${one}_${major}_${minor}";
469                                 push(@tag,"-");
470                                 push(@tag,$t);
471                                 $tag{$t}=($op eq '<' ? 1 : -1);
472                                 print STDERR "DEBUG: $file: found tag $t = $tag{$t}\n" if $debug;
473                         } elsif (/^\#\s*ifndef\s+(.*)/) {
474                                 push(@tag,"-");
475                                 push(@tag,$1);
476                                 $tag{$1}=-1;
477                                 print STDERR "DEBUG: $file: found tag $1 = -1\n" if $debug;
478                         } elsif (/^\#\s*if\s+!defined\s*\(([^\)]+)\)/) {
479                                 push(@tag,"-");
480                                 if (/^\#\s*if\s+(!defined\s*\(([^\)]+)\)(\s+\&\&\s+!defined\s*\(([^\)]+)\))*)$/) {
481                                         my $tmp_1 = $1;
482                                         my $tmp_;
483                                         foreach $tmp_ (split '\&\&',$tmp_1) {
484                                                 $tmp_ =~ /!defined\s*\(([^\)]+)\)/;
485                                                 print STDERR "DEBUG: $file: found tag $1 = -1\n" if $debug;
486                                                 push(@tag,$1);
487                                                 $tag{$1}=-1;
488                                         }
489                                 } else {
490                                         print STDERR "Warning: $file: taking only '!defined($1)' of complicated expression: $_" if $verbose; # because it is O...
491                                         print STDERR "DEBUG: $file: found tag $1 = -1\n" if $debug;
492                                         push(@tag,$1);
493                                         $tag{$1}=-1;
494                                 }
495                         } elsif (/^\#\s*ifdef\s+(\S*)/) {
496                                 push(@tag,"-");
497                                 push(@tag,$1);
498                                 $tag{$1}=1;
499                                 print STDERR "DEBUG: $file: found tag $1 = 1\n" if $debug;
500                         } elsif (/^\#\s*if\s+defined\s*\(([^\)]+)\)/) {
501                                 push(@tag,"-");
502                                 if (/^\#\s*if\s+(defined\s*\(([^\)]+)\)(\s+\|\|\s+defined\s*\(([^\)]+)\))*)$/) {
503                                         my $tmp_1 = $1;
504                                         my $tmp_;
505                                         foreach $tmp_ (split '\|\|',$tmp_1) {
506                                                 $tmp_ =~ /defined\s*\(([^\)]+)\)/;
507                                                 print STDERR "DEBUG: $file: found tag $1 = 1\n" if $debug;
508                                                 push(@tag,$1);
509                                                 $tag{$1}=1;
510                                         }
511                                 } else {
512                                         print STDERR "Warning: $file: taking only 'defined($1)' of complicated expression: $_\n" if $verbose; # because it is O...
513                                         print STDERR "DEBUG: $file: found tag $1 = 1\n" if $debug;
514                                         push(@tag,$1);
515                                         $tag{$1}=1;
516                                 }
517                         } elsif (/^\#\s*error\s+(\w+) is disabled\./) {
518                                 my $tag_i = $#tag;
519                                 while($tag[$tag_i] ne "-") {
520                                         if ($tag[$tag_i] eq "OPENSSL_NO_".$1) {
521                                                 $tag{$tag[$tag_i]}=2;
522                                                 print STDERR "DEBUG: $file: changed tag $1 = 2\n" if $debug;
523                                         }
524                                         $tag_i--;
525                                 }
526                         } elsif (/^\#\s*endif/) {
527                                 my $tag_i = $#tag;
528                                 while($tag_i > 0 && $tag[$tag_i] ne "-") {
529                                         my $t=$tag[$tag_i];
530                                         print STDERR "DEBUG: \$t=\"$t\"\n" if $debug;
531                                         if ($tag{$t}==2) {
532                                                 $tag{$t}=-1;
533                                         } else {
534                                                 $tag{$t}=0;
535                                         }
536                                         print STDERR "DEBUG: $file: changed tag ",$t," = ",$tag{$t},"\n" if $debug;
537                                         pop(@tag);
538                                         if ($t =~ /^OPENSSL_NO_([A-Z0-9_]+)$/) {
539                                                 $t=$1;
540                                         } elsif($t =~ /^OPENSSL_USE_([A-Z0-9_]+)$/) {
541                                                 $t=$1;
542                                         } else {
543                                                 $t="";
544                                         }
545                                         if ($t ne ""
546                                             && !grep(/^$t$/, @known_algorithms)) {
547                                                 $unknown_algorithms{$t} = 1;
548                                                 #print STDERR "DEBUG: Added as unknown algorithm: $t\n" if $debug;
549                                         }
550                                         $tag_i--;
551                                 }
552                                 pop(@tag);
553                         } elsif (/^\#\s*else/) {
554                                 my $tag_i = $#tag;
555                                 die "$file unmatched else\n" if $tag_i < 0;
556                                 while($tag[$tag_i] ne "-") {
557                                         my $t=$tag[$tag_i];
558                                         $tag{$t}= -$tag{$t};
559                                         print STDERR "DEBUG: $file: changed tag ",$t," = ",$tag{$t},"\n" if $debug;
560                                         $tag_i--;
561                                 }
562                         } elsif (/^\#\s*if\s+1/) {
563                                 push(@tag,"-");
564                                 # Dummy tag
565                                 push(@tag,"TRUE");
566                                 $tag{"TRUE"}=1;
567                                 print STDERR "DEBUG: $file: found 1\n" if $debug;
568                         } elsif (/^\#\s*if\s+0/) {
569                                 push(@tag,"-");
570                                 # Dummy tag
571                                 push(@tag,"TRUE");
572                                 $tag{"TRUE"}=-1;
573                                 print STDERR "DEBUG: $file: found 0\n" if $debug;
574                         } elsif (/^\#\s*if\s+/) {
575                                 #Some other unrecognized "if" style
576                                 push(@tag,"-");
577                                 print STDERR "Warning: $file: ignoring unrecognized expression: $_\n" if $verbose; # because it is O...
578                         } elsif (/^\#\s*define\s+(\w+)\s+(\w+)/
579                                  && $symhacking && $tag{'TRUE'} != -1) {
580                                 # This is for aliasing.  When we find an alias,
581                                 # we have to invert
582                                 &$make_variant($1,$2);
583                                 print STDERR "DEBUG: $file: defined $1 = $2\n" if $debug;
584                         }
585                         if (/^\#/) {
586                                 @current_platforms =
587                                     grep(!/^$/,
588                                          map { $tag{$_} == 1 ? $_ :
589                                                    $tag{$_} == -1 ? "!".$_  : "" }
590                                          @known_platforms);
591                                 push @current_platforms
592                                     , grep(!/^$/,
593                                            map { $tag{"OPENSSL_SYS_".$_} == 1 ? $_ :
594                                                      $tag{"OPENSSL_SYS_".$_} == -1 ? "!".$_  : "" }
595                                            @known_ossl_platforms);
596                                 @current_algorithms = ();
597                                 @current_algorithms =
598                                     grep(!/^$/,
599                                          map { $tag{"OPENSSL_NO_".$_} == -1 ? $_ : "" }
600                                          @known_algorithms);
601                                 push @current_algorithms
602                                     , grep(!/^$/,
603                                          map { $tag{"OPENSSL_USE_".$_} == 1 ? $_ : "" }
604                                          @known_algorithms);
605                                 push @current_algorithms,
606                                     grep { /^DEPRECATEDIN_/ && $tag{$_} == 1 }
607                                     @known_algorithms;
608                                 $def .=
609                                     "#INFO:"
610                                         .join(',',@current_platforms).":"
611                                             .join(',',@current_algorithms).";";
612                                 next;
613                         }
614                         if ($tag{'TRUE'} != -1) {
615                                 if (/^\s*DEFINE_STACK_OF\s*\(\s*(\w*)\s*\)/
616                                                 || /^\s*DEFINE_STACK_OF_CONST\s*\(\s*(\w*)\s*\)/) {
617                                         next;
618                                 } elsif (/^\s*DECLARE_ASN1_ENCODE_FUNCTIONS\s*\(\s*(\w*)\s*,\s*(\w*)\s*,\s*(\w*)\s*\)/) {
619                                         $def .= "int d2i_$3(void);";
620                                         $def .= "int i2d_$3(void);";
621                                         # Variant for platforms that do not
622                                         # have to access global variables
623                                         # in shared libraries through functions
624                                         $def .=
625                                             "#INFO:"
626                                                 .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":"
627                                                     .join(',',@current_algorithms).";";
628                                         $def .= "OPENSSL_EXTERN int $2_it;";
629                                         $def .=
630                                             "#INFO:"
631                                                 .join(',',@current_platforms).":"
632                                                     .join(',',@current_algorithms).";";
633                                         # Variant for platforms that have to
634                                         # access global variables in shared
635                                         # libraries through functions
636                                         &$make_variant("$2_it","$2_it",
637                                                       "EXPORT_VAR_AS_FUNCTION",
638                                                       "FUNCTION");
639                                         next;
640                                 } elsif (/^\s*DECLARE_ASN1_FUNCTIONS_fname\s*\(\s*(\w*)\s*,\s*(\w*)\s*,\s*(\w*)\s*\)/) {
641                                         $def .= "int d2i_$3(void);";
642                                         $def .= "int i2d_$3(void);";
643                                         $def .= "int $3_free(void);";
644                                         $def .= "int $3_new(void);";
645                                         # Variant for platforms that do not
646                                         # have to access global variables
647                                         # in shared libraries through functions
648                                         $def .=
649                                             "#INFO:"
650                                                 .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":"
651                                                     .join(',',@current_algorithms).";";
652                                         $def .= "OPENSSL_EXTERN int $2_it;";
653                                         $def .=
654                                             "#INFO:"
655                                                 .join(',',@current_platforms).":"
656                                                     .join(',',@current_algorithms).";";
657                                         # Variant for platforms that have to
658                                         # access global variables in shared
659                                         # libraries through functions
660                                         &$make_variant("$2_it","$2_it",
661                                                       "EXPORT_VAR_AS_FUNCTION",
662                                                       "FUNCTION");
663                                         next;
664                                 } elsif (/^\s*DECLARE_ASN1_FUNCTIONS\s*\(\s*(\w*)\s*\)/ ||
665                                          /^\s*DECLARE_ASN1_FUNCTIONS_const\s*\(\s*(\w*)\s*\)/) {
666                                         $def .= "int d2i_$1(void);";
667                                         $def .= "int i2d_$1(void);";
668                                         $def .= "int $1_free(void);";
669                                         $def .= "int $1_new(void);";
670                                         # Variant for platforms that do not
671                                         # have to access global variables
672                                         # in shared libraries through functions
673                                         $def .=
674                                             "#INFO:"
675                                                 .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":"
676                                                     .join(',',@current_algorithms).";";
677                                         $def .= "OPENSSL_EXTERN int $1_it;";
678                                         $def .=
679                                             "#INFO:"
680                                                 .join(',',@current_platforms).":"
681                                                     .join(',',@current_algorithms).";";
682                                         # Variant for platforms that have to
683                                         # access global variables in shared
684                                         # libraries through functions
685                                         &$make_variant("$1_it","$1_it",
686                                                       "EXPORT_VAR_AS_FUNCTION",
687                                                       "FUNCTION");
688                                         next;
689                                 } elsif (/^\s*DECLARE_ASN1_ENCODE_FUNCTIONS_const\s*\(\s*(\w*)\s*,\s*(\w*)\s*\)/) {
690                                         $def .= "int d2i_$2(void);";
691                                         $def .= "int i2d_$2(void);";
692                                         # Variant for platforms that do not
693                                         # have to access global variables
694                                         # in shared libraries through functions
695                                         $def .=
696                                             "#INFO:"
697                                                 .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":"
698                                                     .join(',',@current_algorithms).";";
699                                         $def .= "OPENSSL_EXTERN int $2_it;";
700                                         $def .=
701                                             "#INFO:"
702                                                 .join(',',@current_platforms).":"
703                                                     .join(',',@current_algorithms).";";
704                                         # Variant for platforms that have to
705                                         # access global variables in shared
706                                         # libraries through functions
707                                         &$make_variant("$2_it","$2_it",
708                                                       "EXPORT_VAR_AS_FUNCTION",
709                                                       "FUNCTION");
710                                         next;
711                                 } elsif (/^\s*DECLARE_ASN1_ALLOC_FUNCTIONS\s*\(\s*(\w*)\s*\)/) {
712                                         $def .= "int $1_free(void);";
713                                         $def .= "int $1_new(void);";
714                                         next;
715                                 } elsif (/^\s*DECLARE_ASN1_FUNCTIONS_name\s*\(\s*(\w*)\s*,\s*(\w*)\s*\)/) {
716                                         $def .= "int d2i_$2(void);";
717                                         $def .= "int i2d_$2(void);";
718                                         $def .= "int $2_free(void);";
719                                         $def .= "int $2_new(void);";
720                                         # Variant for platforms that do not
721                                         # have to access global variables
722                                         # in shared libraries through functions
723                                         $def .=
724                                             "#INFO:"
725                                                 .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":"
726                                                     .join(',',@current_algorithms).";";
727                                         $def .= "OPENSSL_EXTERN int $2_it;";
728                                         $def .=
729                                             "#INFO:"
730                                                 .join(',',@current_platforms).":"
731                                                     .join(',',@current_algorithms).";";
732                                         # Variant for platforms that have to
733                                         # access global variables in shared
734                                         # libraries through functions
735                                         &$make_variant("$2_it","$2_it",
736                                                       "EXPORT_VAR_AS_FUNCTION",
737                                                       "FUNCTION");
738                                         next;
739                                 } elsif (/^\s*DECLARE_ASN1_ITEM\s*\(\s*(\w*)\s*\)/) {
740                                         # Variant for platforms that do not
741                                         # have to access global variables
742                                         # in shared libraries through functions
743                                         $def .=
744                                             "#INFO:"
745                                                 .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":"
746                                                     .join(',',@current_algorithms).";";
747                                         $def .= "OPENSSL_EXTERN int $1_it;";
748                                         $def .=
749                                             "#INFO:"
750                                                 .join(',',@current_platforms).":"
751                                                     .join(',',@current_algorithms).";";
752                                         # Variant for platforms that have to
753                                         # access global variables in shared
754                                         # libraries through functions
755                                         &$make_variant("$1_it","$1_it",
756                                                       "EXPORT_VAR_AS_FUNCTION",
757                                                       "FUNCTION");
758                                         next;
759                                 } elsif (/^\s*DECLARE_ASN1_NDEF_FUNCTION\s*\(\s*(\w*)\s*\)/) {
760                                         $def .= "int i2d_$1_NDEF(void);";
761                                 } elsif (/^\s*DECLARE_ASN1_SET_OF\s*\(\s*(\w*)\s*\)/) {
762                                         next;
763                                 } elsif (/^\s*DECLARE_ASN1_PRINT_FUNCTION\s*\(\s*(\w*)\s*\)/) {
764                                         $def .= "int $1_print_ctx(void);";
765                                         next;
766                                 } elsif (/^\s*DECLARE_ASN1_PRINT_FUNCTION_name\s*\(\s*(\w*)\s*,\s*(\w*)\s*\)/) {
767                                         $def .= "int $2_print_ctx(void);";
768                                         next;
769                                 } elsif (/^\s*DECLARE_PKCS12_STACK_OF\s*\(\s*(\w*)\s*\)/) {
770                                         next;
771                                 } elsif (/^DECLARE_PEM_rw\s*\(\s*(\w*)\s*,/ ||
772                                          /^DECLARE_PEM_rw_cb\s*\(\s*(\w*)\s*,/ ||
773                                          /^DECLARE_PEM_rw_const\s*\(\s*(\w*)\s*,/ ) {
774                                         $def .=
775                                             "#INFO:"
776                                                 .join(',',@current_platforms).":"
777                                                     .join(',',"STDIO",@current_algorithms).";";
778                                         $def .= "int PEM_read_$1(void);";
779                                         $def .= "int PEM_write_$1(void);";
780                                         $def .=
781                                             "#INFO:"
782                                                 .join(',',@current_platforms).":"
783                                                     .join(',',@current_algorithms).";";
784                                         # Things that are everywhere
785                                         $def .= "int PEM_read_bio_$1(void);";
786                                         $def .= "int PEM_write_bio_$1(void);";
787                                         next;
788                                 } elsif (/^DECLARE_PEM_write\s*\(\s*(\w*)\s*,/ ||
789                                         /^DECLARE_PEM_write_const\s*\(\s*(\w*)\s*,/ ||
790                                          /^DECLARE_PEM_write_cb\s*\(\s*(\w*)\s*,/ ) {
791                                         $def .=
792                                             "#INFO:"
793                                                 .join(',',@current_platforms).":"
794                                                     .join(',',"STDIO",@current_algorithms).";";
795                                         $def .= "int PEM_write_$1(void);";
796                                         $def .=
797                                             "#INFO:"
798                                                 .join(',',@current_platforms).":"
799                                                     .join(',',@current_algorithms).";";
800                                         # Things that are everywhere
801                                         $def .= "int PEM_write_bio_$1(void);";
802                                         next;
803                                 } elsif (/^DECLARE_PEM_read\s*\(\s*(\w*)\s*,/ ||
804                                          /^DECLARE_PEM_read_cb\s*\(\s*(\w*)\s*,/ ) {
805                                         $def .=
806                                             "#INFO:"
807                                                 .join(',',@current_platforms).":"
808                                                     .join(',',"STDIO",@current_algorithms).";";
809                                         $def .= "int PEM_read_$1(void);";
810                                         $def .=
811                                             "#INFO:"
812                                                 .join(',',@current_platforms).":"
813                                                     .join(',',"STDIO",@current_algorithms).";";
814                                         # Things that are everywhere
815                                         $def .= "int PEM_read_bio_$1(void);";
816                                         next;
817                                 } elsif (/^OPENSSL_DECLARE_GLOBAL\s*\(\s*(\w*)\s*,\s*(\w*)\s*\)/) {
818                                         # Variant for platforms that do not
819                                         # have to access global variables
820                                         # in shared libraries through functions
821                                         $def .=
822                                             "#INFO:"
823                                                 .join(',',"!EXPORT_VAR_AS_FUNCTION",@current_platforms).":"
824                                                     .join(',',@current_algorithms).";";
825                                         $def .= "OPENSSL_EXTERN int _shadow_$2;";
826                                         $def .=
827                                             "#INFO:"
828                                                 .join(',',@current_platforms).":"
829                                                     .join(',',@current_algorithms).";";
830                                         # Variant for platforms that have to
831                                         # access global variables in shared
832                                         # libraries through functions
833                                         &$make_variant("_shadow_$2","_shadow_$2",
834                                                       "EXPORT_VAR_AS_FUNCTION",
835                                                       "FUNCTION");
836                                 } elsif (/^\s*DEPRECATEDIN/) {
837                                         $parens = count_parens($_);
838                                         if ($parens == 0) {
839                                                 $def .= do_deprecated($_,
840                                                         \@current_platforms,
841                                                         \@current_algorithms);
842                                         } else {
843                                                 $stored_multiline = $_;
844                                                 print STDERR "DEBUG: Found multiline DEPRECATEDIN starting with: $stored_multiline\n" if $debug;
845                                                 next;
846                                         }
847                                 } elsif ($tag{'CONST_STRICT'} != 1) {
848                                         if (/\{|\/\*|\([^\)]*$/) {
849                                                 $line = $_;
850                                         } else {
851                                                 $def .= $_;
852                                         }
853                                 }
854                         }
855                 }
856                 close(IN);
857                 die "$file: Unmatched tags\n" if $#tag >= 0;
858
859                 my $algs;
860                 my $plays;
861
862                 print STDERR "DEBUG: postprocessing ----------\n" if $debug;
863                 foreach (split /;/, $def) {
864                         my $s; my $k = "FUNCTION"; my $p; my $a;
865                         s/^[\n\s]*//g;
866                         s/[\n\s]*$//g;
867                         next if(/\#undef/);
868                         next if(/typedef\W/);
869                         next if(/\#define/);
870
871                         print STDERR "TRACE: processing $_\n" if $trace && !/^\#INFO:/;
872                         # Reduce argument lists to empty ()
873                         # fold round brackets recursively: (t(*v)(t),t) -> (t{}{},t) -> {}
874                         my $nsubst = 1; # prevent infinite loop, e.g., on  int fn()
875                         while($nsubst && /\(.*\)/s) {
876                                 $nsubst = s/\([^\(\)]+\)/\{\}/gs;
877                                 $nsubst+= s/\(\s*\*\s*(\w+)\s*\{\}\s*\)/$1/gs;  #(*f{}) -> f
878                         }
879                         # pretend as we didn't use curly braces: {} -> ()
880                         s/\{\}/\(\)/gs;
881
882                         s/STACK_OF\(\)/void/gs;
883                         s/LHASH_OF\(\)/void/gs;
884
885                         print STDERR "DEBUG: \$_ = \"$_\"\n" if $debug;
886                         if (/^\#INFO:([^:]*):(.*)$/) {
887                                 $plats = $1;
888                                 $algs = $2;
889                                 print STDERR "DEBUG: found info on platforms ($plats) and algorithms ($algs)\n" if $debug;
890                                 next;
891                         } elsif (/^\s*OPENSSL_EXTERN\s.*?(\w+(\{[0-9]+\})?)(\[[0-9]*\])*\s*$/) {
892                                 $s = $1;
893                                 $k = "VARIABLE";
894                                 print STDERR "DEBUG: found external variable $s\n" if $debug;
895                         } elsif (/TYPEDEF_\w+_OF/s) {
896                                 next;
897                         } elsif (/(\w+)\s*\(\).*/s) {   # first token prior [first] () is
898                                 $s = $1;                # a function name!
899                                 print STDERR "DEBUG: found function $s\n" if $debug;
900                         } elsif (/\(/ and not (/=/)) {
901                                 print STDERR "File $file: cannot parse: $_;\n";
902                                 next;
903                         } else {
904                                 next;
905                         }
906
907                         $syms{$s} = 1;
908                         $kind{$s} = $k;
909
910                         $p = $plats;
911                         $a = $algs;
912
913                         $platform{$s} =
914                             &reduce_platforms((defined($platform{$s})?$platform{$s}.',':"").$p);
915                         $algorithm{$s} .= ','.$a;
916
917                         if (defined($variant{$s})) {
918                                 foreach $v (split /;/,$variant{$s}) {
919                                         (my $r, my $p, my $k) = split(/:/,$v);
920                                         my $ip = join ',',map({ /^!(.*)$/ ? $1 : "!".$_ } split /,/, $p);
921                                         $syms{$r} = 1;
922                                         if (!defined($k)) { $k = $kind{$s}; }
923                                         $kind{$r} = $k."(".$s.")";
924                                         $algorithm{$r} = $algorithm{$s};
925                                         $platform{$r} = &reduce_platforms($platform{$s}.",".$p.",".$p);
926                                         $platform{$s} = &reduce_platforms($platform{$s}.','.$ip.','.$ip);
927                                         print STDERR "DEBUG: \$variant{\"$s\"} = ",$v,"; \$r = $r; \$p = ",$platform{$r},"; \$a = ",$algorithm{$r},"; \$kind = ",$kind{$r},"\n" if $debug;
928                                 }
929                         }
930                         print STDERR "DEBUG: \$s = $s; \$p = ",$platform{$s},"; \$a = ",$algorithm{$s},"; \$kind = ",$kind{$s},"\n" if $debug;
931                 }
932         }
933
934         # Prune the returned symbols
935
936         delete $syms{"bn_dump1"};
937         $platform{"BIO_s_log"} .= ",!WIN32,!macintosh";
938
939         $platform{"PEM_read_NS_CERT_SEQ"} = "VMS";
940         $platform{"PEM_write_NS_CERT_SEQ"} = "VMS";
941         $platform{"PEM_read_P8_PRIV_KEY_INFO"} = "VMS";
942         $platform{"PEM_write_P8_PRIV_KEY_INFO"} = "VMS";
943
944         # Info we know about
945
946         push @ret, map { $_."\\".&info_string($_,"EXIST",
947                                               $platform{$_},
948                                               $kind{$_},
949                                               $algorithm{$_}) } keys %syms;
950
951         if (keys %unknown_algorithms) {
952                 print STDERR "WARNING: mkdef.pl doesn't know the following algorithms:\n";
953                 print STDERR "\t",join("\n\t",keys %unknown_algorithms),"\n";
954         }
955         return(@ret);
956 }
957
958 # Param: string of comma-separated platform-specs.
959 sub reduce_platforms
960 {
961         my ($platforms) = @_;
962         my $pl = defined($platforms) ? $platforms : "";
963         my %p = map { $_ => 0 } split /,/, $pl;
964         my $ret;
965
966         print STDERR "DEBUG: Entered reduce_platforms with \"$platforms\"\n"
967             if $debug;
968         # We do this, because if there's code like the following, it really
969         # means the function exists in all cases and should therefore be
970         # everywhere.  By increasing and decreasing, we may attain 0:
971         #
972         # ifndef WIN16
973         #    int foo();
974         # else
975         #    int _fat foo();
976         # endif
977         foreach $platform (split /,/, $pl) {
978                 if ($platform =~ /^!(.*)$/) {
979                         $p{$1}--;
980                 } else {
981                         $p{$platform}++;
982                 }
983         }
984         foreach $platform (keys %p) {
985                 if ($p{$platform} == 0) { delete $p{$platform}; }
986         }
987
988         delete $p{""};
989
990         $ret = join(',',sort(map { $p{$_} < 0 ? "!".$_ : $_ } keys %p));
991         print STDERR "DEBUG: Exiting reduce_platforms with \"$ret\"\n"
992             if $debug;
993         return $ret;
994 }
995
996 sub info_string
997 {
998         (my $symbol, my $exist, my $platforms, my $kind, my $algorithms) = @_;
999
1000         my %a = defined($algorithms) ?
1001             map { $_ => 1 } split /,/, $algorithms : ();
1002         my $k = defined($kind) ? $kind : "FUNCTION";
1003         my $ret;
1004         my $p = &reduce_platforms($platforms);
1005
1006         delete $a{""};
1007
1008         $ret = $exist;
1009         $ret .= ":".$p;
1010         $ret .= ":".$k;
1011         $ret .= ":".join(',',sort keys %a);
1012         return $ret;
1013 }
1014
1015 sub maybe_add_info
1016 {
1017         (my $name, *nums, my @symbols) = @_;
1018         my $sym;
1019         my $new_info = 0;
1020         my %syms=();
1021
1022         foreach $sym (@symbols) {
1023                 (my $s, my $i) = split /\\/, $sym;
1024                 if (defined($nums{$s})) {
1025                         $i =~ s/^(.*?:.*?:\w+)(\(\w+\))?/$1/;
1026                         (my $n, my $vers, my $dummy) = split /\\/, $nums{$s};
1027                         if (!defined($dummy) || $i ne $dummy) {
1028                                 $nums{$s} = $n."\\".$vers."\\".$i;
1029                                 $new_info++;
1030                                 print STDERR "DEBUG: maybe_add_info for $s: \"$dummy\" => \"$i\"\n" if $debug;
1031                         }
1032                 }
1033                 $syms{$s} = 1;
1034         }
1035
1036         my @s=sort { &parse_number($nums{$a},"n") <=> &parse_number($nums{$b},"n") } keys %nums;
1037         foreach $sym (@s) {
1038                 (my $n, my $vers, my $i) = split /\\/, $nums{$sym};
1039                 if (!defined($syms{$sym}) && $i !~ /^NOEXIST:/) {
1040                         $new_info++;
1041                         print STDERR "DEBUG: maybe_add_info for $sym: -> undefined\n" if $debug;
1042                 }
1043         }
1044         if ($new_info) {
1045                 print STDERR "$name: $new_info old symbols have updated info\n";
1046                 if (!$do_rewrite) {
1047                         print STDERR "You should do a rewrite to fix this.\n";
1048                 }
1049         } else {
1050         }
1051 }
1052
1053 # Param: string of comma-separated keywords, each possibly prefixed with a "!"
1054 sub is_valid
1055 {
1056         my ($keywords_txt,$platforms) = @_;
1057         my (@keywords) = split /,/,$keywords_txt;
1058         my ($falsesum, $truesum) = (0, 1);
1059
1060         # Param: one keyword
1061         sub recognise
1062         {
1063                 my ($keyword,$platforms) = @_;
1064
1065                 if ($platforms) {
1066                         # platforms
1067                         if ($keyword eq "UNIX" && $UNIX) { return 1; }
1068                         if ($keyword eq "VMS" && $VMS) { return 1; }
1069                         if ($keyword eq "WIN32" && $W32) { return 1; }
1070                         if ($keyword eq "_WIN32" && $W32) { return 1; }
1071                         if ($keyword eq "WINNT" && $NT) { return 1; }
1072                         # Special platforms:
1073                         # EXPORT_VAR_AS_FUNCTION means that global variables
1074                         # will be represented as functions.
1075                         if ($keyword eq "EXPORT_VAR_AS_FUNCTION" && $W32) {
1076                                 return 1;
1077                         }
1078                         if ($keyword eq "ZLIB" && $zlib) { return 1; }
1079                         return 0;
1080                 } else {
1081                         # algorithms
1082                         if ($disabled_algorithms{$keyword}) { return 0;}
1083
1084                         # Nothing recognise as true
1085                         return 1;
1086                 }
1087         }
1088
1089         foreach $k (@keywords) {
1090                 if ($k =~ /^!(.*)$/) {
1091                         $falsesum += &recognise($1,$platforms);
1092                 } else {
1093                         $truesum *= &recognise($k,$platforms);
1094                 }
1095         }
1096         print STDERR "DEBUG: [",$#keywords,",",$#keywords < 0,"] is_valid($keywords_txt) => (\!$falsesum) && $truesum = ",(!$falsesum) && $truesum,"\n" if $debug;
1097         return (!$falsesum) && $truesum;
1098 }
1099
1100 sub print_test_file
1101 {
1102         (*OUT,my $name,*nums,my $testall,my @symbols)=@_;
1103         my $n = 1; my @e; my @r;
1104         my $sym; my $prev = ""; my $prefSSLeay;
1105
1106         (@e)=grep(/^SSLeay(\{[0-9]+\})?\\.*?:.*?:.*/,@symbols);
1107         (@r)=grep(/^\w+(\{[0-9]+\})?\\.*?:.*?:.*/ && !/^SSLeay(\{[0-9]+\})?\\.*?:.*?:.*/,@symbols);
1108         @symbols=((sort @e),(sort @r));
1109
1110         foreach $sym (@symbols) {
1111                 (my $s, my $i) = $sym =~ /^(.*?)\\(.*)$/;
1112                 my $v = 0;
1113                 $v = 1 if $i=~ /^.*?:.*?:VARIABLE/;
1114                 my $p = ($i =~ /^[^:]*:([^:]*):/,$1);
1115                 my $a = ($i =~ /^[^:]*:[^:]*:[^:]*:([^:]*)/,$1);
1116                 if (!defined($nums{$s})) {
1117                         print STDERR "Warning: $s does not have a number assigned\n"
1118                             if(!$do_update);
1119                 } elsif (is_valid($p,1) && is_valid($a,0)) {
1120                         my $s2 = ($s =~ /^(.*?)(\{[0-9]+\})?$/, $1);
1121                         if ($prev eq $s2) {
1122                                 print OUT "\t/* The following has already appeared previously */\n";
1123                                 print STDERR "Warning: Symbol '",$s2,"' redefined. old=",($nums{$prev} =~ /^(.*?)\\/,$1),", new=",($nums{$s2} =~ /^(.*?)\\/,$1),"\n";
1124                         }
1125                         $prev = $s2;    # To warn about duplicates...
1126
1127                         (my $nn, my $vers, my $ni) = split /\\/, $nums{$s2};
1128                         if ($v) {
1129                                 print OUT "\textern int $s2; /* type unknown */ /* $nn $ni */\n";
1130                         } else {
1131                                 print OUT "\textern int $s2(); /* type unknown */ /* $nn $ni */\n";
1132                         }
1133                 }
1134         }
1135 }
1136
1137 sub get_version
1138 {
1139    return $config{version};
1140 }
1141
1142 sub print_def_file
1143 {
1144         (*OUT,my $name,*nums,my @symbols)=@_;
1145         my $n = 1; my @e; my @r; my @v; my $prev="";
1146         my $liboptions="";
1147         my $libname = $name;
1148         my $http_vendor = 'www.openssl.org/';
1149         my $version = get_version();
1150         my $what = "OpenSSL: implementation of Secure Socket Layer";
1151         my $description = "$what $version, $name - http://$http_vendor";
1152         my $prevsymversion = "", $prevprevsymversion = "";
1153         # For VMS
1154         my $prevnum = 0;
1155         my $symvtextcount = 0;
1156
1157         if ($W32)
1158                 {
1159                 print OUT <<"EOF";
1160 ;
1161 ; Definition file for the DLL version of the $name library from OpenSSL
1162 ;
1163
1164 LIBRARY         $libname        $liboptions
1165
1166 EOF
1167
1168                 print "EXPORTS\n";
1169                 }
1170         elsif ($VMS)
1171                 {
1172                 print OUT <<"EOF";
1173 IDENTIFICATION=$version
1174 CASE_SENSITIVE=YES
1175 SYMBOL_VECTOR=(-
1176 EOF
1177                 $symvtextcount = 16; # length of "SYMBOL_VECTOR=(-"
1178                 }
1179
1180         (@r)=grep(/^\w+(\{[0-9]+\})?\\.*?:.*?:FUNCTION/,@symbols);
1181         (@v)=grep(/^\w+(\{[0-9]+\})?\\.*?:.*?:VARIABLE/,@symbols);
1182         if ($VMS) {
1183             # VMS needs to have the symbols on slot number order
1184             @symbols=(map { $_->[1] }
1185                       sort { $a->[0] <=> $b->[0] }
1186                       map { (my $s, my $i) = $_ =~ /^(.*?)\\(.*)$/;
1187                             die "Error: $s doesn't have a number assigned\n"
1188                                 if !defined($nums{$s});
1189                             (my $n, my @rest) = split /\\/, $nums{$s};
1190                             [ $n, $_ ] } (@e, @r, @v));
1191         } else {
1192             @symbols=((sort @e),(sort @r), (sort @v));
1193         }
1194
1195         my ($baseversion, $currversion) = get_openssl_version();
1196         my $thisversion;
1197         do {
1198                 if (!defined($thisversion)) {
1199                         $thisversion = $baseversion;
1200                 } else {
1201                         $thisversion = get_next_version($thisversion);
1202                 }
1203                 foreach $sym (@symbols) {
1204                         (my $s, my $i) = $sym =~ /^(.*?)\\(.*)$/;
1205                         my $v = 0;
1206                         $v = 1 if $i =~ /^.*?:.*?:VARIABLE/;
1207                         if (!defined($nums{$s})) {
1208                                 die "Error: $s does not have a number assigned\n"
1209                                         if(!$do_update);
1210                         } else {
1211                                 (my $n, my $symversion, my $dummy) = split /\\/, $nums{$s};
1212                                 my %pf = ();
1213                                 my $p = ($i =~ /^[^:]*:([^:]*):/,$1);
1214                                 my $a = ($i =~ /^[^:]*:[^:]*:[^:]*:([^:]*)/,$1);
1215                                 if (is_valid($p,1) && is_valid($a,0)) {
1216                                         my $s2 = ($s =~ /^(.*?)(\{[0-9]+\})?$/, $1);
1217                                         if ($prev eq $s2) {
1218                                                 print STDERR "Warning: Symbol '",$s2,
1219                                                         "' redefined. old=",($nums{$prev} =~ /^(.*?)\\/,$1),
1220                                                         ", new=",($nums{$s2} =~ /^(.*?)\\/,$1),"\n";
1221                                         }
1222                                         $prev = $s2;    # To warn about duplicates...
1223                                         if($linux) {
1224                                                 next if $symversion ne $thisversion;
1225                                                 if ($symversion ne $prevsymversion) {
1226                                                         if ($prevsymversion ne "") {
1227                                                                 if ($prevprevsymversion ne "") {
1228                                                                         print OUT "} OPENSSL${SO_VARIANT}_"
1229                                                                                                 ."$prevprevsymversion;\n\n";
1230                                                                 } else {
1231                                                                         print OUT "};\n\n";
1232                                                                 }
1233                                                         }
1234                                                         print OUT "OPENSSL${SO_VARIANT}_$symversion {\n    global:\n";
1235                                                         $prevprevsymversion = $prevsymversion;
1236                                                         $prevsymversion = $symversion;
1237                                                 }
1238                                                 print OUT "        $s2;\n";
1239                                         } elsif ($VMS) {
1240                                             while(++$prevnum < $n) {
1241                                                 my $symline=" ,SPARE -\n  ,SPARE -\n";
1242                                                 if ($symvtextcount + length($symline) - 2 > 1024) {
1243                                                     print OUT ")\nSYMBOL_VECTOR=(-\n";
1244                                                     $symvtextcount = 16; # length of "SYMBOL_VECTOR=(-"
1245                                                 }
1246                                                 if ($symvtextcount == 16) {
1247                                                     # Take away first comma
1248                                                     $symline =~ s/,//;
1249                                                 }
1250                                                 print OUT $symline;
1251                                                 $symvtextcount += length($symline) - 2;
1252                                             }
1253                                             (my $s_uc = $s) =~ tr/a-z/A-Z/;
1254                                             my $symtype=
1255                                                 $v ? "DATA" : "PROCEDURE";
1256                                             my $symline=
1257                                                 ($s_uc ne $s
1258                                                  ? " ,$s_uc/$s=$symtype -\n  ,$s=$symtype -\n"
1259                                                  : " ,$s=$symtype -\n  ,SPARE -\n");
1260                                             if ($symvtextcount + length($symline) - 2 > 1024) {
1261                                                 print OUT ")\nSYMBOL_VECTOR=(-\n";
1262                                                 $symvtextcount = 16; # length of "SYMBOL_VECTOR=(-"
1263                                             }
1264                                             if ($symvtextcount == 16) {
1265                                                 # Take away first comma
1266                                                 $symline =~ s/,//;
1267                                             }
1268                                             print OUT $symline;
1269                                             $symvtextcount += length($symline) - 2;
1270                                         } elsif($v) {
1271                                                 printf OUT "    %s%-39s DATA\n",
1272                                                                 ($W32)?"":"_",$s2;
1273                                         } else {
1274                                                 printf OUT "    %s%s\n",
1275                                                                 ($W32)?"":"_",$s2;
1276                                         }
1277                                 }
1278                         }
1279                 }
1280         } while ($linux && $thisversion ne $currversion);
1281         if ($linux) {
1282                 if ($prevprevsymversion ne "") {
1283                         print OUT "    local: *;\n} OPENSSL${SO_VARIANT}_$prevprevsymversion;\n\n";
1284                 } else {
1285                         print OUT "    local: *;\n};\n\n";
1286                 }
1287         } elsif ($VMS) {
1288             print OUT ")\n";
1289             (my $libvmaj, my $libvmin, my $libvedit) =
1290                 $currversion =~ /^(\d+)_(\d+)_(\d+)$/;
1291             # The reason to multiply the edit number with 100 is to make space
1292             # for the possibility that we want to encode the patch letters
1293             print OUT "GSMATCH=LEQUAL,",($libvmaj * 100 + $libvmin),",",($libvedit * 100),"\n";
1294         }
1295         printf OUT "\n";
1296 }
1297
1298 sub load_numbers
1299 {
1300         my($name)=@_;
1301         my(@a,%ret);
1302         my $prevversion;
1303
1304         $max_num = 0;
1305         $num_noinfo = 0;
1306         $prev = "";
1307         $prev_cnt = 0;
1308
1309         my ($baseversion, $currversion) = get_openssl_version();
1310
1311         open(IN,"<$name") || die "unable to open $name:$!\n";
1312         while (<IN>) {
1313                 s|\R$||;        # Better chomp
1314                 s/#.*$//;
1315                 next if /^\s*$/;
1316                 @a=split;
1317                 if (defined $ret{$a[0]}) {
1318                         # This is actually perfectly OK
1319                         #print STDERR "Warning: Symbol '",$a[0],"' redefined. old=",$ret{$a[0]},", new=",$a[1],"\n";
1320                 }
1321                 if ($max_num > $a[1]) {
1322                         print STDERR "Warning: Number decreased from ",$max_num," to ",$a[1],"\n";
1323                 }
1324                 elsif ($max_num == $a[1]) {
1325                         # This is actually perfectly OK
1326                         #print STDERR "Warning: Symbol ",$a[0]," has same number as previous ",$prev,": ",$a[1],"\n";
1327                         if ($a[0] eq $prev) {
1328                                 $prev_cnt++;
1329                                 $a[0] .= "{$prev_cnt}";
1330                         }
1331                 }
1332                 else {
1333                         $prev_cnt = 0;
1334                 }
1335                 if ($#a < 2) {
1336                         # Existence will be proven later, in do_defs
1337                         $ret{$a[0]}=$a[1];
1338                         $num_noinfo++;
1339                 } else {
1340                         #Sanity check the version number
1341                         if (defined $prevversion) {
1342                                 check_version_lte($prevversion, $a[2]);
1343                         }
1344                         check_version_lte($a[2], $currversion);
1345                         $prevversion = $a[2];
1346                         $ret{$a[0]}=$a[1]."\\".$a[2]."\\".$a[3]; # \\ is a special marker
1347                 }
1348                 $max_num = $a[1] if $a[1] > $max_num;
1349                 $prev=$a[0];
1350         }
1351         if ($num_noinfo) {
1352                 print STDERR "Warning: $num_noinfo symbols were without info." if $verbose || !$do_rewrite;
1353                 if ($do_rewrite) {
1354                         printf STDERR "  The rewrite will fix this.\n" if $verbose;
1355                 } else {
1356                         printf STDERR "  You should do a rewrite to fix this.\n";
1357                 }
1358         }
1359         close(IN);
1360         return(%ret);
1361 }
1362
1363 sub parse_number
1364 {
1365         (my $str, my $what) = @_;
1366         (my $n, my $v, my $i) = split(/\\/,$str);
1367         if ($what eq "n") {
1368                 return $n;
1369         } else {
1370                 return $i;
1371         }
1372 }
1373
1374 sub rewrite_numbers
1375 {
1376         (*OUT,$name,*nums,@symbols)=@_;
1377         my $thing;
1378
1379         my @r = grep(/^\w+(\{[0-9]+\})?\\.*?:.*?:\w+\(\w+\)/,@symbols);
1380         my $r; my %r; my %rsyms;
1381         foreach $r (@r) {
1382                 (my $s, my $i) = split /\\/, $r;
1383                 my $a = $1 if $i =~ /^.*?:.*?:\w+\((\w+)\)/;
1384                 $i =~ s/^(.*?:.*?:\w+)\(\w+\)/$1/;
1385                 $r{$a} = $s."\\".$i;
1386                 $rsyms{$s} = 1;
1387         }
1388
1389         my %syms = ();
1390         foreach $_ (@symbols) {
1391                 (my $n, my $i) = split /\\/;
1392                 $syms{$n} = 1;
1393         }
1394
1395         my @s=sort {
1396             &parse_number($nums{$a},"n") <=> &parse_number($nums{$b},"n")
1397             || $a cmp $b
1398         } keys %nums;
1399         foreach $sym (@s) {
1400                 (my $n, my $vers, my $i) = split /\\/, $nums{$sym};
1401                 next if defined($i) && $i =~ /^.*?:.*?:\w+\(\w+\)/;
1402                 next if defined($rsyms{$sym});
1403                 print STDERR "DEBUG: rewrite_numbers for sym = ",$sym,": i = ",$i,", n = ",$n,", rsym{sym} = ",$rsyms{$sym},"syms{sym} = ",$syms{$sym},"\n" if $debug;
1404                 $i="NOEXIST::FUNCTION:"
1405                         if !defined($i) || $i eq "" || !defined($syms{$sym});
1406                 my $s2 = $sym;
1407                 $s2 =~ s/\{[0-9]+\}$//;
1408                 printf OUT "%s%-39s %d\t%s\t%s\n","",$s2,$n,$vers,$i;
1409                 if (exists $r{$sym}) {
1410                         (my $s, $i) = split /\\/,$r{$sym};
1411                         my $s2 = $s;
1412                         $s2 =~ s/\{[0-9]+\}$//;
1413                         printf OUT "%s%-39s %d\t%s\t%s\n","",$s2,$n,$vers,$i;
1414                 }
1415         }
1416 }
1417
1418 sub update_numbers
1419 {
1420         (*OUT,$name,*nums,my $start_num, my @symbols)=@_;
1421         my $new_syms = 0;
1422         my $basevers;
1423         my $vers;
1424
1425         ($basevers, $vers) = get_openssl_version();
1426
1427         my @r = grep(/^\w+(\{[0-9]+\})?\\.*?:.*?:\w+\(\w+\)/,@symbols);
1428         my $r; my %r; my %rsyms;
1429         foreach $r (@r) {
1430                 (my $s, my $i) = split /\\/, $r;
1431                 my $a = $1 if $i =~ /^.*?:.*?:\w+\((\w+)\)/;
1432                 $i =~ s/^(.*?:.*?:\w+)\(\w+\)/$1/;
1433                 $r{$a} = $s."\\".$i;
1434                 $rsyms{$s} = 1;
1435         }
1436
1437         foreach $sym (@symbols) {
1438                 (my $s, my $i) = $sym =~ /^(.*?)\\(.*)$/;
1439                 next if $i =~ /^.*?:.*?:\w+\(\w+\)/;
1440                 next if defined($rsyms{$sym});
1441                 die "ERROR: Symbol $sym had no info attached to it."
1442                     if $i eq "";
1443                 if (!exists $nums{$s}) {
1444                         $new_syms++;
1445                         my $s2 = $s;
1446                         $s2 =~ s/\{[0-9]+\}$//;
1447                         printf OUT "%s%-39s %d\t%s\t%s\n","",$s2, ++$start_num,$vers,$i;
1448                         if (exists $r{$s}) {
1449                                 ($s, $i) = split /\\/,$r{$s};
1450                                 $s =~ s/\{[0-9]+\}$//;
1451                                 printf OUT "%s%-39s %d\t%s\t%s\n","",$s, $start_num,$vers,$i;
1452                         }
1453                 }
1454         }
1455         if($new_syms) {
1456                 print STDERR "$name: Added $new_syms new symbols\n";
1457         } else {
1458                 print STDERR "$name: No new symbols added\n";
1459         }
1460 }
1461
1462 sub check_existing
1463 {
1464         (*nums, my @symbols)=@_;
1465         my %existing; my @remaining;
1466         @remaining=();
1467         foreach $sym (@symbols) {
1468                 (my $s, my $i) = $sym =~ /^(.*?)\\(.*)$/;
1469                 $existing{$s}=1;
1470         }
1471         foreach $sym (keys %nums) {
1472                 if (!exists $existing{$sym}) {
1473                         push @remaining, $sym;
1474                 }
1475         }
1476         if(@remaining) {
1477                 print STDERR "The following symbols do not seem to exist:\n";
1478                 foreach $sym (@remaining) {
1479                         print STDERR "\t",$sym,"\n";
1480                 }
1481         }
1482 }
1483
1484 sub count_parens
1485 {
1486         my $line = shift(@_);
1487
1488         my $open = $line =~ tr/\(//;
1489         my $close = $line =~ tr/\)//;
1490
1491         return $open - $close;
1492 }
1493
1494 #Parse opensslv.h to get the current version number. Also work out the base
1495 #version, i.e. the lowest version number that is binary compatible with this
1496 #version
1497 sub get_openssl_version()
1498 {
1499         my $fn = catfile($config{sourcedir},"include","openssl","opensslv.h");
1500         open (IN, "$fn") || die "Can't open opensslv.h";
1501
1502         while(<IN>) {
1503                 if (/OPENSSL_VERSION_TEXT\s+"OpenSSL (\d\.\d\.)(\d[a-z]*)(-| )/) {
1504                         my $suffix = $2;
1505                         (my $baseversion = $1) =~ s/\./_/g;
1506                         close IN;
1507                         return ($baseversion."0", $baseversion.$suffix);
1508                 }
1509         }
1510         die "Can't find OpenSSL version number\n";
1511 }
1512
1513 #Given an OpenSSL version number, calculate the next version number. If the
1514 #version number gets to a.b.czz then we go to a.b.(c+1)
1515 sub get_next_version()
1516 {
1517         my $thisversion = shift;
1518
1519         my ($base, $letter) = $thisversion =~ /^(\d_\d_\d)([a-z]{0,2})$/;
1520
1521         if ($letter eq "zz") {
1522                 my $lastnum = substr($base, -1);
1523                 return substr($base, 0, length($base)-1).(++$lastnum);
1524         }
1525         return $base.get_next_letter($letter);
1526 }
1527
1528 #Given the letters off the end of an OpenSSL version string, calculate what
1529 #the letters for the next release would be.
1530 sub get_next_letter()
1531 {
1532         my $thisletter = shift;
1533         my $baseletter = "";
1534         my $endletter;
1535
1536         if ($thisletter eq "") {
1537                 return "a";
1538         }
1539         if ((length $thisletter) > 1) {
1540                 ($baseletter, $endletter) = $thisletter =~ /([a-z]+)([a-z])/;
1541         } else {
1542                 $endletter = $thisletter;
1543         }
1544
1545         if ($endletter eq "z") {
1546                 return $thisletter."a";
1547         } else {
1548                 return $baseletter.(++$endletter);
1549         }
1550 }
1551
1552 #Check if a version is less than or equal to the current version. Its a fatal
1553 #error if not. They must also only differ in letters, or the last number (i.e.
1554 #the first two numbers must be the same)
1555 sub check_version_lte()
1556 {
1557         my ($testversion, $currversion) = @_;
1558         my $lentv;
1559         my $lencv;
1560         my $cvbase;
1561
1562         my ($cvnums) = $currversion =~ /^(\d_\d_\d)[a-z]*$/;
1563         my ($tvnums) = $testversion =~ /^(\d_\d_\d)[a-z]*$/;
1564
1565         #Die if we can't parse the version numbers or they don't look sane
1566         die "Invalid version number: $testversion and $currversion\n"
1567                 if (!defined($cvnums) || !defined($tvnums)
1568                         || length($cvnums) != 5
1569                         || length($tvnums) != 5);
1570
1571         #If the base versions (without letters) don't match check they only differ
1572         #in the last number
1573         if ($cvnums ne $tvnums) {
1574                 die "Invalid version number: $testversion "
1575                         ."for current version $currversion\n"
1576                         if (substr($cvnums, 0, 4) ne substr($tvnums, 0, 4));
1577                 return;
1578         }
1579         #If we get here then the base version (i.e. the numbers) are the same - they
1580         #only differ in the letters
1581
1582         $lentv = length $testversion;
1583         $lencv = length $currversion;
1584
1585         #If the testversion has more letters than the current version then it must
1586         #be later (or malformed)
1587         if ($lentv > $lencv) {
1588                 die "Invalid version number: $testversion "
1589                         ."is greater than $currversion\n";
1590         }
1591
1592         #Get the last letter from the current version
1593         my ($cvletter) = $currversion =~ /([a-z])$/;
1594         if (defined $cvletter) {
1595                 ($cvbase) = $currversion =~ /(\d_\d_\d[a-z]*)$cvletter$/;
1596         } else {
1597                 $cvbase = $currversion;
1598         }
1599         die "Unable to parse version number $currversion" if (!defined $cvbase);
1600         my $tvbase;
1601         my ($tvletter) = $testversion =~ /([a-z])$/;
1602         if (defined $tvletter) {
1603                 ($tvbase) = $testversion =~ /(\d_\d_\d[a-z]*)$tvletter$/;
1604         } else {
1605                 $tvbase = $testversion;
1606         }
1607         die "Unable to parse version number $testversion" if (!defined $tvbase);
1608
1609         if ($lencv > $lentv) {
1610                 #If current version has more letters than testversion then testversion
1611                 #minus the final letter must be a substring of the current version
1612                 die "Invalid version number $testversion "
1613                         ."is greater than $currversion or is invalid\n"
1614                         if (index($cvbase, $tvbase) != 0);
1615         } else {
1616                 #If both versions have the same number of letters then they must be
1617                 #equal up to the last letter, and the last letter in testversion must
1618                 #be less than or equal to the last letter in current version.
1619                 die "Invalid version number $testversion "
1620                         ."is greater than $currversion\n"
1621                         if (($cvbase ne $tvbase) && ($tvletter gt $cvletter));
1622         }
1623 }
1624
1625 sub do_deprecated()
1626 {
1627         my ($decl, $plats, $algs) = @_;
1628         $decl =~ /^\s*(DEPRECATEDIN_\d+_\d+_\d+)\s*\((.*)\)\s*$/
1629             or die "Bad DEPRECATEDIN: $decl\n";
1630         my $info1 .= "#INFO:";
1631         $info1 .= join(',', @{$plats}) . ":";
1632         my $info2 = $info1;
1633         $info1 .= join(',',@{$algs}, $1) . ";";
1634         $info2 .= join(',',@{$algs}) . ";";
1635         return $info1 . $2 . ";" . $info2;
1636 }