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