1#!/usr/bin/env perl
2
3# Generate error.c
4#
5# Usage: ./generate_errors.pl or scripts/generate_errors.pl without arguments,
6# or generate_errors.pl crypto_include_dir tls_include_dir data_dir error_file
7#
8# Copyright The Mbed TLS Contributors
9# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
10
11use strict;
12use warnings;
13
14my ($crypto_include_dir, $tls_include_dir, $data_dir, $error_file);
15
16if( @ARGV ) {
17    die "Invalid number of arguments" if scalar @ARGV != 4;
18    ($crypto_include_dir, $tls_include_dir, $data_dir, $error_file) = @ARGV;
19
20    -d $crypto_include_dir or die "No such directory: $crypto_include_dir\n";
21    -d $tls_include_dir or die "No such directory: $tls_include_dir\n";
22    -d $data_dir or die "No such directory: $data_dir\n";
23} else {
24    $crypto_include_dir = 'tf-psa-crypto/drivers/builtin/include/mbedtls';
25    $tls_include_dir = 'include/mbedtls';
26    $data_dir = 'scripts/data_files';
27    $error_file = 'library/error.c';
28
29    unless( -d $crypto_include_dir && -d $tls_include_dir && -d $data_dir ) {
30        chdir '..' or die;
31        -d $crypto_include_dir && -d $tls_include_dir && -d $data_dir
32            or die "Without arguments, must be run from root or scripts\n"
33    }
34}
35
36my $error_format_file = $data_dir.'/error.fmt';
37
38my @low_level_modules = qw( AES ARIA ASN1 BASE64 BIGNUM
39                            CAMELLIA CCM CHACHA20 CHACHAPOLY CMAC CTR_DRBG
40                            ENTROPY ERROR GCM HKDF HMAC_DRBG LMS MD5
41                            NET PBKDF2 PLATFORM POLY1305 RIPEMD160
42                            SHA1 SHA256 SHA512 SHA3 THREADING );
43my @high_level_modules = qw( CIPHER ECP MD
44                             PEM PK PKCS12 PKCS5
45                             RSA SSL X509 PKCS7 );
46
47undef $/;
48
49open(FORMAT_FILE, '<:crlf', "$error_format_file") or die "Opening error format file '$error_format_file': $!";
50my $error_format = <FORMAT_FILE>;
51close(FORMAT_FILE);
52
53my @files = glob qq("$crypto_include_dir/*.h");
54push(@files, glob qq("$tls_include_dir/*.h"));
55
56push(@files, glob qq("$crypto_include_dir/private/*.h"));
57push(@files, glob qq("$tls_include_dir/private/*.h"));
58
59my @necessary_include_files;
60my @matches;
61foreach my $file (@files) {
62    open(FILE, '<:crlf', $file) or die("$0: $file: $!");
63    my $content = <FILE>;
64    close FILE;
65    my $found = 0;
66    while ($content =~ m[
67            # Both the before-comment and the after-comment are optional.
68            # Only the comment content is a regex capture group. The comment
69            # start and end parts are outside the capture group.
70            (?:/\*[*!](?!<)             # Doxygen before-comment start
71                ((?:[^*]|\*+[^*/])*)    # $1: Comment content (no */ inside)
72                \*/)?                   # Comment end
73            \s*\#\s*define\s+(MBEDTLS_ERR_\w+)  # $2: name
74            \s+\-(0[Xx][0-9A-Fa-f]+)\s*         # $3: value (without the sign)
75            (?:/\*[*!]<                 # Doxygen after-comment start
76                ((?:[^*]|\*+[^*/])*)    # $4: Comment content (no */ inside)
77                \*/)?                   # Comment end
78    ]gsx) {
79        my ($before, $name, $value, $after) = ($1, $2, $3, $4);
80        # Discard Doxygen comments that are coincidentally present before
81        # an error definition but not attached to it. This is ad hoc, based
82        # on what actually matters (or mattered at some point).
83        undef $before if defined($before) && $before =~ /\s*\\name\s/s;
84        die "Description neither before nor after $name in $file\n"
85          if !defined($before) && !defined($after);
86        die "Description both before and after $name in $file\n"
87          if defined($before) && defined($after);
88        my $description = (defined($before) ? $before : $after);
89        $description =~ s/^\s+//;
90        $description =~ s/\n( *\*)? */ /g;
91        $description =~ s/\.?\s+$//;
92        push @matches, [$name, $value, $description, scalar($file =~ /^.*private\/[^\/]+$/)];
93        ++$found;
94    }
95    if ($found) {
96        my $include_name = $file;
97        $include_name =~ s!.*/!!;
98        $include_name = "error.h" if ($include_name eq "error_common.h");
99        push @necessary_include_files, $include_name;
100    }
101}
102
103my @ll_old_define = ("", "", "");
104my @hl_old_define = ("", "", "");
105
106my $ll_code_check = "";
107my $hl_code_check = "";
108
109my $headers = "";
110my %included_headers;
111
112my %error_codes_seen;
113
114foreach my $match (@matches)
115{
116    my ($error_name, $error_code, $description, $is_private_header) = @$match;
117
118    die "Duplicated error code: $error_code ($error_name)\n"
119        if( $error_codes_seen{$error_code}++ );
120
121    $description =~ s/\\/\\\\/g;
122
123    my ($module_name) = $error_name =~ /^MBEDTLS_ERR_([^_]+)/;
124
125    # Fix faulty ones
126    $module_name = "BIGNUM" if ($module_name eq "MPI");
127    $module_name = "CTR_DRBG" if ($module_name eq "CTR");
128    $module_name = "HMAC_DRBG" if ($module_name eq "HMAC");
129
130    my $define_name = $module_name;
131    $define_name = "X509_USE,X509_CREATE" if ($define_name eq "X509");
132    $define_name = "ASN1_PARSE" if ($define_name eq "ASN1");
133    $define_name = "SSL_TLS" if ($define_name eq "SSL");
134    $define_name = "PEM_PARSE,PEM_WRITE" if ($define_name eq "PEM");
135    $define_name = "PKCS7" if ($define_name eq "PKCS7");
136    $define_name = "ALG_SHA3_224,ALG_SHA3_256,ALG_SHA3_384,ALG_SHA3_512"
137                   if ($define_name eq "SHA3");
138
139    my $define_prefix = "MBEDTLS_";
140    $define_prefix = "PSA_WANT_" if ($module_name eq "SHA3");
141
142    my $define_suffix = "_C";
143    $define_suffix = "" if ($module_name eq "SHA3");
144
145    my $include_name = $module_name;
146    $include_name =~ tr/A-Z/a-z/;
147
148    # Fix faulty ones
149    $include_name = "net_sockets" if ($module_name eq "NET");
150
151    $included_headers{"${include_name}.h"} = $module_name;
152
153    my $found_ll = grep $_ eq $module_name, @low_level_modules;
154    my $found_hl = grep $_ eq $module_name, @high_level_modules;
155    if (!$found_ll && !$found_hl)
156    {
157        printf("Error: Do not know how to handle: $module_name\n");
158        exit 1;
159    }
160
161    my $code_check;
162    my $old_define;
163    my $white_space;
164    my $first;
165
166    if ($found_ll)
167    {
168        $code_check = \$ll_code_check;
169        $old_define = \@ll_old_define;
170        $white_space = '        ';
171    }
172    else
173    {
174        $code_check = \$hl_code_check;
175        $old_define = \@hl_old_define;
176        $white_space = '        ';
177    }
178
179    my $old_define_name   = \${$old_define}[0];
180    my $old_define_prefix = \${$old_define}[1];
181    my $old_define_suffix = \${$old_define}[2];
182
183    if ($define_name ne ${$old_define_name})
184    {
185        if (${$old_define_name} ne "")
186        {
187            ${$code_check} .= "#endif /* ";
188            $first = 0;
189            foreach my $dep (split(/,/, ${$old_define_name}))
190            {
191                ${$code_check} .= " || \n          " if ($first++);
192                ${$code_check} .= "${$old_define_prefix}${dep}${$old_define_suffix}";
193            }
194            ${$code_check} .= " */\n\n";
195        }
196
197        ${$code_check} .= "#if ";
198        $headers .= "#if " if ($include_name ne "");
199        $first = 0;
200        foreach my $dep (split(/,/, ${define_name}))
201        {
202            ${$code_check} .= " || \\\n    " if ($first);
203            $headers       .= " || \\\n    " if ($first++);
204
205            ${$code_check} .= "defined(${define_prefix}${dep}${define_suffix})";
206            $headers       .= "defined(${define_prefix}${dep}${define_suffix})"
207                              if ($include_name ne "");
208        }
209        ${$code_check} .= "\n";
210
211        if ($is_private_header) {
212            $include_name = "private/" . $include_name;
213        }
214
215        $headers .= "\n#include \"mbedtls/${include_name}.h\"\n".
216                    "#endif\n\n" if ($include_name ne "");
217        ${$old_define_name}   = $define_name;
218        ${$old_define_prefix} = $define_prefix;
219        ${$old_define_suffix} = $define_suffix;
220    }
221
222    ${$code_check} .= "${white_space}case -($error_name):\n".
223                      "${white_space}    return( \"$module_name - $description\" );\n"
224};
225
226if ($ll_old_define[0] ne "")
227{
228    $ll_code_check .= "#endif /* ";
229    my $first = 0;
230    foreach my $dep (split(/,/, $ll_old_define[0]))
231    {
232        $ll_code_check .= " || \n          " if ($first++);
233        $ll_code_check .= "${ll_old_define[1]}${dep}${ll_old_define[2]}";
234    }
235    $ll_code_check .= " */\n";
236}
237if ($hl_old_define[0] ne "")
238{
239    $hl_code_check .= "#endif /* ";
240    my $first = 0;
241    foreach my $dep (split(/,/, $hl_old_define[0]))
242    {
243        $hl_code_check .= " || \n          " if ($first++);
244        $hl_code_check .= "${hl_old_define[1]}${dep}${hl_old_define[2]}";
245    }
246    $hl_code_check .= " */\n";
247}
248
249$error_format =~ s/HEADER_INCLUDED\n/$headers/g;
250$error_format =~ s/ *LOW_LEVEL_CODE_CHECKS\n/$ll_code_check/g;
251$error_format =~ s/ *HIGH_LEVEL_CODE_CHECKS\n/$hl_code_check/g;
252
253open(ERROR_FILE, ">$error_file") or die "Opening destination file '$error_file': $!";
254print ERROR_FILE $error_format;
255close(ERROR_FILE);
256
257my $errors = 0;
258for my $include_name (@necessary_include_files)
259{
260    if (not $included_headers{$include_name})
261    {
262        print STDERR "The header file \"$include_name\" defines error codes but has not been included!\n";
263        ++$errors;
264    }
265}
266
267exit !!$errors;
268