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