b1d6259e8937d527daede684ad46fdbaf209a354
[openssl.git] / Configure
1 #! /usr/bin/env perl
2 # -*- mode: perl; -*-
3
4 ##
5 ##  Configure -- OpenSSL source tree configuration script
6 ##  If editing this file, run this command before committing
7 ##      make -f Makefile.in TABLE
8 ##
9
10 require 5.000;
11 use strict;
12 use File::Basename;
13 use File::Spec::Functions;
14
15 # see INSTALL for instructions.
16
17 my $usage="Usage: Configure [no-<cipher> ...] [enable-<cipher> ...] [experimental-<cipher> ...] [-Dxxx] [-lxxx] [-Lxxx] [-fxxx] [-Kxxx] [no-hw-xxx|no-hw] [[no-]threads] [[no-]shared] [[no-]zlib|zlib-dynamic] [no-asm] [no-dso] [no-egd] [sctp] [386] [--prefix=DIR] [--openssldir=OPENSSLDIR] [--with-xxx[=vvv]] [--config=FILE] os/compiler[:flags]\n";
18
19 # Options:
20 #
21 # --config      add the given configuration file, which will be read after
22 #               any "Configurations*" files that are found in the same
23 #               directory as this script.
24 # --prefix      prefix for the OpenSSL installation, which includes the
25 #               directories bin, lib, include, share/man, share/doc/openssl
26 #               This becomes the value of INSTALLTOP in Makefile
27 #               (Default: /usr/local)
28 # --openssldir  OpenSSL data area, such as openssl.cnf, certificates and keys.
29 #               If it's a relative directory, it will be added on the directory
30 #               given with --prefix.
31 #               This becomes the value of OPENSSLDIR in Makefile and in C.
32 #               (Default: PREFIX/ssl)
33 #
34 # --install_prefix  Additional prefix for package builders (empty by
35 #               default).  This needn't be set in advance, you can
36 #               just as well use "make INSTALL_PREFIX=/whatever install".
37 #
38 # --cross-compile-prefix Add specified prefix to binutils components.
39 #
40 # --api         One of 0.9.8, 1.0.0 or 1.1.0.  Do not compile support for
41 #               interfaces deprecated as of the specified OpenSSL version.
42 #
43 # no-hw-xxx     do not compile support for specific crypto hardware.
44 #               Generic OpenSSL-style methods relating to this support
45 #               are always compiled but return NULL if the hardware
46 #               support isn't compiled.
47 # no-hw         do not compile support for any crypto hardware.
48 # [no-]threads  [don't] try to create a library that is suitable for
49 #               multithreaded applications (default is "threads" if we
50 #               know how to do it)
51 # [no-]shared   [don't] try to create shared libraries when supported.
52 # no-asm        do not use assembler
53 # no-dso        do not compile in any native shared-library methods. This
54 #               will ensure that all methods just return NULL.
55 # no-egd        do not compile support for the entropy-gathering daemon APIs
56 # [no-]zlib     [don't] compile support for zlib compression.
57 # zlib-dynamic  Like "zlib", but the zlib library is expected to be a shared
58 #               library and will be loaded in run-time by the OpenSSL library.
59 # sctp          include SCTP support
60 # 386           generate 80386 code
61 # no-sse2       disables IA-32 SSE2 code, above option implies no-sse2
62 # no-<cipher>   build without specified algorithm (rsa, idea, rc5, ...)
63 # -<xxx> +<xxx> compiler options are passed through
64 #
65 # DEBUG_SAFESTACK use type-safe stacks to enforce type-safety on stack items
66 #               provided to stack calls. Generates unique stack functions for
67 #               each possible stack type.
68 # DES_PTR       use pointer lookup vs arrays in the DES in crypto/des/des_locl.h
69 # DES_RISC1     use different DES_ENCRYPT macro that helps reduce register
70 #               dependancies but needs to more registers, good for RISC CPU's
71 # DES_RISC2     A different RISC variant.
72 # DES_UNROLL    unroll the inner DES loop, sometimes helps, somtimes hinders.
73 # DES_INT       use 'int' instead of 'long' for DES_LONG in crypto/des/des.h
74 #               This is used on the DEC Alpha where long is 8 bytes
75 #               and int is 4
76 # BN_LLONG      use the type 'long long' in crypto/bn/bn.h
77 # MD2_CHAR      use 'char' instead of 'int' for MD2_INT in crypto/md2/md2.h
78 # MD2_LONG      use 'long' instead of 'int' for MD2_INT in crypto/md2/md2.h
79 # IDEA_SHORT    use 'short' instead of 'int' for IDEA_INT in crypto/idea/idea.h
80 # IDEA_LONG     use 'long' instead of 'int' for IDEA_INT in crypto/idea/idea.h
81 # RC2_SHORT     use 'short' instead of 'int' for RC2_INT in crypto/rc2/rc2.h
82 # RC2_LONG      use 'long' instead of 'int' for RC2_INT in crypto/rc2/rc2.h
83 # RC4_CHAR      use 'char' instead of 'int' for RC4_INT in crypto/rc4/rc4.h
84 # RC4_LONG      use 'long' instead of 'int' for RC4_INT in crypto/rc4/rc4.h
85 # RC4_INDEX     define RC4_INDEX in crypto/rc4/rc4_locl.h.  This turns on
86 #               array lookups instead of pointer use.
87 # RC4_CHUNK     enables code that handles data aligned at long (natural CPU
88 #               word) boundary.
89 # RC4_CHUNK_LL  enables code that handles data aligned at long long boundary
90 #               (intended for 64-bit CPUs running 32-bit OS).
91 # BF_PTR        use 'pointer arithmatic' for Blowfish (unsafe on Alpha).
92 # BF_PTR2       intel specific version (generic version is more efficient).
93 #
94 # Following are set automatically by this script
95 #
96 # MD5_ASM       use some extra md5 assember,
97 # SHA1_ASM      use some extra sha1 assember, must define L_ENDIAN for x86
98 # RMD160_ASM    use some extra ripemd160 assember,
99 # SHA256_ASM    sha256_block is implemented in assembler
100 # SHA512_ASM    sha512_block is implemented in assembler
101 # AES_ASM       ASE_[en|de]crypt is implemented in assembler
102
103 # Minimum warning options... any contributions to OpenSSL should at least get
104 # past these.
105
106 my $gcc_devteam_warn = "-Wall -pedantic -DPEDANTIC -Wno-long-long -Wsign-compare -Wmissing-prototypes -Wshadow -Wformat -Wtype-limits -Werror -DREF_CHECK -DDEBUG_UNUSED";
107
108 # These are used in addition to $gcc_devteam_warn when the compiler is clang.
109 # TODO(openssl-team): fix problems and investigate if (at least) the
110 # following warnings can also be enabled:
111 # -Wswitch-enum, -Wunused-macros, -Wmissing-field-initializers,
112 # -Wcast-align,
113 # -Wunreachable-code -Wunused-parameter -Wlanguage-extension-token
114 # -Wextended-offsetof
115 my $clang_devteam_warn = "-Wno-unused-parameter -Wno-missing-field-initializers -Wno-language-extension-token -Wno-extended-offsetof -Wconditional-uninitialized -Qunused-arguments -Wincompatible-pointer-types-discards-qualifiers -Wmissing-variable-declarations";
116
117 # Warn that "make depend" should be run?
118 my $warn_make_depend = 0;
119
120 # These are used in addition to $gcc_devteam_warn unless this is a mingw build.
121 # This adds backtrace information to the memory leak info.
122 my $memleak_devteam_backtrace = "-rdynamic -DCRYPTO_MDEBUG_BACKTRACE";
123
124
125 my $strict_warnings = 0;
126
127 my $x86_gcc_des="DES_PTR DES_RISC1 DES_UNROLL";
128
129 # MD2_CHAR slags pentium pros
130 my $x86_gcc_opts="RC4_INDEX MD2_INT";
131
132 # As for $BSDthreads. Idea is to maintain "collective" set of flags,
133 # which would cover all BSD flavors. -pthread applies to them all,
134 # but is treated differently. OpenBSD expands is as -D_POSIX_THREAD
135 # -lc_r, which is sufficient. FreeBSD 4.x expands it as -lc_r,
136 # which has to be accompanied by explicit -D_THREAD_SAFE and
137 # sometimes -D_REENTRANT. FreeBSD 5.x expands it as -lc_r, which
138 # seems to be sufficient?
139 my $BSDthreads="-pthread -D_THREAD_SAFE -D_REENTRANT";
140
141 #
142 # API compability name to version number mapping.
143 #
144 my $maxapi = "1.1.0";           # API for "no-deprecated" builds
145 my $apitable = {
146     "1.1.0" => "0x10100000L",
147     "1.0.0" => "0x10000000L",
148     "0.9.8" => "0x00908000L",
149 };
150
151 my $base_target = "BASE";   # The template that all other inherit from
152 our %table = ();
153 our %config = ();
154
155 # Forward declarations ###############################################
156
157 # read_config(filename)
158 #
159 # Reads a configuration file and populates %table with the contents
160 # (which the configuration file places in %targets).
161 sub read_config;
162
163 # resolve_config(target)
164 #
165 # Resolves all the late evalutations, inheritances and so on for the
166 # chosen target and any target it inherits from.
167 sub resolve_config;
168
169
170 # Information collection #############################################
171
172 # Collect version numbers
173 $config{version} = "unknown";
174 $config{version_num} = "unknown";
175 $config{shlib_version_number} = "unknown";
176 $config{shlib_version_history} = "unknown";
177
178 collect_information(
179     '<include/openssl/opensslv.h',
180     undef,
181     qr/OPENSSL.VERSION.TEXT.*OpenSSL (\S+) / => sub { $config{version} = $1; },
182     qr/OPENSSL.VERSION.NUMBER.*(0x\S+)/      => sub { $config{version_num}=$1 },
183     qr/SHLIB_VERSION_NUMBER *"([^"]+)"/      => sub { $config{shlib_version_number}=$1 },
184     qr/SHLIB_VERSION_HISTORY *"([^"]*)"/     => sub { $config{shlib_version_history}=$1 }
185     );
186 if ($config{shlib_version_history} ne "") { $config{shlib_version_history} .= ":"; }
187
188 ($config{major}, $config{minor})
189     = ($config{version} =~ /^([0-9]+)\.([0-9\.]+)/);
190 ($config{shlib_major}, $config{shlib_minor})
191     = ($config{shlib_version_number} =~ /^([0-9]+)\.([0-9\.]+)/);
192 die "erroneous version information in opensslv.h: ",
193     "$config{major}, $config{minor}, $config{shlib_major}, $config{shlib_minor}\n"
194     if ($config{major} eq "" || $config{minor} eq ""
195         || $config{shlib_major} eq "" ||  $config{shlib_minor} eq "");
196
197 # Collect target configurations
198
199 my ($vol, $dir, $dummy) = File::Spec->splitpath($0);
200 my $pattern = File::Spec->catpath($vol, $dir, "Configurations/*.conf");
201 foreach (sort glob($pattern) ) {
202     &read_config($_);
203 }
204
205
206 print "Configuring OpenSSL version $config{version} (0x$config{version_num})\n";
207
208 $config{perl};
209 $config{prefix}="";
210 $config{openssldir}="";
211 $config{processor}="";
212 $config{libdir}="";
213 $config{install_prefix}= "$ENV{'INSTALL_PREFIX'}";
214 $config{cross_compile_prefix}="";
215 $config{fipslibdir}="/usr/local/ssl/fips-2.0/lib/";
216 my $nofipscanistercheck=0;
217 $config{baseaddr}="0xFB00000";
218 my $no_threads=0;
219 my $threads=0;
220 $config{no_shared}=0; # but "no-shared" is default
221 my $zlib=1;      # but "no-zlib" is default
222 my $no_rfc3779=0;
223 my $no_asm=0;
224 my $no_dso=0;
225 my $Makefile="Makefile";
226 my $default_ranlib;
227 $config{fips}=0;
228
229 # Top level directories to build
230 $config{dirs} = [ "crypto", "ssl", "engines", "apps", "test", "tools" ];
231 # crypto/ subdirectories to build
232 $config{sdirs} = [
233     "objects",
234     "md2", "md4", "md5", "sha", "mdc2", "hmac", "ripemd", "whrlpool", "poly1305",
235     "des", "aes", "rc2", "rc4", "rc5", "idea", "bf", "cast", "camellia", "seed", "chacha", "modes",
236     "bn", "ec", "rsa", "dsa", "dh", "dso", "engine",
237     "buffer", "bio", "stack", "lhash", "rand", "err",
238     "evp", "asn1", "pem", "x509", "x509v3", "conf", "txt_db", "pkcs7", "pkcs12", "comp", "ocsp", "ui",
239     "cms", "ts", "jpake", "srp", "store", "cmac", "ct", "async", "kdf"
240     ];
241
242 # Known TLS and DTLS protocols
243 my @tls = qw(ssl3 tls1 tls1_1 tls1_2);
244 my @dtls = qw(dtls1 dtls1_2);
245
246 # Explicitelly known options that are possible to disable.  They can
247 # be regexps, and will be used like this: /^no-${option}$/
248 # For developers: keep it sorted alphabetically
249
250 my @disablables = (
251     "aes",
252     "asm",
253     "bf",
254     "camellia",
255     "capieng",
256     "cast",
257     "chacha",
258     "cmac",
259     "cms",
260     "comp",
261     "crypto-mdebug",
262     "ct",
263     "deprecated",
264     "des",
265     "dgram",
266     "dh",
267     "dsa",
268     "dso",
269     "dtls",
270     "dynamic[-_]engine",
271     "ec",
272     "ec2m",
273     "ecdh",
274     "ecdsa",
275     "ec_nistp_64_gcc_128",
276     "engine",
277     "err",                      # Really???
278     "gost",
279     "heartbeats",
280     "hmac",
281     "hw(-.+)?",
282     "idea",
283     "jpake",
284     "locking",                  # Really???
285     "md2",
286     "md4",
287     "md5",
288     "mdc2",
289     "md[-_]ghost94",
290     "nextprotoneg",
291     "ocb",
292     "ocsp",
293     "poly1305",
294     "posix-io",
295     "psk",
296     "rc2",
297     "rc4",
298     "rc5",
299     "rdrand",
300     "rfc3779",
301     "rijndael",                 # Old AES name
302     "rmd160",
303     "rsa",
304     "scrypt",
305     "sct",
306     "sctp",
307     "seed",
308     "sha",
309     "shared",
310     "sock",
311     "srp",
312     "srtp",
313     "sse2",
314     "ssl",
315     "ssl-trace",
316     "static-engine",
317     "stdio",
318     "store",
319     "threads",
320     "tls",
321     "unit-test",
322     "whirlpool",
323     "zlib",
324     "zlib-dynamic",
325     );
326 foreach my $proto ((@tls, @dtls))
327         {
328         push(@disablables, $proto);
329         push(@disablables, "$proto-method");
330         }
331
332 # All of the following is disabled by default (RC5 was enabled before 0.9.8):
333
334 my %disabled = ( # "what"         => "comment" [or special keyword "experimental"]
335                  "ec_nistp_64_gcc_128" => "default",
336                  "egd"            => "default",
337                  "jpake"          => "experimental",
338                  "md2"            => "default",
339                  "rc5"            => "default",
340                  "sctp"           => "default",
341                  "shared"         => "default",
342                  "ssl-trace"      => "default",
343                  "store"          => "experimental",
344                  "unit-test"      => "default",
345                  "zlib"           => "default",
346                  "zlib-dynamic"   => "default",
347                  "crypto-mdebug"  => "default",
348                );
349 my @experimental = ();
350
351 # Note: => pair form used for aesthetics, not to truly make a hash table
352 my @disable_cascades = (
353     # "what"            => [ "cascade", ... ]
354     sub { $config{processor} eq "386" }
355                         => [ "sse2" ],
356     "ssl"               => [ "ssl3" ],
357     "ssl3-method"       => [ "ssl3" ],
358     "zlib"              => [ "zlib-dynamic" ],
359     "rijndael"          => [ "aes" ],
360     "des"               => [ "mdc2" ],
361     "ec"                => [ "ecdsa", "ecdh", "gost" ],
362     "dsa"               => [ "gost" ],
363     "dh"                => [ "gost" ],
364     "psk"               => [ "jpake" ],
365
366     "dgram"             => [ "dtls" ],
367     "dtls"              => [ @dtls ],
368
369     # SSL 3.0, (D)TLS 1.0 and TLS 1.1 require MD5 and SHA
370     "md5"               => [ "ssl", "tls1", "tls1_1", "dtls1" ],
371     "sha"               => [ "ssl", "tls1", "tls1_1", "dtls1" ],
372
373     # Additionally, SSL 3.0 requires either RSA or DSA+DH
374     sub { $disabled{rsa}
375           && ($disabled{dsa} || $disabled{dh}); }
376                         => [ "ssl" ],
377
378     # (D)TLS 1.0 and TLS 1.1 also require either RSA or DSA+DH
379     # or ECDSA + ECDH.  (D)TLS 1.2 has this requirement as well.
380     # (XXX: We don't support PSK-only builds).
381     sub { $disabled{rsa}
382           && ($disabled{dsa} || $disabled{dh})
383           && ($disabled{ecdsa} || $disabled{ecdh}); }
384                         => [ "tls1", "tls1_1", "tls1_2",
385                              "dtls1", "dtls1_2" ],
386
387     "tls"               => [ @tls ],
388
389     # SRP and HEARTBEATS require TLSEXT
390     "tlsext"            => [ "srp", "heartbeats" ],
391     );
392
393 # Avoid protocol support holes.  Also disable all versions below N, if version
394 # N is disabled while N+1 is enabled.
395 #
396 my @list = (reverse @tls);
397 while ((my $first, my $second) = (shift @list, shift @list)) {
398     last unless @list;
399     push @disable_cascades, ( sub { !$disabled{$first} && $disabled{$second} }
400                               => [ @list ] );
401     unshift @list, $second;
402 }
403 my @list = (reverse @dtls);
404 while ((my $first, my $second) = (shift @list, shift @list)) {
405     last unless @list;
406     push @disable_cascades, ( sub { !$disabled{$first} && $disabled{$second} }
407                               => [ @list ] );
408     unshift @list, $second;
409 }
410
411 # Construct the string of what $config{depflags} should look like with the defaults
412 # from %disabled above.  (we need this to see if we should advise the user
413 # to run "make depend"):
414 my $default_depflags = join(" ",
415     map { my $x = $_; $x =~ tr{[a-z]-}{[A-Z]_}; "-DOPENSSL_NO_$x"; }
416     grep { $disabled{$_} !~ /\(no-depflags\)$/ }
417     sort keys %disabled);
418
419 # Explicit "no-..." options will be collected in %disabled along with the defaults.
420 # To remove something from %disabled, use "enable-foo" (unless it's experimental).
421 # For symmetry, "disable-foo" is a synonym for "no-foo".
422
423 # For features called "experimental" here, a more explicit "experimental-foo" is needed to enable.
424 # We will collect such requests in @experimental.
425 # To avoid accidental use of experimental features, applications will have to use -DOPENSSL_EXPERIMENTAL_FOO.
426
427
428 my $no_sse2=0;
429
430 &usage if ($#ARGV < 0);
431
432 my $flags="";
433 $config{depflags}="";
434 $config{openssl_experimental_defines}=[];
435 $config{openssl_api_defines}=[];
436 $config{openssl_algorithm_defines}=[];
437 $config{openssl_thread_defines}=[];
438 $config{openssl_sys_defines}=[];
439 $config{openssl_other_defines}=[];
440 my $libs="";
441 my $target="";
442 $config{options}="";
443 my $make_depend=0;
444 my %withargs=();
445 my $build_prefix = "release_";
446
447 my @argvcopy=@ARGV;
448
449 if (grep /^reconf(igure)?$/, @argvcopy) {
450     if (-f "./configdata.pm") {
451         my $file = "./configdata.pm";
452         unless (my $return = do $file) {
453             die "couldn't parse $file: $@" if $@;
454             die "couldn't do $file: $!"    unless defined $return;
455             die "couldn't run $file"       unless $return;
456         }
457
458         @argvcopy = defined($configdata::config{perlargv}) ?
459             @{$configdata::config{perlargv}} : ();
460         die "Incorrect data to reconfigure, please do a normal configuration\n"
461             if (grep(/^reconf/,@argvcopy));
462         $ENV{CROSS_COMPILE} = $configdata::config{cross_compile_prefix}
463             if defined($configdata::config{cross_compile_prefix});
464         $ENV{CROSS_COMPILE} = $configdata::config{cc}
465             if defined($configdata::config{cc});
466
467         print "Reconfiguring with: ", join(" ",@argvcopy), "\n";
468         print "    CROSS_COMPILE = ",$ENV{CROSS_COMPILE},"\n"
469             if $ENV{CROSS_COMPILE};
470         print "    CC = ",$ENV{CC},"\n" if $ENV{CC};
471     } elsif (open IN, "<Makefile") {
472         #
473         # THIS SECTION IS TEMPORARY, it helps transitioning from Makefile
474         # centered information gathering the reading configdata.pm
475         #
476         while (<IN>) {
477             chomp;
478             if (/^CONFIGURE_ARGS=\s*(.*)\s*/) {
479                 # Older form, we split the string and hope for the best
480                 @argvcopy = split /\s+/, $_;
481                 die "Incorrect data to reconfigure, please do a normal configuration\n"
482                     if (grep(/^reconf/,@argvcopy));
483             } elsif (/^CROSS_COMPILE=\s*(.*)/) {
484                 $ENV{CROSS_COMPILE}=$1;
485             } elsif (/^CC=\s*(?:\$\(CROSS_COMPILE\))?(.*?)$/) {
486                 $ENV{CC}=$1;
487             }
488         }
489         #
490         # END OF TEMPORARY SECTION
491         #
492     } else {
493         die "Insufficient data to reconfigure, please do a normal configuration\n";
494     }
495 }
496
497 $config{perlargv} = [ @argvcopy ];
498
499 my %unsupported_options = ();
500 foreach (@argvcopy)
501         {
502         s /^-no-/no-/; # some people just can't read the instructions
503
504         # rewrite some options in "enable-..." form
505         s /^-?-?shared$/enable-shared/;
506         s /^sctp$/enable-sctp/;
507         s /^threads$/enable-threads/;
508         s /^zlib$/enable-zlib/;
509         s /^zlib-dynamic$/enable-zlib-dynamic/;
510
511         if (/^(no|disable|enable|experimental)-(.+)$/)
512                 {
513                 my $word = $2;
514                 if (!grep { $word =~ /^${_}$/ } @disablables)
515                         {
516                         $unsupported_options{$_} = 1;
517                         next;
518                         }
519                 }
520         if (/^no-(.+)$/ || /^disable-(.+)$/)
521                 {
522                 if (!($disabled{$1} eq "experimental"))
523                         {
524                         foreach my $proto ((@tls, @dtls))
525                                 {
526                                 if ($1 eq "$proto-method")
527                                         {
528                                         $disabled{"$proto"} = "option($proto-method)";
529                                         last;
530                                         }
531                                 }
532                         if ($1 eq "dtls")
533                                 {
534                                 foreach my $proto (@dtls)
535                                         {
536                                         $disabled{$proto} = "option(dtls)";
537                                         }
538                                 }
539                         elsif ($1 eq "ssl")
540                                 {
541                                 # Last one of its kind
542                                 $disabled{"ssl3"} = "option(ssl)";
543                                 }
544                         elsif ($1 eq "tls")
545                                 {
546                                 # XXX: Tests will fail if all SSL/TLS
547                                 # protocols are disabled.
548                                 foreach my $proto (@tls)
549                                         {
550                                         $disabled{$proto} = "option(tls)";
551                                         }
552                                 }
553                         else
554                                 {
555                                 $disabled{$1} = "option";
556                                 }
557                         }
558                 }
559         elsif (/^enable-(.+)$/ || /^experimental-(.+)$/)
560                 {
561                 my $algo = $1;
562                 if ($disabled{$algo} eq "experimental")
563                         {
564                         die "You are requesting an experimental feature; please say 'experimental-$algo' if you are sure\n"
565                                 unless (/^experimental-/);
566                         push @experimental, $algo;
567                         }
568                 delete $disabled{$algo};
569
570                 $threads = 1 if ($algo eq "threads");
571                 }
572         elsif (/^--strict-warnings$/)
573                 {
574                 $strict_warnings = 1;
575                 }
576         elsif (/^--debug$/)
577                 {
578                 $build_prefix = "debug_";
579                 }
580         elsif (/^--release$/)
581                 {
582                 $build_prefix = "release_";
583                 }
584         elsif (/^386$/)
585                 { $config{processor}=386; }
586         elsif (/^fips$/)
587                 {
588                 $config{fips}=1;
589                 }
590         elsif (/^rsaref$/)
591                 {
592                 # No RSAref support any more since it's not needed.
593                 # The check for the option is there so scripts aren't
594                 # broken
595                 }
596         elsif (/^nofipscanistercheck$/)
597                 {
598                 $config{fips} = 1;
599                 $nofipscanistercheck = 1;
600                 }
601         elsif (/^[-+]/)
602                 {
603                 if (/^--prefix=(.*)$/)
604                         {
605                         $config{prefix}=$1;
606                         }
607                 elsif (/^--api=(.*)$/)
608                         {
609                         $config{api}=$1;
610                         }
611                 elsif (/^--libdir=(.*)$/)
612                         {
613                         $config{libdir}=$1;
614                         }
615                 elsif (/^--openssldir=(.*)$/)
616                         {
617                         $config{openssldir}=$1;
618                         }
619                 elsif (/^--install.prefix=(.*)$/)
620                         {
621                         $config{install_prefix}=$1;
622                         }
623                 elsif (/^--with-zlib-lib=(.*)$/)
624                         {
625                         $withargs{"zlib-lib"}=$1;
626                         }
627                 elsif (/^--with-zlib-include=(.*)$/)
628                         {
629                         $withargs{"zlib-include"}="-I$1";
630                         }
631                 elsif (/^--with-fipslibdir=(.*)$/)
632                         {
633                         $config{fipslibdir}="$1/";
634                         }
635                 elsif (/^--with-baseaddr=(.*)$/)
636                         {
637                         $config{baseaddr}="$1";
638                         }
639                 elsif (/^--cross-compile-prefix=(.*)$/)
640                         {
641                         $config{cross_compile_prefix}=$1;
642                         }
643                 elsif (/^--config=(.*)$/)
644                         {
645                         read_config $1;
646                         }
647                 elsif (/^-[lL](.*)$/ or /^-Wl,/)
648                         {
649                         $libs.=$_." ";
650                         }
651                 else    # common if (/^[-+]/), just pass down...
652                         {
653                         $_ =~ s/%([0-9a-f]{1,2})/chr(hex($1))/gei;
654                         $flags.=$_." ";
655                         }
656                 }
657         elsif ($_ =~ /^([^:]+):(.+)$/)
658                 {
659                 eval "\$table{\$1} = \"$2\""; # allow $xxx constructs in the string
660                 $target=$1;
661                 }
662         else
663                 {
664                 die "target already defined - $target (offending arg: $_)\n" if ($target ne "");
665                 $target=$_;
666                 }
667         unless ($_ eq $target || /^no-/ || /^disable-/)
668                 {
669                 # "no-..." follows later after implied disactivations
670                 # have been derived.  (Don't take this too seroiusly,
671                 # we really only write OPTIONS to the Makefile out of
672                 # nostalgia.)
673
674                 if ($config{options} eq "")
675                         { $config{options} = $_; }
676                 else
677                         { $config{options} .= " ".$_; }
678                 }
679
680         if (defined($config{api}) && !exists $apitable->{$config{api}}) {
681                 die "***** Unsupported api compatibility level: $config{api}\n",
682         }
683
684         if (keys %unsupported_options)
685                 {
686                 die "***** Unsupported options: ",
687                         join(", ", keys %unsupported_options), "\n";
688                 }
689         }
690
691 if ($config{fips})
692         {
693         delete $disabled{"shared"} if ($disabled{"shared"} =~ /^default/);
694         }
695 else
696         {
697         @{$config{dirs}} = grep !/^fips$/, @{$config{dirs}};
698         }
699
700 my @tocheckfor = (keys %disabled);
701 while (@tocheckfor) {
702     my %new_tocheckfor = ();
703     my @cascade_copy = (@disable_cascades);
704     while (@cascade_copy) {
705         my ($test, $descendents) = (shift @cascade_copy, shift @cascade_copy);
706         if (ref($test) eq "CODE" ? $test->() : defined($disabled{$test})) {
707             map {
708                 $new_tocheckfor{$_} => 1; $disabled{$_} = "forced";
709             } grep { !defined($disabled{$_}) } @$descendents;
710         }
711     }
712     @tocheckfor = (keys %new_tocheckfor);
713 }
714
715 if ($target eq "TABLE") {
716     foreach (sort keys %table) {
717         print_table_entry($_, "TABLE");
718     }
719     exit 0;
720 }
721
722 if ($target eq "LIST") {
723     foreach (sort keys %table) {
724         print $_,"\n" unless $table{$_}->{template};
725     }
726     exit 0;
727 }
728
729 if ($target eq "HASH") {
730     print "%table = (\n";
731     foreach (sort keys %table) {
732         print_table_entry($_, "HASH");
733     }
734     exit 0;
735 }
736
737 # Backward compatibility?
738 if ($target =~ m/^CygWin32(-.*)$/) {
739     $target = "Cygwin".$1;
740 }
741
742 foreach (sort (keys %disabled))
743         {
744         $config{options} .= " no-$_";
745
746         printf "    no-%-12s %-10s", $_, "[$disabled{$_}]";
747
748         if (/^dso$/)
749                 { $no_dso = 1; }
750         elsif (/^threads$/)
751                 { $no_threads = 1; }
752         elsif (/^shared$/)
753                 { $config{no_shared} = 1; }
754         elsif (/^zlib$/)
755                 { $zlib = 0; }
756         elsif (/^static-engine$/)
757                 { }
758         elsif (/^zlib-dynamic$/)
759                 { }
760         elsif (/^sse2$/)
761                 { $no_sse2 = 1; }
762         elsif (/^engine$/)
763                 { @{$config{dirs}} = grep !/^engine$/, @{$config{dirs}}; }
764         elsif (/^gost$/)
765                 { @{$config{engdirs}} = grep !/^ccgost$/, @{$config{engdirs}}; }
766         else
767                 {
768                 my ($ALGO, $algo);
769                 ($ALGO = $algo = $_) =~ tr/[\-a-z]/[_A-Z]/;
770
771                 if (/^asm$/ || /^err$/ || /^hw$/ || /^hw-/)
772                         {
773                         push @{$config{openssl_other_defines}}, "OPENSSL_NO_$ALGO";
774                         print " OPENSSL_NO_$ALGO";
775
776                         if (/^err$/)    { $flags .= "-DOPENSSL_NO_ERR "; }
777                         elsif (/^asm$/) { $no_asm = 1; }
778                         }
779                 else
780                         {
781                         ($ALGO,$algo) = ("RMD160","rmd160") if ($algo eq "ripemd");
782
783                         push @{$config{openssl_algorithm_defines}}, "OPENSSL_NO_$ALGO";
784                         $config{depflags} .= " -DOPENSSL_NO_$ALGO";
785                         print " OPENSSL_NO_$ALGO";
786
787                         # fix-up crypto/directory name(s)
788                         $algo="whrlpool" if $algo eq "whirlpool";
789                         $algo="ripemd" if $algo eq "rmd160";
790                         @{$config{sdirs}} = grep { $_ ne $algo} @{$config{sdirs}};
791
792                         print " (skip dir)";
793                         }
794                 }
795
796         print "\n";
797         }
798
799 my $exp_cflags = "";
800
801 foreach (sort @experimental)
802         {
803         my $ALGO;
804         ($ALGO = $_) =~ tr/[a-z]/[A-Z]/;
805
806         # opensslconf.h will set OPENSSL_NO_... unless OPENSSL_EXPERIMENTAL_... is defined
807         push @{$config{openssl_experimental_defines}}, "OPENSSL_NO_$ALGO";
808         $exp_cflags .= " -DOPENSSL_EXPERIMENTAL_$ALGO";
809         }
810
811 print "Configuring for $target\n";
812
813 # Support for legacy targets having a name starting with 'debug-'
814 my ($d, $t) = $target =~ m/^(debug-)?(.*)$/;
815 if ($d) {
816     $build_prefix = "debug_";
817
818     # If we do not find debug-foo in the table, the target is set to foo.
819     if (!$table{$target}) {
820         $target = $t;
821     }
822 }
823 $config{target} = $target;
824 delete $table{$base_target}->{template}; # or the next test will fail.
825 my %target = ( %{$table{$base_target}}, resolve_config($target) );
826
827 &usage if (!%target || $target{template});
828
829 $target{exe_extension}="";
830 $target{exe_extension}=".exe" if ($config{target} eq "Cygwin" || $config{target} eq "DJGPP" || $config{target} =~ /^mingw/);
831 $target{exe_extension}=".nlm" if ($config{target} =~ /netware/);
832 $target{exe_extension}=".pm"  if ($config{target} =~ /vos/);
833
834 $default_ranlib = which("ranlib") || "true";
835 $config{perl}   = $ENV{'PERL'} || which("perl5") || which("perl") || "perl";
836 my $make        = $ENV{'MAKE'} || "make";
837
838 $config{cross_compile_prefix} = $ENV{'CROSS_COMPILE'}
839     if $config{cross_compile_prefix} eq "";
840
841 $config{prefix} = "/usr/local" if !$config{prefix};
842 $config{openssldir} = "ssl" if !$config{openssldir};
843 $config{openssldir} = catdir($config{prefix}, $config{openssldir})
844     unless file_name_is_absolute($config{openssldir});
845
846 # Allow environment CC to override compiler...
847 $target{cc} = $ENV{CC} || $target{cc};
848
849 # For cflags and lflags, add the debug_ or release_ attributes
850 # Do it in such a way that no spurious space is appended (hence the grep).
851 $config{cflags} = join(" ",
852                        grep { $_ ne "" } ($target{cflags},
853                                           $target{$build_prefix."cflags"}));
854 $config{lflags} = join(" ",
855                        grep { $_ ne "" } ($target{lflags},
856                                           $target{$build_prefix."lflags"}));
857
858 $target{ranlib} = $ENV{'RANLIB'} || $target{ranlib} || $default_ranlib;
859 $target{ar} = $ENV{'AR'} || "ar";
860 $target{arflags} = "" if !defined($target{arflags});
861 $target{nm} = "nm";
862 # Make sure build_scheme is consistent.
863 $target{build_scheme} = [ $target{build_scheme} ]
864     if ref($target{build_scheme}) ne "ARRAY";
865
866 # if $config{prefix}/lib$target{multilib} is not an existing directory, then
867 # assume that it's not searched by linker automatically, in
868 # which case adding $target{multilib} suffix causes more grief than
869 # we're ready to tolerate, so don't...
870 $target{multilib}="" if !-d "$config{prefix}/lib$target{multilib}";
871
872 $config{libdir}="lib$target{multilib}" if $config{libdir} eq "";
873 $config{enginesdir}=$config{prefix} . "/" . $config{libdir}  . "/engines";
874
875 $config{cflags} .= "$exp_cflags";
876
877 # '%' in $config{lflags} is used to split flags to "pre-" and post-flags
878 my ($pre,$post)=split('%',$config{lflags});
879 if (defined($post))     { $config{prelflags}=$pre; $config{lflags}=$post;       }
880 else                    { $config{prelflags}="";   $config{lflags}=$pre;        }
881
882 if ($target =~ /^mingw/ && `$target{cc} --target-help 2>&1` !~ m/-mno-cygwin/m)
883         {
884         $config{cflags} =~ s/-mno-cygwin\s*//;
885         $target{shared_ldflag} =~ s/-mno-cygwin\s*//;
886         }
887
888 if ($target =~ /linux.*-mips/ && !$no_asm && $flags !~ /-m(ips|arch=)/) {
889         # minimally required architecture flags for assembly modules
890         $config{cflags}="-mips2 $config{cflags}" if ($target =~ /mips32/);
891         $config{cflags}="-mips3 $config{cflags}" if ($target =~ /mips64/);
892 }
893
894 my $no_shared_warn=0;
895 my $no_user_cflags=0;
896
897 if ($flags ne "")       { $config{cflags}="$flags$config{cflags}"; }
898 else                    { $no_user_cflags=1;       }
899
900 # The DSO code currently always implements all functions so that no
901 # applications will have to worry about that from a compilation point
902 # of view. However, the "method"s may return zero unless that platform
903 # has support compiled in for them. Currently each method is enabled
904 # by a define "DSO_<name>" ... we translate the "dso_scheme" config
905 # string entry into using the following logic;
906 my $dso_cflags;
907 if (!$no_dso && $target{dso_scheme} ne "")
908         {
909         $target{dso_scheme} =~ tr/[a-z]/[A-Z]/;
910         if ($target{dso_scheme} eq "DLFCN")
911                 {
912                 $dso_cflags = "-DDSO_DLFCN -DHAVE_DLFCN_H";
913                 }
914         elsif ($target{dso_scheme} eq "DLFCN_NO_H")
915                 {
916                 $dso_cflags = "-DDSO_DLFCN";
917                 }
918         else
919                 {
920                 $dso_cflags = "-DDSO_$target{dso_scheme}";
921                 }
922         $config{cflags} = "$dso_cflags $config{cflags}";
923         }
924
925 my $thread_cflags;
926 my @thread_defines;
927 if ($target{thread_cflag} ne "(unknown)" && !$no_threads)
928         {
929         # If we know how to do it, support threads by default.
930         $threads = 1;
931         }
932 if ($target{thread_cflag} eq "(unknown)" && $threads)
933         {
934         # If the user asked for "threads", [s]he is also expected to
935         # provide any system-dependent compiler options that are
936         # necessary.
937         if ($no_user_cflags)
938                 {
939                 print "You asked for multi-threading support, but didn't\n";
940                 print "provide any system-specific compiler options\n";
941                 exit(1);
942                 }
943         $thread_cflags="-DOPENSSL_THREADS $config{cflags}" ;
944         push @thread_defines, "OPENSSL_THREADS";
945         }
946 else
947         {
948         $thread_cflags="-DOPENSSL_THREADS $target{thread_cflag} $config{cflags}";
949         push @thread_defines, "OPENSSL_THREADS";
950 #       my $def;
951 #       foreach $def (split ' ',$target{thread_cflag})
952 #               {
953 #               if ($def =~ s/^-D// && $def !~ /^_/)
954 #                       {
955 #                       push @thread_defines, "$def";
956 #                       }
957 #               }
958         }
959
960 $config{lflags}="$libs$config{lflags}" if ($libs ne "");
961
962 if ($no_asm)
963         {
964         $config{cflags}=~s/-D[BL]_ENDIAN//              if ($config{fips});
965         $thread_cflags=~s/-D[BL]_ENDIAN//       if ($config{fips});
966         }
967
968 if ($threads)
969         {
970         $config{cflags}=$thread_cflags;
971         push @{$config{openssl_thread_defines}}, @thread_defines;
972         }
973
974 if ($zlib)
975         {
976         $config{cflags} = "-DZLIB $config{cflags}";
977         if (defined($disabled{"zlib-dynamic"}))
978                 {
979                 if (defined($withargs{"zlib-lib"}))
980                         {
981                         $config{lflags} .= " -L" . $withargs{"zlib-lib"} . " -lz";
982                         }
983                 else
984                         {
985                         $config{lflags} .= " -lz";
986                         }
987                 }
988         else
989                 {
990                 $config{cflags} = "-DZLIB_SHARED $config{cflags}";
991                 }
992         }
993
994 # With "deprecated" disable all deprecated features.
995 if (defined($disabled{"deprecated"})) {
996         $config{api} = $maxapi;
997 }
998
999 if ($target{shared_target} eq "")
1000         {
1001         $no_shared_warn = 1 if !$config{no_shared} && !$config{fips};
1002         $config{no_shared} = 1;
1003         }
1004 if (!$config{no_shared})
1005         {
1006         if ($target{shared_cflag} ne "")
1007                 {
1008                 $config{cflags} = "$target{shared_cflag} -DOPENSSL_PIC $config{cflags}";
1009                 }
1010         }
1011
1012 if ($target{build_scheme}->[0] ne "mk1mf")
1013         {
1014         # add {no-}static-engine to options to allow mkdef.pl to work without extra arguments
1015         if ($config{no_shared})
1016                 {
1017                 push @{$config{openssl_other_defines}}, "OPENSSL_NO_DYNAMIC_ENGINE";
1018                 $config{options}.=" static-engine";
1019                 }
1020         else
1021                 {
1022                 push @{$config{openssl_other_defines}}, "OPENSSL_NO_STATIC_ENGINE";
1023                 $config{options}.=" no-static-engine";
1024                 }
1025         }
1026
1027 #
1028 # Platform fix-ups
1029 #
1030 if ($target =~ /-icc$/) # Intel C compiler
1031         {
1032         my $iccver=0;
1033         if (open(FD,"$target{cc} -V 2>&1 |"))
1034                 {
1035                 while(<FD>) { $iccver=$1 if (/Version ([0-9]+)\./); }
1036                 close(FD);
1037                 }
1038         if ($iccver>=8)
1039                 {
1040                 $config{cflags}=~s/-KPIC/-fPIC/;
1041                 # Eliminate unnecessary dependency from libirc.a. This is
1042                 # essential for shared library support, as otherwise
1043                 # apps/openssl can end up in endless loop upon startup...
1044                 $config{cflags}.=" -Dmemcpy=__builtin_memcpy -Dmemset=__builtin_memset";
1045                 }
1046         if ($iccver>=9)
1047                 {
1048                 $config{lflags}.=" -i-static";
1049                 $config{lflags}=~s/-no_cpprt/-no-cpprt/;
1050                 }
1051         if ($iccver>=10)
1052                 {
1053                 $config{lflags}=~s/-i-static/-static-intel/;
1054                 }
1055         if ($iccver>=11)
1056                 {
1057                 $config{cflags}.=" -no-intel-extensions";       # disable Cilk
1058                 $config{lflags}=~s/-no-cpprt/-no-cxxlib/;
1059                 }
1060         }
1061
1062 # Unlike other OSes (like Solaris, Linux, Tru64, IRIX) BSD run-time
1063 # linkers (tested OpenBSD, NetBSD and FreeBSD) "demand" RPATH set on
1064 # .so objects. Apparently application RPATH is not global and does
1065 # not apply to .so linked with other .so. Problem manifests itself
1066 # when libssl.so fails to load libcrypto.so. One can argue that we
1067 # should engrave this into Makefile.shared rules or into BSD-* config
1068 # lines above. Meanwhile let's try to be cautious and pass -rpath to
1069 # linker only when --prefix is not /usr.
1070 if ($target =~ /^BSD-/)
1071         {
1072         $target{shared_ldflag}.=" -Wl,-rpath,\$\$(LIBRPATH)" if ($config{prefix} !~ m|^/usr[/]*$|);
1073         }
1074
1075 if ($target{sys_id} ne "")
1076         {
1077         #$config{cflags}="-DOPENSSL_SYS_$target{sys_id} $config{cflags}";
1078         push @{$config{openssl_sys_defines}}, "OPENSSL_SYS_$target{sys_id}";
1079         }
1080
1081 if ($target{ranlib} eq "")
1082         {
1083         $target{ranlib} = $default_ranlib;
1084         }
1085
1086 if (!$no_asm) {
1087     $target{cpuid_obj}=$table{BASE}->{cpuid_obj} if ($config{processor} eq "386");
1088     $target{cpuid_obj}.=" uplink.o uplink-x86.o" if ($config{cflags} =~ /-DOPENSSL_USE_APPLINK/);
1089
1090     $target{bn_obj} =~ s/\w+-gf2m.o// if (defined($disabled{ec2m}));
1091
1092     # bn-586 is the only one implementing bn_*_part_words
1093     $config{cflags}.=" -DOPENSSL_BN_ASM_PART_WORDS" if ($target{bn_obj} =~ /bn-586/);
1094     $config{cflags}.=" -DOPENSSL_IA32_SSE2" if (!$no_sse2 && $target{bn_obj} =~ /86/);
1095
1096     $config{cflags}.=" -DOPENSSL_BN_ASM_MONT" if ($target{bn_obj} =~ /-mont/);
1097     $config{cflags}.=" -DOPENSSL_BN_ASM_MONT5" if ($target{bn_obj} =~ /-mont5/);
1098     $config{cflags}.=" -DOPENSSL_BN_ASM_GF2m" if ($target{bn_obj} =~ /-gf2m/);
1099
1100     if ($config{fips}) {
1101         push @{$config{openssl_other_defines}}, "OPENSSL_FIPS";
1102     }
1103
1104     if ($target{sha1_obj} =~ /\.o$/) {
1105         $config{cflags}.=" -DSHA1_ASM"   if ($target{sha1_obj} =~ /sx86/ || $target{sha1_obj} =~ /sha1/);
1106         $config{cflags}.=" -DSHA256_ASM" if ($target{sha1_obj} =~ /sha256/);
1107         $config{cflags}.=" -DSHA512_ASM" if ($target{sha1_obj} =~ /sha512/);
1108         if ($target{sha1_obj} =~ /sse2/) {
1109             if ($no_sse2) {
1110                 $target{sha1_obj} =~ s/\S*sse2\S+//;
1111             } elsif ($config{cflags} !~ /OPENSSL_IA32_SSE2/) {
1112                 $config{cflags}.=" -DOPENSSL_IA32_SSE2";
1113             }
1114         }
1115     }
1116     if ($target{md5_obj} =~ /\.o$/) {
1117         $config{cflags}.=" -DMD5_ASM";
1118     }
1119     $target{cast_obj}=$table{BASE}->{cast_obj} if (!$config{no_shared}); # CAST assembler is not PIC
1120     if ($target{rmd160_obj} =~ /\.o$/) {
1121         $config{cflags}.=" -DRMD160_ASM";
1122     }
1123     if ($target{aes_obj} =~ /\.o$/) {
1124         $config{cflags}.=" -DAES_ASM" if ($target{aes_obj} =~ m/\baes-/);;
1125         # aes-ctr.o is not a real file, only indication that assembler
1126         # module implements AES_ctr32_encrypt...
1127         $config{cflags}.=" -DAES_CTR_ASM" if ($target{aes_obj} =~ s/\s*aes-ctr\.o//);
1128         # aes-xts.o indicates presence of AES_xts_[en|de]crypt...
1129         $config{cflags}.=" -DAES_XTS_ASM" if ($target{aes_obj} =~ s/\s*aes-xts\.o//);
1130         $target{aes_obj} =~ s/\s*(vpaes|aesni)-x86\.o//g if ($no_sse2);
1131         $config{cflags}.=" -DVPAES_ASM" if ($target{aes_obj} =~ m/vpaes/);
1132         $config{cflags}.=" -DBSAES_ASM" if ($target{aes_obj} =~ m/bsaes/);
1133     }
1134     if ($target{wp_obj} =~ /mmx/ && $config{processor} eq "386") {
1135         $target{wp_obj}=$table{BASE}->{wp_obj};
1136     } elsif (!$disabled{"whirlpool"}) {
1137         $config{cflags}.=" -DWHIRLPOOL_ASM";
1138     }
1139     if ($target{modes_obj} =~ /ghash-/) {
1140         $config{cflags}.=" -DGHASH_ASM";
1141     }
1142     if ($target{ec_obj} =~ /ecp_nistz256/) {
1143         $config{cflags}.=" -DECP_NISTZ256_ASM";
1144     }
1145     if ($target{poly1305_obj} =~ /\.o$/) {
1146         $config{cflags}.=" -DPOLY1305_ASM";
1147     }
1148 }
1149
1150 $config{makedepprog} = "makedepend";
1151 if ($target{cc} eq "gcc" || ($target{cc} eq 'cc' && $config{target} =~ /darwin/)) {
1152     $config{makedepprog} = $target{cc};
1153 }
1154 # On different platforms, shared library suffixes takes interesting forms.
1155 # On Most Unixen, it's .so.{version} or .sl.{version}, while on MacOS X,
1156 # it's .{version}.dylib.  We're want to separate the two so we can calculate
1157 # symlinks.
1158 # FIXME: is this actually needed any more?  Makefile.shared seems to just
1159 # symlink a file name without SOVER to the file with full SOVER, nothing in
1160 # between.
1161 if ($target{shared_extension} =~ /^(|(?<e>\.s[ol])(?<v>\..*)|(?<v>\..*)(?<e>\.dylib))$/) {
1162     my @vernums = split /\./, $+{v};
1163     shift @vernums;             # Because the initial period in shlib_extension.
1164     my @s = ();
1165     while (@vernums) {
1166         pop @vernums;
1167         push @s, join(".", $+{e} eq ".dylib" ? "" : $+{e},
1168                       @vernums,
1169                       $+{e} eq ".dylib" ? $+{e} : () );
1170     }
1171     $config{shared_link_extensions} = join(" ", @s);
1172 } else {
1173     $config{shared_link_extensions} = "";
1174 }
1175 $config{depflags} =~ s/^\s*//;
1176
1177
1178 # Deal with bn_ops ###################################################
1179
1180 $config{des_ptr}                =0;
1181 $config{des_risc1}              =0;
1182 $config{des_risc2}              =0;
1183 $config{des_unroll}             =0;
1184 $config{bn_ll}                  =0;
1185 $config{rc4_idx}                =0;
1186 $config{bf_ptr}                 =0;
1187 $config{export_var_as_fn}       =0;
1188 my $def_int="unsigned int";
1189 $config{rc4_int}                =$def_int;
1190 $config{rc4_chunk}              ="";
1191 $config{md2_int}                =$def_int;
1192 $config{idea_int}               =$def_int;
1193 $config{rc2_int}                =$def_int;
1194 ($config{b64l},$config{b64},$config{b32},$config{b16},$config{b8})=(0,0,1,0,0);
1195
1196 $config{des_int} = "unsigned long";
1197
1198 foreach (sort split(/\s+/,$target{bn_ops})) {
1199     $config{des_ptr}=1                          if /DES_PTR/;
1200     $config{des_risc1}=1                        if /DES_RISC1/;
1201     $config{des_risc2}=1                        if /DES_RISC2/;
1202     $config{des_unroll}=1                       if /DES_UNROLL/;
1203     $config{des_int}="unsigned int"             if /DES_INT/;
1204     $config{bn_ll}=1                            if /BN_LLONG/;
1205     $config{rc4_int}="unsigned char"            if /RC4_CHAR/;
1206     $config{rc4_int}="unsigned long"            if /RC4_LONG/;
1207     $config{rc4_idx}=1                          if /RC4_INDEX/;
1208     $config{rc4_chunk}="unsigned long"          if /RC4_CHUNK/;
1209     $config{rc4_chunk}="unsigned long long"     if /RC4_CHUNK_LL/;
1210     $config{md2_int}="unsigned char"            if /MD2_CHAR/;
1211     $config{md2_int}="unsigned long"            if /MD2_LONG/;
1212     $config{idea_int}="unsigned char"           if /IDEA_CHAR/;
1213     $config{idea_int}="unsigned long"           if /IDEA_LONG/;
1214     $config{rc2_int}="unsigned char"            if /RC2_CHAR/;
1215     $config{rc2_int}="unsigned long"            if /RC2_LONG/;
1216     $config{bf_ptr}=1                           if $_ eq "BF_PTR";
1217     $config{bf_ptr}=2                           if $_ eq "BF_PTR2";
1218     ($config{b64l},$config{b64},$config{b32},$config{b16},$config{b8})
1219         =(0,1,0,0,0)                            if /SIXTY_FOUR_BIT/;
1220     ($config{b64l},$config{b64},$config{b32},$config{b16},$config{b8})
1221         =(1,0,0,0,0)                            if /SIXTY_FOUR_BIT_LONG/;
1222     ($config{b64l},$config{b64},$config{b32},$config{b16},$config{b8})
1223         =(0,0,1,0,0)                            if /THIRTY_TWO_BIT/;
1224     ($config{b64l},$config{b64},$config{b32},$config{b16},$config{b8})
1225         =(0,0,0,1,0)                            if /SIXTEEN_BIT/;
1226     ($config{b64l},$config{b64},$config{b32},$config{b16},$config{b8})
1227         =(0,0,0,0,1)                            if /EIGHT_BIT/;
1228     $config{export_var_as_fn}=1                 if /EXPORT_VAR_AS_FN/;
1229 }
1230
1231
1232 # Hack cflags for better warnings (dev option) #######################
1233
1234 # "Stringify" the C flags string.  This permits it to be made part of a string
1235 # and works as well on command lines.
1236 $config{cflags} =~ s/([\\\"])/\\\1/g;
1237
1238 if (defined($config{api})) {
1239     $config{openssl_api_defines} = [ "OPENSSL_MIN_API=".$apitable->{$config{api}} ];
1240     my $apiflag = sprintf("-DOPENSSL_API_COMPAT=%s", $apitable->{$config{api}});
1241     $default_depflags .= " $apiflag";
1242     $config{cflags} .= " $apiflag";
1243 }
1244
1245 my $ecc = $target{cc};
1246 $ecc = "clang" if `$target{cc} --version 2>&1` =~ /clang/;
1247
1248 if ($strict_warnings)
1249         {
1250         my $wopt;
1251         die "ERROR --strict-warnings requires gcc or clang" unless ($ecc =~ /gcc(-\d(\.\d)*)?$/ or $ecc =~ /clang$/);
1252         foreach $wopt (split /\s+/, $gcc_devteam_warn)
1253                 {
1254                 $config{cflags} .= " $wopt" unless ($config{cflags} =~ /(^|\s)$wopt(\s|$)/)
1255                 }
1256         if ($ecc eq "clang")
1257                 {
1258                 foreach $wopt (split /\s+/, $clang_devteam_warn)
1259                         {
1260                         $config{cflags} .= " $wopt" unless ($config{cflags} =~ /(^|\s)$wopt(\s|$)/)
1261                         }
1262                 }
1263         if ($target !~ /^mingw/)
1264                 {
1265                 foreach $wopt (split /\s+/, $memleak_devteam_backtrace)
1266                         {
1267                         $config{cflags} .= " $wopt" unless ($config{cflags} =~ /(^|\s)$wopt(\s|$)/)
1268                         }
1269                 if ($target =~ /^BSD-/)
1270                         {
1271                         $config{lflags} .= " -lexecinfo";
1272                         }
1273                 }
1274         }
1275
1276 # Write down our configuration where it fits #########################
1277
1278 open(OUT,">configdata.pm") || die "unable to create configdata.pm: $!\n";
1279 print OUT <<"EOF";
1280 package configdata;
1281
1282 use strict;
1283 use warnings;
1284
1285 use Exporter;
1286 #use vars qw(\@ISA \@EXPORT);
1287 our \@ISA = qw(Exporter);
1288 our \@EXPORT = qw(\%config \%target %withargs);
1289
1290 EOF
1291 print OUT "our %config = (\n";
1292 foreach (sort keys %config) {
1293     if (ref($config{$_}) eq "ARRAY") {
1294         print OUT "  ", $_, " => [ ", join(", ",
1295                                            map { quotify("perl", $_) }
1296                                            @{$config{$_}}), " ],\n";
1297     } else {
1298         print OUT "  ", $_, " => ", quotify("perl", $config{$_}), ",\n"
1299     }
1300 }
1301 print OUT <<"EOF";
1302 );
1303
1304 EOF
1305 print OUT "our %target = (\n";
1306 foreach (sort keys %target) {
1307     if (ref($target{$_}) eq "ARRAY") {
1308         print OUT "  ", $_, " => [ ", join(", ",
1309                                            map { quotify("perl", $_) }
1310                                            @{$target{$_}}), " ],\n";
1311     } else {
1312         print OUT "  ", $_, " => ", quotify("perl", $target{$_}), ",\n"
1313     }
1314 }
1315 print OUT <<"EOF";
1316 );
1317
1318 EOF
1319 print OUT "our %withargs = (\n";
1320 foreach (sort keys %withargs) {
1321     if (ref($withargs{$_}) eq "ARRAY") {
1322         print OUT "  ", $_, " => [ ", join(", ",
1323                                            map { quotify("perl", $_) }
1324                                            @{$withargs{$_}}), " ],\n";
1325     } else {
1326         print OUT "  ", $_, " => ", quotify("perl", $withargs{$_}), ",\n"
1327     }
1328 }
1329 print OUT <<"EOF";
1330 );
1331
1332 1;
1333 EOF
1334 close(OUT);
1335
1336 print "IsMK1MF       =", ($target{build_scheme}->[0] eq "mk1mf" ? "yes" : "no"), "\n";
1337 print "CC            =$target{cc}\n";
1338 print "CFLAG         =$config{cflags}\n";
1339 print "EX_LIBS       =$config{lflags}\n";
1340 print "CPUID_OBJ     =$target{cpuid_obj}\n";
1341 print "BN_ASM        =$target{bn_obj}\n";
1342 print "EC_ASM        =$target{ec_obj}\n";
1343 print "DES_ENC       =$target{des_obj}\n";
1344 print "AES_ENC       =$target{aes_obj}\n";
1345 print "BF_ENC        =$target{bf_obj}\n";
1346 print "CAST_ENC      =$target{cast_obj}\n";
1347 print "RC4_ENC       =$target{rc4_obj}\n";
1348 print "RC5_ENC       =$target{rc5_obj}\n";
1349 print "MD5_OBJ_ASM   =$target{md5_obj}\n";
1350 print "SHA1_OBJ_ASM  =$target{sha1_obj}\n";
1351 print "RMD160_OBJ_ASM=$target{rmd160_obj}\n";
1352 print "CMLL_ENC      =$target{cmll_obj}\n";
1353 print "MODES_OBJ     =$target{modes_obj}\n";
1354 print "ENGINES_OBJ   =$target{engines_obj}\n";
1355 print "CHACHA_ENC    =$target{chacha_obj}\n";
1356 print "POLY1305_OBJ  =$target{poly1305_obj}\n";
1357 print "PROCESSOR     =$config{processor}\n";
1358 print "RANLIB        =$target{ranlib}\n";
1359 print "ARFLAGS       =$target{arflags}\n";
1360 print "PERL          =$config{perl}\n";
1361
1362 run_dofile("$Makefile.in","$Makefile.new");
1363
1364 run_dofile("include/openssl/opensslconf.h.in", "include/openssl/opensslconf.h");
1365
1366 run_dofile("include/openssl/opensslconf.h.in", "include/openssl/opensslconf.h");
1367
1368 foreach my $alg ( 'bf', 'bn', 'des', 'rc4' ) {
1369     run_dofile("crypto/include/internal/${alg}_conf.h.in",
1370                "crypto/include/internal/${alg}_conf.h");
1371 }
1372
1373 # Fix the date
1374
1375 print "SIXTY_FOUR_BIT_LONG mode\n" if $config{b64l};
1376 print "SIXTY_FOUR_BIT mode\n" if $config{b64};
1377 print "THIRTY_TWO_BIT mode\n" if $config{b32};
1378 print "SIXTEEN_BIT mode\n" if $config{b16};
1379 print "EIGHT_BIT mode\n" if $config{b8};
1380 print "DES_PTR used\n" if $config{des_ptr};
1381 print "DES_RISC1 used\n" if $config{des_risc1};
1382 print "DES_RISC2 used\n" if $config{des_risc2};
1383 print "DES_UNROLL used\n" if $config{des_unroll};
1384 print "DES_INT used\n" if $config{des_int} =~ / int$/;
1385 print "BN_LLONG mode\n" if $config{bn_ll};
1386 print "RC4 uses $config{rc4_int}\n" if $config{rc4_int} != $def_int;
1387 print "RC4_INDEX mode\n" if $config{rc4_idx};
1388 print "RC4_CHUNK is undefined\n" unless $config{rc4_chunk};
1389 print "RC4_CHUNK is $config{rc4_chunk}\n" if $config{rc4_chunk};
1390 print "MD2 uses $config{md2_int}\n" if $config{md2_int} != $def_int;
1391 print "IDEA uses $config{idea_int}\n" if $config{idea_int} != $def_int;
1392 print "RC2 uses $config{rc2_int}\n" if $config{rc2_int} != $def_int;
1393 print "BF_PTR used\n" if $config{bf_ptr} == 1;
1394 print "BF_PTR2 used\n" if $config{bf_ptr} == 2;
1395
1396 # Copy all Makefile.in to Makefile (except top-level)
1397 use File::Find;
1398 use IO::File;
1399 find(sub {
1400         return if ($_ ne "Makefile.in" || $File::Find::dir eq ".");
1401         my $in = IO::File->new($_, "r") or
1402             die sprintf "Error reading Makefile.in in %s: !$\n",
1403                 $File::Find::dir;
1404         my $out = IO::File->new("Makefile", "w") or
1405             die sprintf "Error writing Makefile in %s: !$\n",
1406                 $File::Find::dir;
1407         print $out "# Generated from $_, do not edit\n";
1408         while (my $line = <$in>) { print $out $line }
1409         $in->close() or
1410             die sprintf "Error reading Makefile.in in %s: !$\n",
1411                 $File::Find::dir;
1412         $out->close() or
1413             die sprintf "Error writing Makefile in %s: !$\n",
1414                 $File::Find::dir;
1415     }, ".");
1416
1417 my %builders = (
1418     unixmake => sub {
1419         my $make_command = "$make PERL=\'$config{perl}\'";
1420         my $make_targets = "";
1421         $make_targets .= " depend" if $config{depflags} ne $default_depflags && $make_depend;
1422         (system $make_command.$make_targets) == 0 or die "make $make_targets failed"
1423             if $make_targets ne "";
1424         if ($config{depflags} ne $default_depflags && !$make_depend) {
1425             $warn_make_depend++;
1426         }
1427     },
1428     mk1mf => sub {
1429         open (OUT,">crypto/buildinf.h") || die "Can't open buildinf.h";
1430         printf OUT <<"EOF";
1431 #ifndef MK1MF_BUILD
1432   /* auto-generated by Configure for crypto/cversion.c:
1433    * for Unix builds, crypto/Makefile.ssl generates functional definitions;
1434    * Windows builds (and other mk1mf builds) compile cversion.c with
1435    * -DMK1MF_BUILD and use definitions added to this file by util/mk1mf.pl. */
1436   #error "Windows builds (PLATFORM=$target) use mk1mf.pl-created Makefiles"
1437 #endif
1438 EOF
1439         close(OUT);
1440
1441         # create the ms/version32.rc file if needed
1442         if (! grep /^netware/, @{$target{build_scheme}}) {
1443             my ($v1, $v2, $v3, $v4);
1444             if ($config{version_num} =~ /^0x([0-9a-f]{1})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{1})L$/i) {
1445                 $v1=hex $1;
1446                 $v2=hex $2;
1447                 $v3=hex $3;
1448                 $v4=hex $4;
1449             }
1450             open (OUT,">ms/version32.rc") || die "Can't open ms/version32.rc";
1451             print OUT <<"EOF";
1452 #include <winver.h>
1453
1454 LANGUAGE 0x09,0x01
1455
1456 1 VERSIONINFO
1457   FILEVERSION $v1,$v2,$v3,$v4
1458   PRODUCTVERSION $v1,$v2,$v3,$v4
1459   FILEFLAGSMASK 0x3fL
1460 #ifdef _DEBUG
1461   FILEFLAGS 0x01L
1462 #else
1463   FILEFLAGS 0x00L
1464 #endif
1465   FILEOS VOS__WINDOWS32
1466   FILETYPE VFT_DLL
1467   FILESUBTYPE 0x0L
1468 BEGIN
1469     BLOCK "StringFileInfo"
1470     BEGIN
1471         BLOCK "040904b0"
1472         BEGIN
1473             // Required:
1474             VALUE "CompanyName", "The OpenSSL Project, http://www.openssl.org/\\0"
1475             VALUE "FileDescription", "OpenSSL Shared Library\\0"
1476             VALUE "FileVersion", "$config{version}\\0"
1477 #if defined(CRYPTO)
1478             VALUE "InternalName", "libeay32\\0"
1479             VALUE "OriginalFilename", "libeay32.dll\\0"
1480 #elif defined(SSL)
1481             VALUE "InternalName", "ssleay32\\0"
1482             VALUE "OriginalFilename", "ssleay32.dll\\0"
1483 #endif
1484             VALUE "ProductName", "The OpenSSL Toolkit\\0"
1485             VALUE "ProductVersion", "$config{version}\\0"
1486             // Optional:
1487             //VALUE "Comments", "\\0"
1488             VALUE "LegalCopyright", "Copyright Â© 1998-2015 The OpenSSL Project. Copyright Â© 1995-1998 Eric A. Young, Tim J. Hudson. All rights reserved.\\0"
1489             //VALUE "LegalTrademarks", "\\0"
1490             //VALUE "PrivateBuild", "\\0"
1491             //VALUE "SpecialBuild", "\\0"
1492         END
1493     END
1494     BLOCK "VarFileInfo"
1495     BEGIN
1496         VALUE "Translation", 0x409, 0x4b0
1497     END
1498 END
1499 EOF
1500             close(OUT);
1501         }
1502     },
1503     );
1504
1505 my ($builder, @builder_opts) = @{$target{build_scheme}};
1506 $builders{$builder}->(@builder_opts);
1507
1508 print <<"EOF";
1509
1510 Configured for $target.
1511 EOF
1512
1513 print <<"EOF" if (!$no_threads && !$threads);
1514
1515 The library could not be configured for supporting multi-threaded
1516 applications as the compiler options required on this system are not known.
1517 See file INSTALL for details if you need multi-threading.
1518 EOF
1519
1520 print <<"EOF" if ($no_shared_warn);
1521
1522 You gave the option 'shared', which is not supported on this platform, so
1523 we will pretend you gave the option 'no-shared'.  If you know how to implement
1524 shared libraries, please let us know (but please first make sure you have
1525 tried with a current version of OpenSSL).
1526 EOF
1527
1528 print <<"EOF" if ($warn_make_depend);
1529
1530 *** Because of configuration changes, you MUST do the following before
1531 *** building:
1532
1533         make depend
1534 EOF
1535
1536 exit(0);
1537
1538 ######################################################################
1539 #
1540 # Helpers and utility functions
1541 #
1542
1543 # Configuration file reading #########################################
1544
1545 # Helper function to implement conditional inheritance depending on the
1546 # value of $no_asm.  Used in inherit_from values as follows:
1547 #
1548 #      inherit_from => [ "template", asm("asm_tmpl") ]
1549 #
1550 sub asm {
1551     my @x = @_;
1552     sub {
1553         $no_asm ? () : @x;
1554     }
1555 }
1556
1557 # Helper function to implement adding values to already existing configuration
1558 # values.  It handles elements that are ARRAYs, CODEs and scalars
1559 sub _add {
1560     my $separator = shift;
1561
1562     # If there's any ARRAY in the collection of values, we will return
1563     # an ARRAY of combined values, otherwise a string of joined values
1564     # with $separator as the separator.
1565     my $found_array = 0;
1566
1567     my @values =
1568         map {
1569             if (ref($_) eq "ARRAY") {
1570                 $found_array = 1;
1571                 @$_;
1572             } else {
1573                 $_;
1574             }
1575     } (@_);
1576
1577     if ($found_array) {
1578         [ @values ];
1579     } else {
1580         join($separator, @values);
1581     }
1582 }
1583 sub add_before {
1584     my $separator = shift;
1585     my @x = @_;
1586     sub { _add($separator, @x, @_) };
1587 }
1588 sub add {
1589     my $separator = shift;
1590     my @x = @_;
1591     sub { _add($separator, @_, @x) };
1592 }
1593
1594 # configuration reader, evaluates the input file as a perl script and expects
1595 # it to fill %targets with target configurations.  Those are then added to
1596 # %table.
1597 sub read_config {
1598     my $fname = shift;
1599     open(CONFFILE, "< $fname")
1600         or die "Can't open configuration file '$fname'!\n";
1601     my $x = $/;
1602     undef $/;
1603     my $content = <CONFFILE>;
1604     $/ = $x;
1605     close(CONFFILE);
1606     my %targets = ();
1607     {
1608         local %table = %::table;    # Protect %table from tampering
1609
1610         eval $content;
1611         warn $@ if $@;
1612     }
1613
1614     # For each target, check that it's configured with a hash table.
1615     foreach (keys %targets) {
1616         if (ref($targets{$_}) ne "HASH") {
1617             if (ref($targets{$_}) eq "") {
1618                 warn "Deprecated target configuration for $_, ignoring...\n";
1619             } else {
1620                 warn "Misconfigured target configuration for $_ (should be a hash table), ignoring...\n";
1621             }
1622             delete $targets{$_};
1623         }
1624     }
1625
1626     %table = (%table, %targets);
1627
1628 }
1629
1630 # configuration resolver.  Will only resolve all the lazy evalutation
1631 # codeblocks for the chozen target and all those it inherits from,
1632 # recursively
1633 sub resolve_config {
1634     my $target = shift;
1635     my @breadcrumbs = @_;
1636
1637     if (grep { $_ eq $target } @breadcrumbs) {
1638         die "inherit_from loop!  target backtrace:\n  "
1639             ,$target,"\n  ",join("\n  ", @breadcrumbs),"\n";
1640     }
1641
1642     if (!defined($table{$target})) {
1643         warn "Warning! target $target doesn't exist!\n";
1644         return ();
1645     }
1646     # Recurse through all inheritances.  They will be resolved on the
1647     # fly, so when this operation is done, they will all just be a
1648     # bunch of attributes with string values.
1649     # What we get here, though, are keys with references to lists of
1650     # the combined values of them all.  We will deal with lists after
1651     # this stage is done.
1652     my %combined_inheritance = ();
1653     if ($table{$target}->{inherit_from}) {
1654         my @inherit_from =
1655             map { ref($_) eq "CODE" ? $_->() : $_ } @{$table{$target}->{inherit_from}};
1656         foreach (@inherit_from) {
1657             my %inherited_config = resolve_config($_, $target, @breadcrumbs);
1658
1659             # 'template' is a marker that's considered private to
1660             # the config that had it.
1661             delete $inherited_config{template};
1662
1663             map {
1664                 if (!$combined_inheritance{$_}) {
1665                     $combined_inheritance{$_} = [];
1666                 }
1667                 push @{$combined_inheritance{$_}}, $inherited_config{$_};
1668             } keys %inherited_config;
1669         }
1670     }
1671
1672     # We won't need inherit_from in this target any more, since we've
1673     # resolved all the inheritances that lead to this
1674     delete $table{$target}->{inherit_from};
1675
1676     # Now is the time to deal with those lists.  Here's the place to
1677     # decide what shall be done with those lists, all based on the
1678     # values of the target we're currently dealing with.
1679     # - If a value is a coderef, it will be executed with the list of
1680     #   inherited values as arguments.
1681     # - If the corresponding key doesn't have a value at all or is the
1682     #   emoty string, the inherited value list will be run through the
1683     #   default combiner (below), and the result becomes this target's
1684     #   value.
1685     # - Otherwise, this target's value is assumed to be a string that
1686     #   will simply override the inherited list of values.
1687     my $default_combiner = add(" ");
1688
1689     my %all_keys =
1690         map { $_ => 1 } (keys %combined_inheritance,
1691                          keys %{$table{$target}});
1692     foreach (sort keys %all_keys) {
1693
1694         # Current target doesn't have a value for the current key?
1695         # Assign it the default combiner, the rest of this loop body
1696         # will handle it just like any other coderef.
1697         if (!exists $table{$target}->{$_}) {
1698             $table{$target}->{$_} = $default_combiner;
1699         }
1700
1701         my $valuetype = ref($table{$target}->{$_});
1702         if ($valuetype eq "CODE") {
1703             # CODE reference, execute it with the inherited values as
1704             # arguments.
1705             $table{$target}->{$_} =
1706                 $table{$target}->{$_}->(@{$combined_inheritance{$_}});
1707         } elsif ($valuetype eq "ARRAY" || $valuetype eq "") {
1708             # ARRAY or Scalar, just leave it as is.
1709         } else {
1710             # Some other type of reference that we don't handle.
1711             # Better to abort at this point.
1712             die "cannot handle reference type $valuetype,"
1713                 ," found in target $target -> $_\n";
1714         }
1715     }
1716
1717     # Finally done, return the result.
1718     return %{$table{$target}};
1719 }
1720
1721 sub usage
1722         {
1723         print STDERR $usage;
1724         print STDERR "\npick os/compiler from:\n";
1725         my $j=0;
1726         my $i;
1727         my $k=0;
1728         foreach $i (sort keys %table)
1729                 {
1730                 next if $table{$i}->{template};
1731                 next if $i =~ /^debug/;
1732                 $k += length($i) + 1;
1733                 if ($k > 78)
1734                         {
1735                         print STDERR "\n";
1736                         $k=length($i);
1737                         }
1738                 print STDERR $i . " ";
1739                 }
1740         foreach $i (sort keys %table)
1741                 {
1742                 next if $table{$i}->{template};
1743                 next if $i !~ /^debug/;
1744                 $k += length($i) + 1;
1745                 if ($k > 78)
1746                         {
1747                         print STDERR "\n";
1748                         $k=length($i);
1749                         }
1750                 print STDERR $i . " ";
1751                 }
1752         print STDERR "\n\nNOTE: If in doubt, on Unix-ish systems use './config'.\n";
1753         exit(1);
1754         }
1755
1756 sub run_dofile()
1757 {
1758     my $in = shift;
1759     my $out = shift;
1760
1761     # should we remove $out ?
1762     system("$config{perl} -I. -Mconfigdata util/dofile.pl <$in >$out.new");
1763     exit 1 if $? != 0;
1764     rename("$out.new", $out) || die "Can't rename $out.new, $!";
1765 }
1766
1767 # Configuration printer ##############################################
1768
1769 sub print_table_entry
1770 {
1771     my $target = shift;
1772     my %target = resolve_config($target);
1773     my $type = shift;
1774
1775     # Don't print the templates
1776     return if $target{template};
1777
1778     my @sequence = (
1779         "cc",
1780         "cflags",
1781         "debug_cflags",
1782         "release_cflags",
1783         "unistd",
1784         "thread_cflag",
1785         "sys_id",
1786         "lflags",
1787         "debug_lflags",
1788         "release_lflags",
1789         "bn_ops",
1790         "cpuid_obj",
1791         "bn_obj",
1792         "ec_obj",
1793         "des_obj",
1794         "aes_obj",
1795         "bf_obj",
1796         "md5_obj",
1797         "sha1_obj",
1798         "cast_obj",
1799         "rc4_obj",
1800         "rmd160_obj",
1801         "rc5_obj",
1802         "wp_obj",
1803         "cmll_obj",
1804         "modes_obj",
1805         "engines_obj",
1806         "perlasm_scheme",
1807         "dso_scheme",
1808         "shared_target",
1809         "shared_cflag",
1810         "shared_ldflag",
1811         "shared_extension",
1812         "ranlib",
1813         "arflags",
1814         "multilib",
1815         );
1816
1817     if ($type eq "TABLE") {
1818         print "\n";
1819         print "*** $target\n";
1820         printf "\$%-12s = %s\n", $_, $target{$_} foreach (@sequence);
1821     } elsif ($type eq "HASH") {
1822         my $largest =
1823             length((sort { length($a) <=> length($b) } @sequence)[-1]);
1824         print "    '$target' => {\n";
1825         foreach (@sequence) {
1826             if ($target{$_}) {
1827                 print "      '",$_,"'"," " x ($largest - length($_))," => '",$target{$_},"',\n";
1828             }
1829         }
1830         print "    },\n";
1831     }
1832 }
1833
1834 # Utility routines ###################################################
1835
1836 sub which
1837         {
1838         my($name)=@_;
1839         my $path;
1840         foreach $path (split /:/, $ENV{PATH})
1841                 {
1842                 if (-f "$path/$name$target{exe_extension}" and -x _)
1843                         {
1844                         return "$path/$name$target{exe_extension}" unless ($name eq "perl" and
1845                          system("$path/$name$target{exe_extension} -e " . '\'exit($]<5.0);\''));
1846                         }
1847                 }
1848         }
1849
1850 sub print_table_entry
1851         {
1852         my $target = shift;
1853         my %target = resolve_config($target);
1854         my $type = shift;
1855
1856         # Don't print the templates
1857         return if $target{template};
1858
1859         if ($type eq "TABLE") {
1860             print <<"EOF"
1861
1862 *** $target
1863 \$cc           = $target{cc}
1864 \$cflags       = $target{cflags}
1865 \$debug_cflags   = $target{debug_cflags}
1866 \$release_cflags = $target{release_cflags}
1867 \$unistd       = $target{unistd}
1868 \$thread_cflag = $target{thread_cflag}
1869 \$sys_id       = $target{sys_id}
1870 \$lflags       = $target{lflags}
1871 \$debug_lflags   = $target{debug_lflags}
1872 \$release_lflags = $target{release_lflags}
1873 \$bn_ops       = $target{bn_ops}
1874 \$cpuid_obj    = $target{cpuid_obj}
1875 \$bn_obj       = $target{bn_obj}
1876 \$ec_obj       = $target{ec_obj}
1877 \$des_obj      = $target{des_obj}
1878 \$aes_obj      = $target{aes_obj}
1879 \$bf_obj       = $target{bf_obj}
1880 \$md5_obj      = $target{md5_obj}
1881 \$sha1_obj     = $target{sha1_obj}
1882 \$cast_obj     = $target{cast_obj}
1883 \$rc4_obj      = $target{rc4_obj}
1884 \$rmd160_obj   = $target{rmd160_obj}
1885 \$rc5_obj      = $target{rc5_obj}
1886 \$wp_obj       = $target{wp_obj}
1887 \$cmll_obj     = $target{cmll_obj}
1888 \$modes_obj    = $target{modes_obj}
1889 \$engines_obj  = $target{engines_obj}
1890 \$chacha_obj   = $target{chacha_obj}
1891 \$poly1305_obj = $target{poly1305_obj}
1892 \$perlasm_scheme = $target{perlasm_scheme}
1893 \$dso_scheme   = $target{dso_scheme}
1894 \$shared_target= $target{shared_target}
1895 \$shared_cflag = $target{shared_cflag}
1896 \$shared_ldflag = $target{shared_ldflag}
1897 \$shared_extension = $target{shared_extension}
1898 \$ranlib       = $target{ranlib}
1899 \$arflags      = $target{arflags}
1900 \$multilib     = $target{multilib}
1901 EOF
1902         } elsif ($type eq "HASH") {
1903             my @sequence = (
1904                 "cc",
1905                 "cflags",
1906                 "debug_cflags",
1907                 "release_cflags",
1908                 "unistd",
1909                 "thread_cflag",
1910                 "sys_id",
1911                 "lflags",
1912                 "debug_lflags",
1913                 "release_lflags",
1914                 "bn_ops",
1915                 "cpuid_obj",
1916                 "bn_obj",
1917                 "ec_obj",
1918                 "des_obj",
1919                 "aes_obj",
1920                 "bf_obj",
1921                 "md5_obj",
1922                 "sha1_obj",
1923                 "cast_obj",
1924                 "rc4_obj",
1925                 "rmd160_obj",
1926                 "rc5_obj",
1927                 "wp_obj",
1928                 "cmll_obj",
1929                 "modes_obj",
1930                 "engines_obj",
1931                 "chacha_obj",
1932                 "poly1305_obj",
1933                 "perlasm_scheme",
1934                 "dso_scheme",
1935                 "shared_target",
1936                 "shared_cflag",
1937                 "shared_ldflag",
1938                 "shared_extension",
1939                 "ranlib",
1940                 "arflags",
1941                 "multilib",
1942                 );
1943             my $largest =
1944                 length((sort { length($a) <=> length($b) } @sequence)[-1]);
1945             print "    '$target' => {\n";
1946             foreach (@sequence) {
1947                 if ($target{$_}) {
1948                     print "      '",$_,"'"," " x ($largest - length($_))," => '",$target{$_},"',\n";
1949                 }
1950             }
1951             print "    },\n";
1952         }
1953         }
1954
1955 sub quotify {
1956     my %processors = (
1957         perl    => sub { my $x = shift;
1958                          $x =~ s/([\\\$\@"])/\\$1/g;
1959                          return '"'.$x.'"'; },
1960         );
1961     my $for = shift;
1962     my $processor =
1963         defined($processors{$for}) ? $processors{$for} : sub { shift; };
1964
1965     map { $processor->($_); } @_;
1966 }
1967
1968 # collect_information($filename, $line_continue, $regexp => $CODEref, ...)
1969 # $filename is the file to read.
1970 # $line_continue is either undef (which is a noop), or two arguments, where
1971 # the first is a regexp detecting a line continuation ending, and the
1972 # following argument is a CODEref that takes care of concatenating two
1973 # lines.
1974 # All following arguments are regex/CODEref pairs, where the regexp detects a
1975 # line and the CODEref does something with the result of the regexp.
1976 sub collect_information {
1977     my $filename = shift;
1978     my $line_continue_re = shift;
1979     my $line_concat = defined($line_continue_re) ? shift : undef;
1980     my %collectors = @_;
1981
1982     my $saved_line = "";
1983     open IN, $filename || die "unable to read $filename: $!\n";
1984     while(<IN>) {
1985         chomp;
1986         if (defined $line_concat) {
1987             $_ = $line_concat->($saved_line, $_);
1988         }
1989         if (defined $line_continue_re && /$line_continue_re/) {
1990             $saved_line = $_;
1991             next;
1992         }
1993         foreach my $re (keys %collectors) {
1994             if (/$re/) { $collectors{$re}->() };
1995         }
1996     }
1997     close IN;
1998 }