ParseC.pm 45 KB

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