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