1#!/usr/bin/env perl
2#
3# Copyright The Mbed TLS Contributors
4# SPDX-License-Identifier: Apache-2.0
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18use strict;
19
20my ($include_dir, $data_dir, $feature_file);
21
22if( @ARGV ) {
23    die "Invalid number of arguments" if scalar @ARGV != 3;
24    ($include_dir, $data_dir, $feature_file) = @ARGV;
25
26    -d $include_dir or die "No such directory: $include_dir\n";
27    -d $data_dir or die "No such directory: $data_dir\n";
28} else {
29    $include_dir = 'include/mbedtls';
30    $data_dir = 'scripts/data_files';
31    $feature_file = 'library/version_features.c';
32
33    unless( -d $include_dir && -d $data_dir ) {
34        chdir '..' or die;
35        -d $include_dir && -d $data_dir
36            or die "Without arguments, must be run from root or scripts\n"
37    }
38}
39
40my $feature_format_file = $data_dir.'/version_features.fmt';
41
42my @sections = ( "System support", "mbed TLS modules",
43                 "mbed TLS feature support" );
44
45my $line_separator = $/;
46undef $/;
47
48open(FORMAT_FILE, "$feature_format_file") or die "Opening feature format file '$feature_format_file': $!";
49my $feature_format = <FORMAT_FILE>;
50close(FORMAT_FILE);
51
52$/ = $line_separator;
53
54open(CONFIG_H, "$include_dir/config.h") || die("Failure when opening config.h: $!");
55
56my $feature_defines = "";
57my $in_section = 0;
58
59while (my $line = <CONFIG_H>)
60{
61    next if ($in_section && $line !~ /#define/ && $line !~ /SECTION/);
62    next if (!$in_section && $line !~ /SECTION/);
63
64    if ($in_section) {
65        if ($line =~ /SECTION/) {
66            $in_section = 0;
67            next;
68        }
69
70        my ($define) = $line =~ /#define (\w+)/;
71        $feature_defines .= "#if defined(${define})\n";
72        $feature_defines .= "    \"${define}\",\n";
73        $feature_defines .= "#endif /* ${define} */\n";
74    }
75
76    if (!$in_section) {
77        my ($section_name) = $line =~ /SECTION: ([\w ]+)/;
78        my $found_section = grep $_ eq $section_name, @sections;
79
80        $in_section = 1 if ($found_section);
81    }
82};
83
84$feature_format =~ s/FEATURE_DEFINES\n/$feature_defines/g;
85
86open(ERROR_FILE, ">$feature_file") or die "Opening destination file '$feature_file': $!";
87print ERROR_FILE $feature_format;
88close(ERROR_FILE);
89