2 # Copyright 2018 The OpenSSL Project Authors. All Rights Reserved.
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
9 package OpenSSL::ParseC;
15 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
21 my @preprocessor_conds; # A list of simple preprocessor conditions,
22 # each item being a list of macros defined
27 return map { ( @$_ ) } @preprocessor_conds;
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:
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:
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
47 # [3] Return type (only for type 'F' and 'V')
48 # [4] Value (for type 'M') or signature (for type 'F',
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
56 # If the massager returns an empty list, it means the
57 # "complete" string has side effects but should otherwise
59 # If the massager is undefined, the "complete" string
61 my @opensslcpphandlers = (
62 ##################################################################
63 # OpenSSL CPP specials
65 # These are used to convert certain pre-precessor expressions into
66 # others that @cpphandlers have a better chance to understand.
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+)?)$/,
75 #if$1 OPENSSL_NO_DEPRECATEDIN_$2
81 ##################################################################
84 { regexp => qr/#ifdef ?(.*)/,
87 if (ref($_[$#_]) eq "HASH") {
91 push @preprocessor_conds, [ $1 ];
92 print STDERR "DEBUG[",$opts{debug_type},"]: preprocessor level: ", scalar(@preprocessor_conds), "\n"
97 { regexp => qr/#ifndef ?(.*)/,
100 if (ref($_[$#_]) eq "HASH") {
104 push @preprocessor_conds, [ '!'.$1 ];
105 print STDERR "DEBUG[",$opts{debug_type},"]: preprocessor level: ", scalar(@preprocessor_conds), "\n"
110 { regexp => qr/#if (0|1)/,
113 if (ref($_[$#_]) eq "HASH") {
118 push @preprocessor_conds, [ "TRUE" ];
120 push @preprocessor_conds, [ "!TRUE" ];
122 print STDERR "DEBUG[",$opts{debug_type},"]: preprocessor level: ", scalar(@preprocessor_conds), "\n"
127 { regexp => qr/#if ?(.*)/,
130 if (ref($_[$#_]) eq "HASH") {
136 if ($conds =~ m|^defined<<<\(([^\)]*)\)>>>(.*)$|) {
137 push @results, $1; # Handle the simple case
139 my $re = qr/^(?:\|\|defined<<<\([^\)]*\)>>>)*$/;
140 print STDERR "DEBUG[",$opts{debug_type},"]: Matching '$rest' with '$re'\n"
142 if ($rest =~ m/$re/) {
143 my @rest = split /\|\|/, $rest;
146 m|^defined<<<\(([^\)]*)\)>>>$|;
147 die "Something wrong...$opts{PLACE}" if $1 eq "";
151 $conds =~ s/<<<|>>>//g;
152 warn "Warning: complicated #if expression(1): $conds$opts{PLACE}"
155 } elsif ($conds =~ m|^!defined<<<\(([^\)]*)\)>>>(.*)$|) {
156 push @results, '!'.$1; # Handle the simple case
158 my $re = qr/^(?:\&\&!defined<<<\([^\)]*\)>>>)*$/;
159 print STDERR "DEBUG[",$opts{debug_type},"]: Matching '$rest' with '$re'\n"
161 if ($rest =~ m/$re/) {
162 my @rest = split /\&\&/, $rest;
165 m|^!defined<<<\(([^\)]*)\)>>>$|;
166 die "Something wrong...$opts{PLACE}" if $1 eq "";
167 push @results, '!'.$1;
170 $conds =~ s/<<<|>>>//g;
171 warn "Warning: complicated #if expression(2): $conds$opts{PLACE}"
175 $conds =~ s/<<<|>>>//g;
176 warn "Warning: complicated #if expression(3): $conds$opts{PLACE}"
179 print STDERR "DEBUG[",$opts{debug_type},"]: Added preprocessor conds: '", join("', '", @results), "'\n"
181 push @preprocessor_conds, [ @results ];
182 print STDERR "DEBUG[",$opts{debug_type},"]: preprocessor level: ", scalar(@preprocessor_conds), "\n"
187 { regexp => qr/#elif (.*)/,
190 if (ref($_[$#_]) eq "HASH") {
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"
204 { regexp => qr/#else/,
207 if (ref($_[$#_]) eq "HASH") {
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
218 print STDERR "DEBUG[",$opts{debug_type},"]: preprocessor level: ", scalar(@preprocessor_conds), "\n"
223 { regexp => qr/#endif ?/,
226 if (ref($_[$#_]) eq "HASH") {
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"
238 { regexp => qr/#define ([[:alpha:]_]\w*)(<<<\(.*?\)>>>)?( (.*))?/,
242 my $spaceval = $3||"";
245 $1, 'M', "", $params ? "$name$params$spaceval" : $val,
249 massager => sub { return (); }
253 my @opensslchandlers = (
254 ##################################################################
257 # They are really preprocessor stuff, but they look like C stuff
258 # to this parser. All of these do replacements, anything else is
262 # Deprecated stuff, by OpenSSL release.
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");
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"); }
284 { regexp => qr/DEFINE_LHASH_OF<<<\((.*)\)>>>/,
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,
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 *));
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"); }
315 # { regexp => qr/(.*)\bSTACK_OF\((.*?)\)(.*)/,
318 # my $stack_of = "struct stack_st_$2";
320 # if ($after =~ m|^\w|) { $after = " ".$after; }
321 # return ("$before$stack_of$after");
324 { regexp => qr/SKM_DEFINE_STACK_OF<<<\((.*),\s*(.*),\s*(.*)\)>>>/,
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,
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);
363 { regexp => qr/DEFINE_SPECIAL_STACK_OF<<<\((.*),\s*(.*)\)>>>/,
364 massager => sub { return ("SKM_DEFINE_STACK_OF($1,$2,$2)"); },
366 { regexp => qr/DEFINE_STACK_OF<<<\((.*)\)>>>/,
367 massager => sub { return ("SKM_DEFINE_STACK_OF($1,$1,$1)"); },
369 { regexp => qr/DEFINE_SPECIAL_STACK_OF_CONST<<<\((.*),\s*(.*)\)>>>/,
370 massager => sub { return ("SKM_DEFINE_STACK_OF($1,const $2,$2)"); },
372 { regexp => qr/DEFINE_STACK_OF_CONST<<<\((.*)\)>>>/,
373 massager => sub { return ("SKM_DEFINE_STACK_OF($1,const $1,$1)"); },
378 { regexp => qr/DECLARE_ASN1_ITEM<<<\((.*)\)>>>/,
381 const ASN1_ITEM *$1_it(void);
385 { regexp => qr/DECLARE_ASN1_ENCODE_FUNCTIONS_only<<<\((.*),\s*(.*)\)>>>/,
393 { regexp => qr/DECLARE_ASN1_ENCODE_FUNCTIONS<<<\((.*),\s*(.*),\s*(.*)\)>>>/,
398 DECLARE_ASN1_ITEM($2)
402 { regexp => qr/DECLARE_ASN1_ENCODE_FUNCTIONS_name<<<\((.*),\s*(.*)\)>>>/,
407 DECLARE_ASN1_ITEM($2)
411 { regexp => qr/DECLARE_ASN1_ALLOC_FUNCTIONS_name<<<\((.*),\s*(.*)\)>>>/,
419 { regexp => qr/DECLARE_ASN1_ALLOC_FUNCTIONS<<<\((.*)\)>>>/,
427 { regexp => qr/DECLARE_ASN1_FUNCTIONS_name<<<\((.*),\s*(.*)\)>>>/,
434 DECLARE_ASN1_ITEM($2)
438 { regexp => qr/DECLARE_ASN1_FUNCTIONS<<<\((.*)\)>>>/,
439 massager => sub { return (<<"EOF");
444 DECLARE_ASN1_ITEM($1)
448 { regexp => qr/DECLARE_ASN1_NDEF_FUNCTION<<<\((.*)\)>>>/,
451 int i2d_$1_NDEF(void);
455 { regexp => qr/DECLARE_ASN1_PRINT_FUNCTION<<<\((.*)\)>>>/,
458 int $1_print_ctx(void);
462 { regexp => qr/DECLARE_ASN1_PRINT_FUNCTION_name<<<\((.*),\s*(.*)\)>>>/,
465 int $2_print_ctx(void);
469 { regexp => qr/DECLARE_ASN1_SET_OF<<<\((.*)\)>>>/,
470 massager => sub { return (); }
472 { regexp => qr/DECLARE_ASN1_DUP_FUNCTION<<<\((.*)\)>>>/,
479 { regexp => qr/DECLARE_ASN1_DUP_FUNCTION_name<<<\((.*),\s*(.*)\)>>>/,
486 { regexp => qr/DECLARE_PKCS12_SET_OF<<<\((.*)\)>>>/,
487 massager => sub { return (); }
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);
495 int PEM_read_bio_$1(void);
496 int PEM_write_bio_$1(void);
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);
508 int PEM_write_bio_$1(void);
512 { regexp => qr/DECLARE_PEM(?|_read|_read_cb)<<<\((.*?),.*\)>>>/,
513 massager => sub { return (<<"EOF");
514 #ifndef OPENSSL_NO_STDIO
515 int PEM_read_$1(void);
517 int PEM_read_bio_$1(void);
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 (); }
532 ##################################################################
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); },
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
549 massager => sub { return (); },
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
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)
569 || sprintf("__anon%03d", ++$anoncnt); # Anonymous struct
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());
578 # If there was no before nor after, make the return much simple
579 return ("", "$word $name", $type, "", "$word$definition", all_conds());
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 (); }
588 # Function returning function pointer declaration
589 { regexp => qr/(?:(typedef)\s?)? # Possible typedef ($1)
590 ((?:\w|\*|\s)*?) # Return type ($2)
593 ([[:alpha:]_]\w*) # Function name ($3)
594 (\(.*\)) # Parameters ($4)
596 <<<(\(.*\))>>> # F.p. parameters ($5)
600 return ("", $3, 'F', "", "$2(*$4)$5", all_conds())
602 return ("", $3, 'F', "$2(*)$5", "$2(*$4)$5", all_conds()); }
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)
612 return ("", $3, 'T', "", "$2(*)$4", all_conds())
614 return ("", $3, 'V', "$2(*)$4", "$2(*)$4", all_conds());
617 # Function declaration, or typedef thereof
618 { regexp => qr/(?:(typedef)\s?)? # Possible typedef ($1)
619 ((?:\w|\*|\s)*?) # Return type ($2)
621 ([[:alpha:]_]\w*) # Function name ($3)
622 <<<(\(.*\))>>> # Parameters ($4)
626 return ("", $3, 'T', "", "$2$4", all_conds())
628 return ("", $3, 'F', $2, "$2$4", all_conds());
631 # Variable declaration, including arrays, or typedef thereof
632 { regexp => qr/(?:(typedef)\s?)? # Possible typedef ($1)
633 ((?:\w|\*|\s)*?) # Type ($2)
635 ([[:alpha:]_]\w*) # Variable name ($3)
636 ((?:<<<\[[^\]]*\]>>>)*) # Possible array declaration ($4)
640 return ("", $3, 'T', "", $2.($4||""), all_conds())
642 return ("", $3, 'V', $2.($4||""), $2.($4||""), all_conds());
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.
655 die "Unfinished preprocessor conditions levels: ",scalar(@preprocessor_conds),($opts{filename} ? " in file ".$opts{filename}: ""),$opts{PLACE}
656 if @preprocessor_conds;
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.
664 # returns a list of hashes with information:
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
671 # conds preprocessor conditions (array ref)
675 if (ref($_[$#_]) eq "HASH") {
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
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.
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
702 # 2. between words and number
703 # 3. after the first word of a preprocessor
705 # 4. for the #define directive, between the macro
706 # name/args and its value, so we end up with:
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.
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.
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$|;
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;
727 # Remember that extra # we added above? Now we remove it
729 pop @lines; # Don't forget the undef
732 if (!defined($lines[0])) {
734 $state{current_line}++;
736 $opts{PLACE} = " at ".$opts{filename}." line ".$state{current_line}."\n";
737 $opts{PLACE2} = $opts{filename}.":".$state{current_line};
742 $_ = "" unless defined $_;
751 print STDERR "DEBUG:----------------------------\n";
752 print STDERR "DEBUG: \$_ = '$_'\n";
755 ##########################################################
756 # Now that we have a full line, let's process through it
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"
766 $opts{debug_type} = "OPENSSL CPP";
767 my @r = ( _run_handlers($normalized_line,
771 # Checking if there are lines to inject.
773 @r = split $/, (pop @r).$_;
774 print STDERR "DEBUG[OPENSSL CPP]: injecting '", join("', '", @r),"'\n"
775 if $opts{debug} && @r;
776 @lines = ( @r, @lines );
781 print STDERR "DEBUG[CPP]: \$normalized_line = '$normalized_line'\n"
783 $opts{debug_type} = "CPP";
784 my @r = ( _run_handlers($normalized_line,
788 if (ref($r[0]) eq "HASH") {
789 push @result, shift @r;
792 # Now, check if there are lines to inject.
793 # Really, this should never happen, it IS a
794 # preprocessor directive after all...
796 @r = split $/, pop @r;
797 print STDERR "DEBUG[CPP]: injecting '", join("', '", @r),"'\n"
798 if $opts{debug} && @r;
799 @lines = ( @r, @lines );
805 # Note: we simply ignore all directives that no
807 $normalized_line = "";
810 # If the two strings end and start with a character that
811 # shouldn't get concatenated, add a space
813 ($collected_stmt =~ m/(?:"|')$/
814 || ($collected_stmt =~ m/(?:\w|\d)$/
815 && $normalized_line =~ m/^(?:\w|\d)/)) ? " " : "";
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} ) {
826 print STDERR "DEBUG[OPENSSL C]: \$collected_stmt = '$collected_stmt'\n";
827 print STDERR "DEBUG[OPENSSL C]: \$normalized_line = '$normalized_line'\n";
829 $opts{debug_type} = "OPENSSL C";
830 my @r = ( _run_handlers($collected_stmt
836 # Checking if there are lines to inject.
838 @r = split $/, (pop @r).$_;
839 print STDERR "DEBUG[OPENSSL]: injecting '", join("', '", @r),"'\n"
840 if $opts{debug} && @r;
841 @lines = ( @r, @lines );
845 $normalized_line = "";
846 $collected_stmt = "";
849 print STDERR "DEBUG[C]: \$collected_stmt = '$collected_stmt'\n";
850 print STDERR "DEBUG[C]: \$normalized_line = '$normalized_line'\n";
852 $opts{debug_type} = "C";
853 my @r = ( _run_handlers($collected_stmt
859 if (ref($r[0]) eq "HASH") {
860 push @result, shift @r;
863 # Checking if there are lines to inject.
865 @r = split $/, (pop @r).$_;
866 print STDERR "DEBUG[C]: injecting '", join("', '", @r),"'\n"
867 if $opts{debug} && @r;
868 @lines = ( @r, @lines );
872 $normalized_line = "";
873 $collected_stmt = "";
878 $collected_stmt .= $space.$normalized_line;
879 $normalized_line = "";
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
893 $normalized_line .= $`.$&;
894 $state{in_string} = "";
898 die "Unfinished string without continuation found$opts{PLACE}\n";
901 # ... or inside comments, whichever happens to apply
902 elsif ($state{in_comment}) {
904 # This should never happen
905 die "Something went seriously wrong, multiline //???$opts{PLACE}\n"
906 if ($state{in_comment} eq "//");
908 # A note: comments are simply discarded.
910 if (m/ (?:^|(?<!\\)) # Make sure it's not escaped
911 \*\/ # Look for C comment end
913 $state{in_comment} = "";
915 print STDERR "DEBUG: Found end of comment, followed by '$_'\n"
924 # At this point, it's safe to remove leading whites, but
925 # we need to be careful with some preprocessor lines
930 if ($normalized_line =~ m/^
931 \#define\s\w(?:\w|\d)*(?:<<<\([^\)]*\)>>>)?
934 print STDERR "DEBUG: Processing leading spaces: \$normalized_line = '$normalized_line', \$space = '$space', \$rest = '$rest'\n"
940 $normalized_line =~ m|^#| ? 'cpp_parens' : 'c_parens';
941 (my $paren_singular = $parens) =~ s|s$||;
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.
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"
956 $normalized_line = "";
958 $normalized_line .= "<<<".$body;
961 $normalized_line .= $body;
964 if ($normalized_line ne "") {
965 print STDERR "DEBUG: found $paren_singular start '$body'\n"
967 $body =~ tr|\{\[\(|\}\]\)|;
968 print STDERR "DEBUG: pushing $paren_singular end '$body'\n"
970 push @{$state{$parens}}, $body;
972 } elsif (m|^[\}\]\)]|) {
975 if (!@{$state{$parens}}
976 && $& eq '}' && $state{in_extern_C}) {
977 print STDERR "DEBUG: found end of 'extern \"C\"'\n"
979 $state{in_extern_C} = 0;
981 print STDERR "DEBUG: Trying to match '$&' against '"
982 ,join("', '", @{$state{$parens}})
985 die "Unmatched parentheses$opts{PLACE}\n"
986 unless (@{$state{$parens}}
987 && pop @{$state{$parens}} eq $&);
988 if (!@{$state{$parens}}) {
989 $normalized_line .= $&.">>>";
991 $normalized_line .= $&;
994 } elsif (m|^["']|) { # string start
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"
1005 $state{in_comment} = $&;
1007 } elsif (m|^\/\/|) { # C++ style comment
1008 print STDERR "DEBUG: found C++ style comment\n"
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)?
1015 print STDERR "DEBUG: Processing numbers: \$normalized_line = '$normalized_line', \$& = '$&', \$' = '$''\n"
1017 $normalized_line .= $&;
1019 } elsif (m/^[[:alpha:]_]\w*/) {
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 '.
1029 if ($normalized_line =~ m/("|')$/
1030 || ($normalized_line =~ m/(\w|\d)$/
1031 && $body =~ m/^(\w|\d)/));
1033 print STDERR "DEBUG: Processing words: \$normalized_line = '$normalized_line', \$space = '$space', \$body = '$body', \$rest = '$rest'\n"
1035 $normalized_line .= $space.$body;
1037 } elsif (m|^(?:\\)?.|) { # Catch-all
1038 $normalized_line .= $&;
1044 foreach my $handler (@endhandlers) {
1045 if ($handler->{massager}) {
1046 $handler->{massager}->(\%opts);
1052 # arg1: line to check
1053 # arg2...: handlers to check
1054 # return undef when no handler matched
1057 if (ref($_[$#_]) eq "HASH") {
1064 foreach my $handler (@handlers) {
1065 if ($handler->{regexp}
1066 && $line =~ m|^$handler->{regexp}$|) {
1067 if ($handler->{massager}) {
1069 print STDERR "DEBUG[",$opts{debug_type},"]: Trying to handle '$line'\n";
1070 print STDERR "DEBUG[",$opts{debug_type},"]: (matches /\^",$handler->{regexp},"\$/)\n";
1072 my $saved_line = $line;
1074 map { s/(<<<|>>>)//g; $_ }
1075 $handler->{massager}->($saved_line, \%opts);
1076 print STDERR "DEBUG[",$opts{debug_type},"]: Got back '"
1077 , join("', '", @massaged), "'\n"
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 || "";
1091 name => shift @massaged,
1092 type => shift @massaged,
1093 returntype => shift @massaged,
1094 value => shift @massaged,
1095 conds => [ @massaged ]
1100 print STDERR "DEBUG[",$opts{debug_type},"]: (ignore, possible side effects)\n"
1101 if $opts{debug} && $injected_lines eq "";
1102 return (1, $injected_lines);