Remove handling of outdated macro's
[oweals/openssl.git] / util / perl / OpenSSL / ParseC.pm
1 #! /usr/bin/env perl
2 # Copyright 2018 The OpenSSL Project Authors. All Rights Reserved.
3 #
4 # Licensed under the Apache License 2.0 (the "License").  You may not use
5 # this file except in compliance with the License.  You can obtain a copy
6 # in the file LICENSE in the source distribution or at
7 # https://www.openssl.org/source/license.html
8
9 package OpenSSL::ParseC;
10
11 use strict;
12 use warnings;
13
14 use Exporter;
15 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
16 $VERSION = "0.9";
17 @ISA = qw(Exporter);
18 @EXPORT = qw(parse);
19
20 # Global handler data
21 my @preprocessor_conds;         # A list of simple preprocessor conditions,
22                                 # each item being a list of macros defined
23                                 # or not defined.
24
25 # Handler helpers
26 sub all_conds {
27     return map { ( @$_ ) } @preprocessor_conds;
28 }
29
30 # A list of handlers that will look at a "complete" string and try to
31 # figure out what to make of it.
32 # Each handler is a hash with the following keys:
33 #
34 # regexp                a regexp to compare the "complete" string with.
35 # checker               a function that does a more complex comparison.
36 #                       Use this instead of regexp if that isn't enough.
37 # massager              massages the "complete" string into an array with
38 #                       the following elements:
39 #
40 #                       [0]     String that needs further processing (this
41 #                               applies to typedefs of structs), or empty.
42 #                       [1]     The name of what was found.
43 #                       [2]     A character that denotes what type of thing
44 #                               this is: 'F' for function, 'S' for struct,
45 #                               'T' for typedef, 'M' for macro, 'V' for
46 #                               variable.
47 #                       [3]     Return type (only for type 'F' and 'V')
48 #                       [4]     Value (for type 'M') or signature (for type 'F',
49 #                               'V', 'T' or 'S')
50 #                       [5...]  The list of preprocessor conditions this is
51 #                               found in, as in checks for macro definitions
52 #                               (stored as the macro's name) or the absence
53 #                               of definition (stored as the macro's name
54 #                               prefixed with a '!'
55 #
56 #                       If the massager returns an empty list, it means the
57 #                       "complete" string has side effects but should otherwise
58 #                       be ignored.
59 #                       If the massager is undefined, the "complete" string
60 #                       should be ignored.
61 my @opensslcpphandlers = (
62     ##################################################################
63     # OpenSSL CPP specials
64     #
65     # These are used to convert certain pre-precessor expressions into
66     # others that @cpphandlers have a better chance to understand.
67
68     # This changes any OPENSSL_NO_DEPRECATED_x_y[_z] check to a check of
69     # OPENSSL_NO_DEPRECATEDIN_x_y[_z].  That's due to <openssl/macros.h>
70     # creating OPENSSL_NO_DEPRECATED_x_y[_z], but the ordinals files using
71     # DEPRECATEDIN_x_y[_z].
72     { regexp   => qr/#if(def|ndef) OPENSSL_NO_DEPRECATED_(\d+_\d+(?:_\d+)?)$/,
73       massager => sub {
74           return (<<"EOF");
75 #if$1 OPENSSL_NO_DEPRECATEDIN_$2
76 EOF
77       }
78    }
79 );
80 my @cpphandlers = (
81     ##################################################################
82     # CPP stuff
83
84     { regexp   => qr/#ifdef ?(.*)/,
85       massager => sub {
86           my %opts;
87           if (ref($_[$#_]) eq "HASH") {
88               %opts = %{$_[$#_]};
89               pop @_;
90           }
91           push @preprocessor_conds, [ $1 ];
92           print STDERR "DEBUG[",$opts{debug_type},"]: preprocessor level: ", scalar(@preprocessor_conds), "\n"
93               if $opts{debug};
94           return ();
95       },
96     },
97     { regexp   => qr/#ifndef ?(.*)/,
98       massager => sub {
99           my %opts;
100           if (ref($_[$#_]) eq "HASH") {
101               %opts = %{$_[$#_]};
102               pop @_;
103           }
104           push @preprocessor_conds, [ '!'.$1 ];
105           print STDERR "DEBUG[",$opts{debug_type},"]: preprocessor level: ", scalar(@preprocessor_conds), "\n"
106               if $opts{debug};
107           return ();
108       },
109     },
110     { regexp   => qr/#if (0|1)/,
111       massager => sub {
112           my %opts;
113           if (ref($_[$#_]) eq "HASH") {
114               %opts = %{$_[$#_]};
115               pop @_;
116           }
117           if ($1 eq "1") {
118               push @preprocessor_conds, [ "TRUE" ];
119           } else {
120               push @preprocessor_conds, [ "!TRUE" ];
121           }
122           print STDERR "DEBUG[",$opts{debug_type},"]: preprocessor level: ", scalar(@preprocessor_conds), "\n"
123               if $opts{debug};
124           return ();
125       },
126     },
127     { regexp   => qr/#if ?(.*)/,
128       massager => sub {
129           my %opts;
130           if (ref($_[$#_]) eq "HASH") {
131               %opts = %{$_[$#_]};
132               pop @_;
133           }
134           my @results = ();
135           my $conds = $1;
136           if ($conds =~ m|^defined<<<\(([^\)]*)\)>>>(.*)$|) {
137               push @results, $1; # Handle the simple case
138               my $rest = $2;
139               my $re = qr/^(?:\|\|defined<<<\([^\)]*\)>>>)*$/;
140               print STDERR "DEBUG[",$opts{debug_type},"]: Matching '$rest' with '$re'\n"
141                   if $opts{debug};
142               if ($rest =~ m/$re/) {
143                   my @rest = split /\|\|/, $rest;
144                   shift @rest;
145                   foreach (@rest) {
146                       m|^defined<<<\(([^\)]*)\)>>>$|;
147                       die "Something wrong...$opts{PLACE}" if $1 eq "";
148                       push @results, $1;
149                   }
150               } else {
151                   $conds =~ s/<<<|>>>//g;
152                   warn "Warning: complicated #if expression(1): $conds$opts{PLACE}"
153                       if $opts{warnings};
154               }
155           } elsif ($conds =~ m|^!defined<<<\(([^\)]*)\)>>>(.*)$|) {
156               push @results, '!'.$1; # Handle the simple case
157               my $rest = $2;
158               my $re = qr/^(?:\&\&!defined<<<\([^\)]*\)>>>)*$/;
159               print STDERR "DEBUG[",$opts{debug_type},"]: Matching '$rest' with '$re'\n"
160                   if $opts{debug};
161               if ($rest =~ m/$re/) {
162                   my @rest = split /\&\&/, $rest;
163                   shift @rest;
164                   foreach (@rest) {
165                       m|^!defined<<<\(([^\)]*)\)>>>$|;
166                       die "Something wrong...$opts{PLACE}" if $1 eq "";
167                       push @results, '!'.$1;
168                   }
169               } else {
170                   $conds =~ s/<<<|>>>//g;
171                   warn "Warning: complicated #if expression(2): $conds$opts{PLACE}"
172                       if $opts{warnings};
173               }
174           } else {
175               $conds =~ s/<<<|>>>//g;
176               warn "Warning: complicated #if expression(3): $conds$opts{PLACE}"
177                   if $opts{warnings};
178           }
179           print STDERR "DEBUG[",$opts{debug_type},"]: Added preprocessor conds: '", join("', '", @results), "'\n"
180               if $opts{debug};
181           push @preprocessor_conds, [ @results ];
182           print STDERR "DEBUG[",$opts{debug_type},"]: preprocessor level: ", scalar(@preprocessor_conds), "\n"
183               if $opts{debug};
184           return ();
185       },
186     },
187     { regexp   => qr/#elif (.*)/,
188       massager => sub {
189           my %opts;
190           if (ref($_[$#_]) eq "HASH") {
191               %opts = %{$_[$#_]};
192               pop @_;
193           }
194           die "An #elif without corresponding condition$opts{PLACE}"
195               if !@preprocessor_conds;
196           pop @preprocessor_conds;
197           print STDERR "DEBUG[",$opts{debug_type},"]: preprocessor level: ", scalar(@preprocessor_conds), "\n"
198               if $opts{debug};
199           return (<<"EOF");
200 #if $1
201 EOF
202       },
203     },
204     { regexp   => qr/#else/,
205       massager => sub {
206           my %opts;
207           if (ref($_[$#_]) eq "HASH") {
208               %opts = %{$_[$#_]};
209               pop @_;
210           }
211           die "An #else without corresponding condition$opts{PLACE}"
212               if !@preprocessor_conds;
213           # Invert all conditions on the last level
214           my $stuff = pop @preprocessor_conds;
215           push @preprocessor_conds, [
216               map { m|^!(.*)$| ? $1 : '!'.$_ } @$stuff
217           ];
218           print STDERR "DEBUG[",$opts{debug_type},"]: preprocessor level: ", scalar(@preprocessor_conds), "\n"
219               if $opts{debug};
220           return ();
221       },
222     },
223     { regexp   => qr/#endif ?/,
224       massager => sub {
225           my %opts;
226           if (ref($_[$#_]) eq "HASH") {
227               %opts = %{$_[$#_]};
228               pop @_;
229           }
230           die "An #endif without corresponding condition$opts{PLACE}"
231               if !@preprocessor_conds;
232           pop @preprocessor_conds;
233           print STDERR "DEBUG[",$opts{debug_type},"]: preprocessor level: ", scalar(@preprocessor_conds), "\n"
234               if $opts{debug};
235           return ();
236       },
237     },
238     { regexp   => qr/#define ([[:alpha:]_]\w*)(<<<\(.*?\)>>>)?( (.*))?/,
239       massager => sub {
240           my $name = $1;
241           my $params = $2;
242           my $spaceval = $3||"";
243           my $val = $4||"";
244           return ("",
245                   $1, 'M', "", $params ? "$name$params$spaceval" : $val,
246                   all_conds()); }
247     },
248     { regexp   => qr/#.*/,
249       massager => sub { return (); }
250     },
251     );
252
253 my @opensslchandlers = (
254     ##################################################################
255     # OpenSSL C specials
256     #
257     # They are really preprocessor stuff, but they look like C stuff
258     # to this parser.  All of these do replacements, anything else is
259     # an error.
260
261     #####
262     # Deprecated stuff, by OpenSSL release.
263
264     # We trick the parser by pretending that the declaration is wrapped in a
265     # check if the DEPRECATEDIN macro is defined or not.  Callers of parse()
266     # will have to decide what to do with it.
267     { regexp   => qr/(DEPRECATEDIN_\d+_\d+(?:_\d+)?)<<<\((.*)\)>>>/,
268       massager => sub { return (<<"EOF");
269 #ifndef $1
270 $2;
271 #endif
272 EOF
273       },
274     },
275
276     #####
277     # LHASH stuff
278
279     # LHASH_OF(foo) is used as a type, but the chandlers won't take it
280     # gracefully, so we expand it here.
281     { regexp   => qr/(.*)\bLHASH_OF<<<\((.*?)\)>>>(.*)/,
282       massager => sub { return ("$1struct lhash_st_$2$3"); }
283     },
284     { regexp   => qr/DEFINE_LHASH_OF<<<\((.*)\)>>>/,
285       massager => sub {
286           return (<<"EOF");
287 static ossl_inline LHASH_OF($1) * lh_$1_new(unsigned long (*hfn)(const $1 *),
288                                             int (*cfn)(const $1 *, const $1 *));
289 static ossl_inline void lh_$1_free(LHASH_OF($1) *lh);
290 static ossl_inline $1 *lh_$1_insert(LHASH_OF($1) *lh, $1 *d);
291 static ossl_inline $1 *lh_$1_delete(LHASH_OF($1) *lh, const $1 *d);
292 static ossl_inline $1 *lh_$1_retrieve(LHASH_OF($1) *lh, const $1 *d);
293 static ossl_inline int lh_$1_error(LHASH_OF($1) *lh);
294 static ossl_inline unsigned long lh_$1_num_items(LHASH_OF($1) *lh);
295 static ossl_inline void lh_$1_node_stats_bio(const LHASH_OF($1) *lh, BIO *out);
296 static ossl_inline void lh_$1_node_usage_stats_bio(const LHASH_OF($1) *lh,
297                                                    BIO *out);
298 static ossl_inline void lh_$1_stats_bio(const LHASH_OF($1) *lh, BIO *out);
299 static ossl_inline unsigned long lh_$1_get_down_load(LHASH_OF($1) *lh);
300 static ossl_inline void lh_$1_set_down_load(LHASH_OF($1) *lh, unsigned long dl);
301 static ossl_inline void lh_$1_doall(LHASH_OF($1) *lh, void (*doall)($1 *));
302 LHASH_OF($1)
303 EOF
304       }
305      },
306
307     #####
308     # STACK stuff
309
310     # STACK_OF(foo) is used as a type, but the chandlers won't take it
311     # gracefully, so we expand it here.
312     { regexp   => qr/(.*)\bSTACK_OF<<<\((.*?)\)>>>(.*)/,
313       massager => sub { return ("$1struct stack_st_$2$3"); }
314     },
315 #    { regexp   => qr/(.*)\bSTACK_OF\((.*?)\)(.*)/,
316 #      massager => sub {
317 #          my $before = $1;
318 #          my $stack_of = "struct stack_st_$2";
319 #          my $after = $3;
320 #          if ($after =~ m|^\w|) { $after = " ".$after; }
321 #          return ("$before$stack_of$after");
322 #      }
323 #    },
324     { regexp   => qr/SKM_DEFINE_STACK_OF<<<\((.*),\s*(.*),\s*(.*)\)>>>/,
325       massager => sub {
326           return (<<"EOF");
327 STACK_OF($1);
328 typedef int (*sk_$1_compfunc)(const $3 * const *a, const $3 *const *b);
329 typedef void (*sk_$1_freefunc)($3 *a);
330 typedef $3 * (*sk_$1_copyfunc)(const $3 *a);
331 static ossl_inline int sk_$1_num(const STACK_OF($1) *sk);
332 static ossl_inline $2 *sk_$1_value(const STACK_OF($1) *sk, int idx);
333 static ossl_inline STACK_OF($1) *sk_$1_new(sk_$1_compfunc compare);
334 static ossl_inline STACK_OF($1) *sk_$1_new_null(void);
335 static ossl_inline STACK_OF($1) *sk_$1_new_reserve(sk_$1_compfunc compare,
336                                                    int n);
337 static ossl_inline int sk_$1_reserve(STACK_OF($1) *sk, int n);
338 static ossl_inline void sk_$1_free(STACK_OF($1) *sk);
339 static ossl_inline void sk_$1_zero(STACK_OF($1) *sk);
340 static ossl_inline $2 *sk_$1_delete(STACK_OF($1) *sk, int i);
341 static ossl_inline $2 *sk_$1_delete_ptr(STACK_OF($1) *sk, $2 *ptr);
342 static ossl_inline int sk_$1_push(STACK_OF($1) *sk, $2 *ptr);
343 static ossl_inline int sk_$1_unshift(STACK_OF($1) *sk, $2 *ptr);
344 static ossl_inline $2 *sk_$1_pop(STACK_OF($1) *sk);
345 static ossl_inline $2 *sk_$1_shift(STACK_OF($1) *sk);
346 static ossl_inline void sk_$1_pop_free(STACK_OF($1) *sk,
347                                        sk_$1_freefunc freefunc);
348 static ossl_inline int sk_$1_insert(STACK_OF($1) *sk, $2 *ptr, int idx);
349 static ossl_inline $2 *sk_$1_set(STACK_OF($1) *sk, int idx, $2 *ptr);
350 static ossl_inline int sk_$1_find(STACK_OF($1) *sk, $2 *ptr);
351 static ossl_inline int sk_$1_find_ex(STACK_OF($1) *sk, $2 *ptr);
352 static ossl_inline void sk_$1_sort(STACK_OF($1) *sk);
353 static ossl_inline int sk_$1_is_sorted(const STACK_OF($1) *sk);
354 static ossl_inline STACK_OF($1) * sk_$1_dup(const STACK_OF($1) *sk);
355 static ossl_inline STACK_OF($1) *sk_$1_deep_copy(const STACK_OF($1) *sk,
356                                                  sk_$1_copyfunc copyfunc,
357                                                  sk_$1_freefunc freefunc);
358 static ossl_inline sk_$1_compfunc sk_$1_set_cmp_func(STACK_OF($1) *sk,
359                                                      sk_$1_compfunc compare);
360 EOF
361       }
362     },
363     { regexp   => qr/DEFINE_SPECIAL_STACK_OF<<<\((.*),\s*(.*)\)>>>/,
364       massager => sub { return ("SKM_DEFINE_STACK_OF($1,$2,$2)"); },
365     },
366     { regexp   => qr/DEFINE_STACK_OF<<<\((.*)\)>>>/,
367       massager => sub { return ("SKM_DEFINE_STACK_OF($1,$1,$1)"); },
368     },
369     { regexp   => qr/DEFINE_SPECIAL_STACK_OF_CONST<<<\((.*),\s*(.*)\)>>>/,
370       massager => sub { return ("SKM_DEFINE_STACK_OF($1,const $2,$2)"); },
371     },
372     { regexp   => qr/DEFINE_STACK_OF_CONST<<<\((.*)\)>>>/,
373       massager => sub { return ("SKM_DEFINE_STACK_OF($1,const $1,$1)"); },
374     },
375
376     #####
377     # ASN1 stuff
378     { regexp   => qr/DECLARE_ASN1_ITEM<<<\((.*)\)>>>/,
379       massager => sub {
380           return (<<"EOF");
381 const ASN1_ITEM *$1_it(void);
382 EOF
383       },
384     },
385     { regexp   => qr/DECLARE_ASN1_ENCODE_FUNCTIONS_only<<<\((.*),\s*(.*)\)>>>/,
386       massager => sub {
387           return (<<"EOF");
388 int d2i_$2(void);
389 int i2d_$2(void);
390 EOF
391       },
392     },
393     { regexp   => qr/DECLARE_ASN1_ENCODE_FUNCTIONS<<<\((.*),\s*(.*),\s*(.*)\)>>>/,
394       massager => sub {
395           return (<<"EOF");
396 int d2i_$3(void);
397 int i2d_$3(void);
398 DECLARE_ASN1_ITEM($2)
399 EOF
400       },
401     },
402     { regexp   => qr/DECLARE_ASN1_ENCODE_FUNCTIONS_name<<<\((.*),\s*(.*)\)>>>/,
403       massager => sub {
404           return (<<"EOF");
405 int d2i_$2(void);
406 int i2d_$2(void);
407 DECLARE_ASN1_ITEM($2)
408 EOF
409       },
410     },
411     { regexp   => qr/DECLARE_ASN1_ALLOC_FUNCTIONS_name<<<\((.*),\s*(.*)\)>>>/,
412       massager => sub {
413           return (<<"EOF");
414 int $2_free(void);
415 int $2_new(void);
416 EOF
417       },
418     },
419     { regexp   => qr/DECLARE_ASN1_ALLOC_FUNCTIONS<<<\((.*)\)>>>/,
420       massager => sub {
421           return (<<"EOF");
422 int $1_free(void);
423 int $1_new(void);
424 EOF
425       },
426     },
427     { regexp   => qr/DECLARE_ASN1_FUNCTIONS_name<<<\((.*),\s*(.*)\)>>>/,
428       massager => sub {
429           return (<<"EOF");
430 int d2i_$2(void);
431 int i2d_$2(void);
432 int $2_free(void);
433 int $2_new(void);
434 DECLARE_ASN1_ITEM($2)
435 EOF
436       },
437     },
438     { regexp   => qr/DECLARE_ASN1_FUNCTIONS<<<\((.*)\)>>>/,
439       massager => sub { return (<<"EOF");
440 int d2i_$1(void);
441 int i2d_$1(void);
442 int $1_free(void);
443 int $1_new(void);
444 DECLARE_ASN1_ITEM($1)
445 EOF
446       }
447     },
448     { regexp   => qr/DECLARE_ASN1_NDEF_FUNCTION<<<\((.*)\)>>>/,
449       massager => sub {
450           return (<<"EOF");
451 int i2d_$1_NDEF(void);
452 EOF
453       }
454     },
455     { regexp   => qr/DECLARE_ASN1_PRINT_FUNCTION<<<\((.*)\)>>>/,
456       massager => sub {
457           return (<<"EOF");
458 int $1_print_ctx(void);
459 EOF
460       }
461     },
462     { regexp   => qr/DECLARE_ASN1_PRINT_FUNCTION_name<<<\((.*),\s*(.*)\)>>>/,
463       massager => sub {
464           return (<<"EOF");
465 int $2_print_ctx(void);
466 EOF
467       }
468     },
469     { regexp   => qr/DECLARE_ASN1_SET_OF<<<\((.*)\)>>>/,
470       massager => sub { return (); }
471     },
472     { regexp   => qr/DECLARE_ASN1_DUP_FUNCTION<<<\((.*)\)>>>/,
473       massager => sub {
474           return (<<"EOF");
475 int $1_dup(void);
476 EOF
477       }
478     },
479     { regexp   => qr/DECLARE_ASN1_DUP_FUNCTION_name<<<\((.*),\s*(.*)\)>>>/,
480       massager => sub {
481           return (<<"EOF");
482 int $2_dup(void);
483 EOF
484       }
485     },
486     { regexp   => qr/DECLARE_PKCS12_SET_OF<<<\((.*)\)>>>/,
487       massager => sub { return (); }
488     },
489     { regexp   => qr/DECLARE_PEM(?|_rw|_rw_cb|_rw_const)<<<\((.*?),.*\)>>>/,
490       massager => sub { return (<<"EOF");
491 #ifndef OPENSSL_NO_STDIO
492 int PEM_read_$1(void);
493 int PEM_write_$1(void);
494 #endif
495 int PEM_read_bio_$1(void);
496 int PEM_write_bio_$1(void);
497 EOF
498       },
499     },
500
501     #####
502     # PEM stuff
503     { regexp   => qr/DECLARE_PEM(?|_write|_write_cb|_write_const)<<<\((.*?),.*\)>>>/,
504       massager => sub { return (<<"EOF");
505 #ifndef OPENSSL_NO_STDIO
506 int PEM_write_$1(void);
507 #endif
508 int PEM_write_bio_$1(void);
509 EOF
510       },
511     },
512     { regexp   => qr/DECLARE_PEM(?|_read|_read_cb)<<<\((.*?),.*\)>>>/,
513       massager => sub { return (<<"EOF");
514 #ifndef OPENSSL_NO_STDIO
515 int PEM_read_$1(void);
516 #endif
517 int PEM_read_bio_$1(void);
518 EOF
519       },
520     },
521
522     # Spurious stuff found in the OpenSSL headers
523     # Usually, these are just macros that expand to, well, something
524     { regexp   => qr/__NDK_FPABI__/,
525       massager => sub { return (); }
526     },
527     );
528
529 my $anoncnt = 0;
530
531 my @chandlers = (
532     ##################################################################
533     # C stuff
534
535     # extern "C" of individual items
536     # Note that the main parse function has a special hack for 'extern "C" {'
537     # which can't be done in handlers
538     # We simply ignore it.
539     { regexp   => qr/^extern "C" (.*(?:;|>>>))/,
540       massager => sub { return ($1); },
541     },
542     # any other extern is just ignored
543     { regexp   => qr/^\s*                       # Any spaces before
544                      extern                     # The keyword we look for
545                      \b                         # word to non-word boundary
546                      .*                         # Anything after
547                      ;
548                     /x,
549       massager => sub { return (); },
550     },
551     # union, struct and enum definitions
552     # Because this one might appear a little everywhere within type
553     # definitions, we take it out and replace it with just
554     # 'union|struct|enum name' while registering it.
555     # This makes use of the parser trick to surround the outer braces
556     # with <<< and >>>
557     { regexp   => qr/(.*)                       # Anything before       ($1)
558                      \b                         # word to non-word boundary
559                      (union|struct|enum)        # The word used         ($2)
560                      (?:\s([[:alpha:]_]\w*))?   # Struct or enum name   ($3)
561                      <<<(\{.*?\})>>>            # Struct or enum definition ($4)
562                      (.*)                       # Anything after        ($5)
563                      ;
564                     /x,
565       massager => sub {
566           my $before = $1;
567           my $word = $2;
568           my $name = $3
569               || sprintf("__anon%03d", ++$anoncnt); # Anonymous struct
570           my $definition = $4;
571           my $after = $5;
572           my $type = $word eq "struct" ? 'S' : 'E';
573           if ($before ne "" || $after ne ";") {
574               if ($after =~ m|^\w|) { $after = " ".$after; }
575               return ("$before$word $name$after;",
576                       "$word $name", $type, "", "$word$definition", all_conds());
577           }
578           # If there was no before nor after, make the return much simple
579           return ("", "$word $name", $type, "", "$word$definition", all_conds());
580       }
581     },
582     # Named struct and enum forward declarations
583     # We really just ignore them, but we need to parse them or the variable
584     # declaration handler further down will think it's a variable declaration.
585     { regexp   => qr/^(union|struct|enum) ([[:alpha:]_]\w*);/,
586       massager => sub { return (); }
587     },
588     # Function returning function pointer declaration
589     { regexp   => qr/(?:(typedef)\s?)?          # Possible typedef      ($1)
590                      ((?:\w|\*|\s)*?)           # Return type           ($2)
591                      \s?                        # Possible space
592                      <<<\(\*
593                      ([[:alpha:]_]\w*)          # Function name         ($3)
594                      (\(.*\))                   # Parameters            ($4)
595                      \)>>>
596                      <<<(\(.*\))>>>             # F.p. parameters       ($5)
597                      ;
598                     /x,
599       massager => sub {
600           return ("", $3, 'F', "", "$2(*$4)$5", all_conds())
601               if defined $1;
602           return ("", $3, 'F', "$2(*)$5", "$2(*$4)$5", all_conds()); }
603     },
604     # Function pointer declaration, or typedef thereof
605     { regexp   => qr/(?:(typedef)\s?)?          # Possible typedef      ($1)
606                      ((?:\w|\*|\s)*?)           # Return type           ($2)
607                      <<<\(\*([[:alpha:]_]\w*)\)>>> # T.d. or var name   ($3)
608                      <<<(\(.*\))>>>             # F.p. parameters       ($4)
609                      ;
610                     /x,
611       massager => sub {
612           return ("", $3, 'T', "", "$2(*)$4", all_conds())
613               if defined $1;
614           return ("", $3, 'V', "$2(*)$4", "$2(*)$4", all_conds());
615       },
616     },
617     # Function declaration, or typedef thereof
618     { regexp   => qr/(?:(typedef)\s?)?          # Possible typedef      ($1)
619                      ((?:\w|\*|\s)*?)           # Return type           ($2)
620                      \s?                        # Possible space
621                      ([[:alpha:]_]\w*)          # Function name         ($3)
622                      <<<(\(.*\))>>>             # Parameters            ($4)
623                      ;
624                     /x,
625       massager => sub {
626           return ("", $3, 'T', "", "$2$4", all_conds())
627               if defined $1;
628           return ("", $3, 'F', $2, "$2$4", all_conds());
629       },
630     },
631     # Variable declaration, including arrays, or typedef thereof
632     { regexp   => qr/(?:(typedef)\s?)?          # Possible typedef      ($1)
633                      ((?:\w|\*|\s)*?)           # Type                  ($2)
634                      \s?                        # Possible space
635                      ([[:alpha:]_]\w*)          # Variable name         ($3)
636                      ((?:<<<\[[^\]]*\]>>>)*)    # Possible array declaration ($4)
637                      ;
638                     /x,
639       massager => sub {
640           return ("", $3, 'T', "", $2.($4||""), all_conds())
641               if defined $1;
642           return ("", $3, 'V', $2.($4||""), $2.($4||""), all_conds());
643       },
644     },
645 );
646
647 # End handlers are almost the same as handlers, except they are run through
648 # ONCE when the input has been parsed through.  These are used to check for
649 # remaining stuff, such as an unfinished #ifdef and stuff like that that the
650 # main parser can't check on its own.
651 my @endhandlers = (
652     { massager => sub {
653         my %opts = %{$_[0]};
654
655         die "Unfinished preprocessor conditions levels: ",scalar(@preprocessor_conds),($opts{filename} ? " in file ".$opts{filename}: ""),$opts{PLACE}
656             if @preprocessor_conds;
657       }
658     }
659     );
660
661 # takes a list of strings that can each contain one or several lines of code
662 # also takes a hash of options as last argument.
663 #
664 # returns a list of hashes with information:
665 #
666 #       name            name of the thing
667 #       type            type, see the massage handler function
668 #       returntype      return type of functions and variables
669 #       value           value for macros, signature for functions, variables
670 #                       and structs
671 #       conds           preprocessor conditions (array ref)
672
673 sub parse {
674     my %opts;
675     if (ref($_[$#_]) eq "HASH") {
676         %opts = %{$_[$#_]};
677         pop @_;
678     }
679     my %state = (
680         in_extern_C => 0,       # An exception to parenthesis processing.
681         cpp_parens => [],       # A list of ending parens and braces found in
682                                 # preprocessor directives
683         c_parens => [],         # A list of ending parens and braces found in
684                                 # C statements
685         in_string => "",        # empty string when outside a string, otherwise
686                                 # "'" or '"' depending on the starting quote.
687         in_comment => "",       # empty string when outside a comment, otherwise
688                                 # "/*" or "//" depending on the type of comment
689                                 # found.  The latter will never be multiline
690                                 # NOTE: in_string and in_comment will never be
691                                 # true (in perl semantics) at the same time.
692         current_line => 0,
693         );
694     my @result = ();
695     my $normalized_line = "";   # $input_line, but normalized.  In essence, this
696                                 # means that ALL whitespace is removed unless
697                                 # it absolutely has to be present, and in that
698                                 # case, there's only one space.
699                                 # The cases where a space needs to stay present
700                                 # are:
701                                 # 1. between words
702                                 # 2. between words and number
703                                 # 3. after the first word of a preprocessor
704                                 #    directive.
705                                 # 4. for the #define directive, between the macro
706                                 #    name/args and its value, so we end up with:
707                                 #       #define FOO val
708                                 #       #define BAR(x) something(x)
709     my $collected_stmt = "";    # Where we're building up a C line until it's a
710                                 # complete definition/declaration, as determined
711                                 # by any handler being capable of matching it.
712
713     # We use $_ shamelessly when looking through @lines.
714     # In case we find a \ at the end, we keep filling it up with more lines.
715     $_ = undef;
716
717     foreach my $line (@_) {
718         # split tries to be smart when a string ends with the thing we split on
719         $line .= "\n" unless $line =~ m|\R$|;
720         $line .= "#";
721
722         # We use Â¦undef¦ as a marker for a new line from the file.
723         # Since we convert one line to several and unshift that into @lines,
724         # that's the only safe way we have to track the original lines
725         my @lines = map { ( undef, $_ ) } split $/, $line;
726
727         # Remember that extra # we added above?  Now we remove it
728         pop @lines;
729         pop @lines;             # Don't forget the undef
730
731         while (@lines) {
732             if (!defined($lines[0])) {
733                 shift @lines;
734                 $state{current_line}++;
735                 if (!defined($_)) {
736                     $opts{PLACE} = " at ".$opts{filename}." line ".$state{current_line}."\n";
737                     $opts{PLACE2} = $opts{filename}.":".$state{current_line};
738                 }
739                 next;
740             }
741
742             $_ = "" unless defined $_;
743             $_ .= shift @lines;
744
745             if (m|\\$|) {
746                 $_ = $`;
747                 next;
748             }
749
750             if ($opts{debug}) {
751                 print STDERR "DEBUG:----------------------------\n";
752                 print STDERR "DEBUG: \$_      = '$_'\n";
753             }
754
755             ##########################################################
756             # Now that we have a full line, let's process through it
757             while(1) {
758                 unless ($state{in_comment}) {
759                     # Begin with checking if the current $normalized_line
760                     # contains a preprocessor directive
761                     # This is only done if we're not inside a comment and
762                     # if it's a preprocessor directive and it's finished.
763                     if ($normalized_line =~ m|^#| && $_ eq "") {
764                         print STDERR "DEBUG[OPENSSL CPP]: \$normalized_line = '$normalized_line'\n"
765                             if $opts{debug};
766                         $opts{debug_type} = "OPENSSL CPP";
767                         my @r = ( _run_handlers($normalized_line,
768                                                 @opensslcpphandlers,
769                                                 \%opts) );
770                         if (shift @r) {
771                             # Checking if there are lines to inject.
772                             if (@r) {
773                                 @r = split $/, (pop @r).$_;
774                                 print STDERR "DEBUG[OPENSSL CPP]: injecting '", join("', '", @r),"'\n"
775                                     if $opts{debug} && @r;
776                                 @lines = ( @r, @lines );
777
778                                 $_ = "";
779                             }
780                         } else {
781                             print STDERR "DEBUG[CPP]: \$normalized_line = '$normalized_line'\n"
782                                 if $opts{debug};
783                             $opts{debug_type} = "CPP";
784                             my @r = ( _run_handlers($normalized_line,
785                                                     @cpphandlers,
786                                                     \%opts) );
787                             if (shift @r) {
788                                 if (ref($r[0]) eq "HASH") {
789                                     push @result, shift @r;
790                                 }
791
792                                 # Now, check if there are lines to inject.
793                                 # Really, this should never happen, it IS a
794                                 # preprocessor directive after all...
795                                 if (@r) {
796                                     @r = split $/, pop @r;
797                                     print STDERR "DEBUG[CPP]: injecting '", join("', '", @r),"'\n"
798                                     if $opts{debug} && @r;
799                                     @lines = ( @r, @lines );
800                                     $_ = "";
801                                 }
802                             }
803                         }
804
805                         # Note: we simply ignore all directives that no
806                         # handler matches
807                         $normalized_line = "";
808                     }
809
810                     # If the two strings end and start with a character that
811                     # shouldn't get concatenated, add a space
812                     my $space =
813                         ($collected_stmt =~ m/(?:"|')$/
814                          || ($collected_stmt =~ m/(?:\w|\d)$/
815                              && $normalized_line =~ m/^(?:\w|\d)/)) ? " " : "";
816
817                     # Now, unless we're building up a preprocessor directive or
818                     # are in the middle of a string, or the parens et al aren't
819                     # balanced up yet, let's try and see if there's a OpenSSL
820                     # or C handler that can make sense of what we have so far.
821                     if ( $normalized_line !~ m|^#|
822                          && ($collected_stmt ne "" || $normalized_line ne "")
823                          && ! @{$state{c_parens}}
824                          && ! $state{in_string} ) {
825                         if ($opts{debug}) {
826                             print STDERR "DEBUG[OPENSSL C]: \$collected_stmt  = '$collected_stmt'\n";
827                             print STDERR "DEBUG[OPENSSL C]: \$normalized_line = '$normalized_line'\n";
828                         }
829                         $opts{debug_type} = "OPENSSL C";
830                         my @r = ( _run_handlers($collected_stmt
831                                                     .$space
832                                                     .$normalized_line,
833                                                 @opensslchandlers,
834                                                 \%opts) );
835                         if (shift @r) {
836                             # Checking if there are lines to inject.
837                             if (@r) {
838                                 @r = split $/, (pop @r).$_;
839                                 print STDERR "DEBUG[OPENSSL]: injecting '", join("', '", @r),"'\n"
840                                     if $opts{debug} && @r;
841                                 @lines = ( @r, @lines );
842
843                                 $_ = "";
844                             }
845                             $normalized_line = "";
846                             $collected_stmt = "";
847                         } else {
848                             if ($opts{debug}) {
849                                 print STDERR "DEBUG[C]: \$collected_stmt  = '$collected_stmt'\n";
850                                 print STDERR "DEBUG[C]: \$normalized_line = '$normalized_line'\n";
851                             }
852                             $opts{debug_type} = "C";
853                             my @r = ( _run_handlers($collected_stmt
854                                                         .$space
855                                                         .$normalized_line,
856                                                     @chandlers,
857                                                     \%opts) );
858                             if (shift @r) {
859                                 if (ref($r[0]) eq "HASH") {
860                                     push @result, shift @r;
861                                 }
862
863                                 # Checking if there are lines to inject.
864                                 if (@r) {
865                                     @r = split $/, (pop @r).$_;
866                                     print STDERR "DEBUG[C]: injecting '", join("', '", @r),"'\n"
867                                         if $opts{debug} && @r;
868                                     @lines = ( @r, @lines );
869
870                                     $_ = "";
871                                 }
872                                 $normalized_line = "";
873                                 $collected_stmt = "";
874                             }
875                         }
876                     }
877                     if ($_ eq "") {
878                         $collected_stmt .= $space.$normalized_line;
879                         $normalized_line = "";
880                     }
881                 }
882
883                 if ($_ eq "") {
884                     $_ = undef;
885                     last;
886                 }
887
888                 # Take care of inside string first.
889                 if ($state{in_string}) {
890                     if (m/ (?:^|(?<!\\))        # Make sure it's not escaped
891                            $state{in_string}    # Look for matching quote
892                          /x) {
893                         $normalized_line .= $`.$&;
894                         $state{in_string} = "";
895                         $_ = $';
896                         next;
897                     } else {
898                         die "Unfinished string without continuation found$opts{PLACE}\n";
899                     }
900                 }
901                 # ... or inside comments, whichever happens to apply
902                 elsif ($state{in_comment}) {
903
904                     # This should never happen
905                     die "Something went seriously wrong, multiline //???$opts{PLACE}\n"
906                         if ($state{in_comment} eq "//");
907
908                     # A note: comments are simply discarded.
909
910                     if (m/ (?:^|(?<!\\))        # Make sure it's not escaped
911                            \*\/                 # Look for C comment end
912                          /x) {
913                         $state{in_comment} = "";
914                         $_ = $';
915                         print STDERR "DEBUG: Found end of comment, followed by '$_'\n"
916                             if $opts{debug};
917                         next;
918                     } else {
919                         $_ = "";
920                         next;
921                     }
922                 }
923
924                 # At this point, it's safe to remove leading whites, but
925                 # we need to be careful with some preprocessor lines
926                 if (m|^\s+|) {
927                     my $rest = $';
928                     my $space = "";
929                     $space = " "
930                         if ($normalized_line =~ m/^
931                                                   \#define\s\w(?:\w|\d)*(?:<<<\([^\)]*\)>>>)?
932                                                   | \#[a-z]+
933                                                   $/x);
934                     print STDERR "DEBUG: Processing leading spaces: \$normalized_line = '$normalized_line', \$space = '$space', \$rest = '$rest'\n"
935                         if $opts{debug};
936                     $_ = $space.$rest;
937                 }
938
939                 my $parens =
940                     $normalized_line =~ m|^#| ? 'cpp_parens' : 'c_parens';
941                 (my $paren_singular = $parens) =~ s|s$||;
942
943                 # Now check for specific tokens, and if they are parens,
944                 # check them against $state{$parens}.  Note that we surround
945                 # the outermost parens with extra "<<<" and ">>>".  Those
946                 # are for the benefit of handlers who to need to detect
947                 # them, and they will be removed from the final output.
948                 if (m|^[\{\[\(]|) {
949                     my $body = $&;
950                     $_ = $';
951                     if (!@{$state{$parens}}) {
952                         if ("$normalized_line$body" =~ m|^extern "C"\{$|) {
953                             $state{in_extern_C} = 1;
954                             print STDERR "DEBUG: found start of 'extern \"C\"' ($normalized_line$body)\n"
955                                 if $opts{debug};
956                             $normalized_line = "";
957                         } else {
958                             $normalized_line .= "<<<".$body;
959                         }
960                     } else {
961                         $normalized_line .= $body;
962                     }
963
964                     if ($normalized_line ne "") {
965                         print STDERR "DEBUG: found $paren_singular start '$body'\n"
966                             if $opts{debug};
967                         $body =~ tr|\{\[\(|\}\]\)|;
968                         print STDERR "DEBUG: pushing $paren_singular end '$body'\n"
969                             if $opts{debug};
970                         push @{$state{$parens}}, $body;
971                     }
972                 } elsif (m|^[\}\]\)]|) {
973                     $_ = $';
974
975                     if (!@{$state{$parens}}
976                         && $& eq '}' && $state{in_extern_C}) {
977                         print STDERR "DEBUG: found end of 'extern \"C\"'\n"
978                             if $opts{debug};
979                         $state{in_extern_C} = 0;
980                     } else {
981                         print STDERR "DEBUG: Trying to match '$&' against '"
982                             ,join("', '", @{$state{$parens}})
983                             ,"'\n"
984                             if $opts{debug};
985                         die "Unmatched parentheses$opts{PLACE}\n"
986                             unless (@{$state{$parens}}
987                                     && pop @{$state{$parens}} eq $&);
988                         if (!@{$state{$parens}}) {
989                             $normalized_line .= $&.">>>";
990                         } else {
991                             $normalized_line .= $&;
992                         }
993                     }
994                 } elsif (m|^["']|) { # string start
995                     my $body = $&;
996                     $_ = $';
997
998                     # We want to separate strings from \w and \d with one space.
999                     $normalized_line .= " " if $normalized_line =~ m/(\w|\d)$/;
1000                     $normalized_line .= $body;
1001                     $state{in_string} = $body;
1002                 } elsif (m|^\/\*|) { # C style comment
1003                     print STDERR "DEBUG: found start of C style comment\n"
1004                         if $opts{debug};
1005                     $state{in_comment} = $&;
1006                     $_ = $';
1007                 } elsif (m|^\/\/|) { # C++ style comment
1008                     print STDERR "DEBUG: found C++ style comment\n"
1009                         if $opts{debug};
1010                     $_ = "";    # (just discard it entirely)
1011                 } elsif (m/^ (?| (?: 0[xX][[:xdigit:]]+ | 0[bB][01]+ | [0-9]+ )
1012                                  (?i: U | L | UL | LL | ULL )?
1013                                | [0-9]+\.[0-9]+(?:[eE][\-\+]\d+)? (?i: F | L)?
1014                                ) /x) {
1015                     print STDERR "DEBUG: Processing numbers: \$normalized_line = '$normalized_line', \$& = '$&', \$' = '$''\n"
1016                         if $opts{debug};
1017                     $normalized_line .= $&;
1018                     $_ = $';
1019                 } elsif (m/^[[:alpha:]_]\w*/) {
1020                     my $body = $&;
1021                     my $rest = $';
1022                     my $space = "";
1023
1024                     # Now, only add a space if it's needed to separate
1025                     # two \w characters, and we also surround strings with
1026                     # a space.  In this case, that's if $normalized_line ends
1027                     # with a \w, \d, " or '.
1028                     $space = " "
1029                         if ($normalized_line =~ m/("|')$/
1030                             || ($normalized_line =~ m/(\w|\d)$/
1031                                 && $body =~ m/^(\w|\d)/));
1032
1033                     print STDERR "DEBUG: Processing words: \$normalized_line = '$normalized_line', \$space = '$space', \$body = '$body', \$rest = '$rest'\n"
1034                         if $opts{debug};
1035                     $normalized_line .= $space.$body;
1036                     $_ = $rest;
1037                 } elsif (m|^(?:\\)?.|) { # Catch-all
1038                     $normalized_line .= $&;
1039                     $_ = $';
1040                 }
1041             }
1042         }
1043     }
1044     foreach my $handler (@endhandlers) {
1045         if ($handler->{massager}) {
1046             $handler->{massager}->(\%opts);
1047         }
1048     }
1049     return @result;
1050 }
1051
1052 # arg1:    line to check
1053 # arg2...: handlers to check
1054 # return undef when no handler matched
1055 sub _run_handlers {
1056     my %opts;
1057     if (ref($_[$#_]) eq "HASH") {
1058         %opts = %{$_[$#_]};
1059         pop @_;
1060     }
1061     my $line = shift;
1062     my @handlers = @_;
1063
1064     foreach my $handler (@handlers) {
1065         if ($handler->{regexp}
1066             && $line =~ m|^$handler->{regexp}$|) {
1067             if ($handler->{massager}) {
1068                 if ($opts{debug}) {
1069                     print STDERR "DEBUG[",$opts{debug_type},"]: Trying to handle '$line'\n";
1070                     print STDERR "DEBUG[",$opts{debug_type},"]: (matches /\^",$handler->{regexp},"\$/)\n";
1071                 }
1072                 my $saved_line = $line;
1073                 my @massaged =
1074                     map { s/(<<<|>>>)//g; $_ }
1075                     $handler->{massager}->($saved_line, \%opts);
1076                 print STDERR "DEBUG[",$opts{debug_type},"]: Got back '"
1077                     , join("', '", @massaged), "'\n"
1078                     if $opts{debug};
1079
1080                 # Because we may get back new lines to be
1081                 # injected before whatever else that follows,
1082                 # and the injected stuff might include
1083                 # preprocessor lines, we need to inject them
1084                 # in @lines and set $_ to the empty string to
1085                 # break out from the inner loops
1086                 my $injected_lines = shift @massaged || "";
1087
1088                 if (@massaged) {
1089                     return (1,
1090                             {
1091                                 name    => shift @massaged,
1092                                 type    => shift @massaged,
1093                                 returntype => shift @massaged,
1094                                 value   => shift @massaged,
1095                                 conds   => [ @massaged ]
1096                             },
1097                             $injected_lines
1098                         );
1099                 } else {
1100                     print STDERR "DEBUG[",$opts{debug_type},"]:   (ignore, possible side effects)\n"
1101                         if $opts{debug} && $injected_lines eq "";
1102                     return (1, $injected_lines);
1103                 }
1104             }
1105             return (1);
1106         }
1107     }
1108     return (0);
1109 }