1#!/usr/bin/env perl
2#
3# Copyright The Mbed TLS Contributors
4# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
5
6use strict;
7
8my ($include_dir, $data_dir, $feature_file);
9
10if( @ARGV ) {
11    die "Invalid number of arguments" if scalar @ARGV != 3;
12    ($include_dir, $data_dir, $feature_file) = @ARGV;
13
14    -d $include_dir or die "No such directory: $include_dir\n";
15    -d $data_dir or die "No such directory: $data_dir\n";
16} else {
17    $include_dir = 'include/mbedtls';
18    $data_dir = 'scripts/data_files';
19    $feature_file = 'library/version_features.c';
20
21    unless( -d $include_dir && -d $data_dir ) {
22        chdir '..' or die;
23        -d $include_dir && -d $data_dir
24            or die "Without arguments, must be run from root or scripts\n"
25    }
26}
27
28my $feature_format_file = $data_dir.'/version_features.fmt';
29
30my @sections = ( "System support", "Mbed TLS modules",
31                 "Mbed TLS feature support" );
32
33my $line_separator = $/;
34undef $/;
35
36open(FORMAT_FILE, '<:crlf', "$feature_format_file") or die "Opening feature format file '$feature_format_file': $!";
37my $feature_format = <FORMAT_FILE>;
38close(FORMAT_FILE);
39
40$/ = $line_separator;
41
42open(CONFIG_H, '<:crlf', "$include_dir/mbedtls_config.h") || die("Failure when opening mbedtls_config.h: $!");
43
44my $feature_defines = "";
45my $in_section = 0;
46
47while (my $line = <CONFIG_H>)
48{
49    next if ($in_section && $line !~ /#define/ && $line !~ /SECTION/);
50    next if (!$in_section && $line !~ /SECTION/);
51
52    if ($in_section) {
53        if ($line =~ /SECTION/) {
54            $in_section = 0;
55            next;
56        }
57        # Strip leading MBEDTLS_ to save binary size
58        my ($mbedtls_prefix, $define) = $line =~ /#define (MBEDTLS_)?(\w+)/;
59        if (!$mbedtls_prefix) {
60            die "Feature does not start with 'MBEDTLS_': $line\n";
61        }
62        $feature_defines .= "#if defined(MBEDTLS_${define})\n";
63        $feature_defines .= "    \"${define}\", //no-check-names\n";
64        $feature_defines .= "#endif /* MBEDTLS_${define} */\n";
65    }
66
67    if (!$in_section) {
68        my ($section_name) = $line =~ /SECTION: ([\w ]+)/;
69        my $found_section = grep $_ eq $section_name, @sections;
70
71        $in_section = 1 if ($found_section);
72    }
73};
74
75$feature_format =~ s/FEATURE_DEFINES\n/$feature_defines/g;
76
77open(ERROR_FILE, ">$feature_file") or die "Opening destination file '$feature_file': $!";
78print ERROR_FILE $feature_format;
79close(ERROR_FILE);
80