Git for Windows 1.7.10-preview20120409
[msysgit.git] / bin / h2ph
blob38103f87595d0199025425a3c48953702eedaed9
1 #!/usr/bin/perl
2 eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
3 if $running_under_some_shell;
5 use strict;
7 use Config;
8 use File::Path qw(mkpath);
9 use Getopt::Std;
11 # Make sure read permissions for all are set:
12 if (defined umask && (umask() & 0444)) {
13 umask (umask() & ~0444);
16 getopts('Dd:rlhaQe');
17 use vars qw($opt_D $opt_d $opt_r $opt_l $opt_h $opt_a $opt_Q $opt_e);
18 die "-r and -a options are mutually exclusive\n" if ($opt_r and $opt_a);
19 my @inc_dirs = inc_dirs() if $opt_a;
21 my $Exit = 0;
23 my $Dest_dir = $opt_d || $Config{installsitearch};
24 die "Destination directory $Dest_dir doesn't exist or isn't a directory\n"
25 unless -d $Dest_dir;
27 my @isatype = qw(
28 char uchar u_char
29 short ushort u_short
30 int uint u_int
31 long ulong u_long
32 FILE key_t caddr_t
33 float double size_t
36 my %isatype;
37 @isatype{@isatype} = (1) x @isatype;
38 my $inif = 0;
39 my %Is_converted;
40 my %bad_file = ();
42 @ARGV = ('-') unless @ARGV;
44 build_preamble_if_necessary();
46 sub reindent($) {
47 my($text) = shift;
48 $text =~ s/\n/\n /g;
49 $text =~ s/ /\t/g;
50 $text;
53 my ($t, $tab, %curargs, $new, $eval_index, $dir, $name, $args, $outfile);
54 my ($incl, $incl_type, $next);
55 while (defined (my $file = next_file())) {
56 if (-l $file and -d $file) {
57 link_if_possible($file) if ($opt_l);
58 next;
61 # Recover from header files with unbalanced cpp directives
62 $t = '';
63 $tab = 0;
65 # $eval_index goes into ``#line'' directives, to help locate syntax errors:
66 $eval_index = 1;
68 if ($file eq '-') {
69 open(IN, "-");
70 open(OUT, ">-");
71 } else {
72 ($outfile = $file) =~ s/\.h$/.ph/ || next;
73 print "$file -> $outfile\n" unless $opt_Q;
74 if ($file =~ m|^(.*)/|) {
75 $dir = $1;
76 mkpath "$Dest_dir/$dir";
79 if ($opt_a) { # automagic mode: locate header file in @inc_dirs
80 foreach (@inc_dirs) {
81 chdir $_;
82 last if -f $file;
86 open(IN,"$file") || (($Exit = 1),(warn "Can't open $file: $!\n"),next);
87 open(OUT,">$Dest_dir/$outfile") || die "Can't create $outfile: $!\n";
90 print OUT
91 "require '_h2ph_pre.ph';\n\n",
92 "no warnings 'redefine';\n\n";
94 while (defined (local $_ = next_line($file))) {
95 if (s/^\s*\#\s*//) {
96 if (s/^define\s+(\w+)//) {
97 $name = $1;
98 $new = '';
99 s/\s+$//;
100 s/\(\w+\s*\(\*\)\s*\(\w*\)\)\s*(-?\d+)/$1/; # (int (*)(foo_t))0
101 if (s/^\(([\w,\s]*)\)//) {
102 $args = $1;
103 my $proto = '() ';
104 if ($args ne '') {
105 $proto = '';
106 foreach my $arg (split(/,\s*/,$args)) {
107 $arg =~ s/^\s*([^\s].*[^\s])\s*$/$1/;
108 $curargs{$arg} = 1;
110 $args =~ s/\b(\w)/\$$1/g;
111 $args = "my($args) = \@_;\n$t ";
113 s/^\s+//;
114 expr();
115 $new =~ s/(["\\])/\\$1/g; #"]);
116 EMIT:
117 $new = reindent($new);
118 $args = reindent($args);
119 if ($t ne '') {
120 $new =~ s/(['\\])/\\$1/g; #']);
121 if ($opt_h) {
122 print OUT $t,
123 "eval \"\\n#line $eval_index $outfile\\n\" . 'sub $name $proto\{\n$t ${args}eval q($new);\n$t}' unless defined(\&$name);\n";
124 $eval_index++;
125 } else {
126 print OUT $t,
127 "eval 'sub $name $proto\{\n$t ${args}eval q($new);\n$t}' unless defined(\&$name);\n";
129 } else {
130 print OUT "unless(defined(\&$name)) {\n sub $name $proto\{\n\t${args}eval q($new);\n }\n}\n";
132 %curargs = ();
133 } else {
134 s/^\s+//;
135 expr();
136 $new = 1 if $new eq '';
137 $new = reindent($new);
138 $args = reindent($args);
139 if ($t ne '') {
140 $new =~ s/(['\\])/\\$1/g; #']);
142 if ($opt_h) {
143 print OUT $t,"eval \"\\n#line $eval_index $outfile\\n\" . 'sub $name () {",$new,";}' unless defined(\&$name);\n";
144 $eval_index++;
145 } else {
146 print OUT $t,"eval 'sub $name () {",$new,";}' unless defined(\&$name);\n";
148 } else {
149 # Shunt around such directives as `#define FOO FOO':
150 next if " \&$name" eq $new;
152 print OUT $t,"unless(defined(\&$name)) {\n sub $name () {\t",$new,";}\n}\n";
155 } elsif (/^(include|import|include_next)\s*[<\"](.*)[>\"]/) {
156 $incl_type = $1;
157 $incl = $2;
158 if (($incl_type eq 'include_next') ||
159 ($opt_e && exists($bad_file{$incl}))) {
160 $incl =~ s/\.h$/.ph/;
161 print OUT ($t,
162 "eval {\n");
163 $tab += 4;
164 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
165 print OUT ($t, "my(\@REM);\n");
166 if ($incl_type eq 'include_next') {
167 print OUT ($t,
168 "my(\%INCD) = map { \$INC{\$_} => 1 } ",
169 "(grep { \$_ eq \"$incl\" } ",
170 "keys(\%INC));\n");
171 print OUT ($t,
172 "\@REM = map { \"\$_/$incl\" } ",
173 "(grep { not exists(\$INCD{\"\$_/$incl\"})",
174 " and -f \"\$_/$incl\" } \@INC);\n");
175 } else {
176 print OUT ($t,
177 "\@REM = map { \"\$_/$incl\" } ",
178 "(grep {-r \"\$_/$incl\" } \@INC);\n");
180 print OUT ($t,
181 "require \"\$REM[0]\" if \@REM;\n");
182 $tab -= 4;
183 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
184 print OUT ($t,
185 "};\n");
186 print OUT ($t,
187 "warn(\$\@) if \$\@;\n");
188 } else {
189 $incl =~ s/\.h$/.ph/;
190 print OUT $t,"require '$incl';\n";
192 } elsif (/^ifdef\s+(\w+)/) {
193 print OUT $t,"if(defined(&$1)) {\n";
194 $tab += 4;
195 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
196 } elsif (/^ifndef\s+(\w+)/) {
197 print OUT $t,"unless(defined(&$1)) {\n";
198 $tab += 4;
199 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
200 } elsif (s/^if\s+//) {
201 $new = '';
202 $inif = 1;
203 expr();
204 $inif = 0;
205 print OUT $t,"if($new) {\n";
206 $tab += 4;
207 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
208 } elsif (s/^elif\s+//) {
209 $new = '';
210 $inif = 1;
211 expr();
212 $inif = 0;
213 $tab -= 4;
214 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
215 print OUT $t,"}\n elsif($new) {\n";
216 $tab += 4;
217 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
218 } elsif (/^else/) {
219 $tab -= 4;
220 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
221 print OUT $t,"} else {\n";
222 $tab += 4;
223 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
224 } elsif (/^endif/) {
225 $tab -= 4;
226 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8);
227 print OUT $t,"}\n";
228 } elsif(/^undef\s+(\w+)/) {
229 print OUT $t, "undef(&$1) if defined(&$1);\n";
230 } elsif(/^error\s+(".*")/) {
231 print OUT $t, "die($1);\n";
232 } elsif(/^error\s+(.*)/) {
233 print OUT $t, "die(\"", quotemeta($1), "\");\n";
234 } elsif(/^warning\s+(.*)/) {
235 print OUT $t, "warn(\"", quotemeta($1), "\");\n";
236 } elsif(/^ident\s+(.*)/) {
237 print OUT $t, "# $1\n";
239 } elsif (/^\s*(typedef\s*)?enum\s*(\s+[a-zA-Z_]\w*\s*)?/) { # { for vi
240 until(/\{[^}]*\}.*;/ || /;/) {
241 last unless defined ($next = next_line($file));
242 chomp $next;
243 # drop "#define FOO FOO" in enums
244 $next =~ s/^\s*#\s*define\s+(\w+)\s+\1\s*$//;
245 # #defines in enums (aliases)
246 $next =~ s/^\s*#\s*define\s+(\w+)\s+(\w+)\s*$/$1 = $2,/;
247 $_ .= $next;
248 print OUT "# $next\n" if $opt_D;
250 s/#\s*if.*?#\s*endif//g; # drop #ifdefs
251 s@/\*.*?\*/@@g;
252 s/\s+/ /g;
253 next unless /^\s?(typedef\s?)?enum\s?([a-zA-Z_]\w*)?\s?\{(.*)\}\s?([a-zA-Z_]\w*)?\s?;/;
254 (my $enum_subs = $3) =~ s/\s//g;
255 my @enum_subs = split(/,/, $enum_subs);
256 my $enum_val = -1;
257 foreach my $enum (@enum_subs) {
258 my ($enum_name, $enum_value) = $enum =~ /^([a-zA-Z_]\w*)(=.+)?$/;
259 $enum_name or next;
260 $enum_value =~ s/^=//;
261 $enum_val = (length($enum_value) ? $enum_value : $enum_val + 1);
262 if ($opt_h) {
263 print OUT ($t,
264 "eval(\"\\n#line $eval_index $outfile\\n",
265 "sub $enum_name () \{ $enum_val; \}\") ",
266 "unless defined(\&$enum_name);\n");
267 ++ $eval_index;
268 } else {
269 print OUT ($t,
270 "eval(\"sub $enum_name () \{ $enum_val; \}\") ",
271 "unless defined(\&$enum_name);\n");
274 } elsif (/^(?:__extension__\s+)?(?:extern|static)\s+(?:__)?inline(?:__)?\s+/
275 and !/;\s*$/ and !/{\s*}\s*$/)
276 { # { for vi
277 # This is a hack to parse the inline functions in the glibc headers.
278 # Warning: massive kludge ahead. We suppose inline functions
279 # are mainly constructed like macros.
280 while (1) {
281 last unless defined ($next = next_line($file));
282 chomp $next;
283 undef $_, last if $next =~ /__THROW\s*;/
284 or $next =~ /^(__extension__|extern|static)\b/;
285 $_ .= " $next";
286 print OUT "# $next\n" if $opt_D;
287 last if $next =~ /^}|^{.*}\s*$/;
289 next if not defined; # because it's only a prototype
290 s/\b(__extension__|extern|static|(?:__)?inline(?:__)?)\b//g;
291 # violently drop #ifdefs
292 s/#\s*if.*?#\s*endif//g
293 and print OUT "# some #ifdef were dropped here -- fill in the blanks\n";
294 if (s/^(?:\w|\s|\*)*\s(\w+)\s*//) {
295 $name = $1;
296 } else {
297 warn "name not found"; next; # shouldn't occur...
299 my @args;
300 if (s/^\(([^()]*)\)\s*(\w+\s*)*//) {
301 for my $arg (split /,/, $1) {
302 if ($arg =~ /(\w+)\s*$/) {
303 $curargs{$1} = 1;
304 push @args, $1;
308 $args = (
309 @args
310 ? "my(" . (join ',', map "\$$_", @args) . ") = \@_;\n$t "
311 : ""
313 my $proto = @args ? '' : '() ';
314 $new = '';
315 s/\breturn\b//g; # "return" doesn't occur in macros usually...
316 expr();
317 # try to find and perlify local C variables
318 our @local_variables = (); # needs to be a our(): (?{...}) bug workaround
320 use re "eval";
321 my $typelist = join '|', keys %isatype;
322 $new =~ s['
323 (?:(?:__)?const(?:__)?\s+)?
324 (?:(?:un)?signed\s+)?
325 (?:long\s+)?
326 (?:$typelist)\s+
327 (\w+)
328 (?{ push @local_variables, $1 })
330 [my \$$1]gx;
331 $new =~ s['
332 (?:(?:__)?const(?:__)?\s+)?
333 (?:(?:un)?signed\s+)?
334 (?:long\s+)?
335 (?:$typelist)\s+
336 ' \s+ &(\w+) \s* ;
337 (?{ push @local_variables, $1 })
339 [my \$$1;]gx;
341 $new =~ s/&$_\b/\$$_/g for @local_variables;
342 $new =~ s/(["\\])/\\$1/g; #"]);
343 # now that's almost like a macro (we hope)
344 goto EMIT;
347 $Is_converted{$file} = 1;
348 if ($opt_e && exists($bad_file{$file})) {
349 unlink($Dest_dir . '/' . $outfile);
350 $next = '';
351 } else {
352 print OUT "1;\n";
353 queue_includes_from($file) if $opt_a;
357 if ($opt_e && (scalar(keys %bad_file) > 0)) {
358 warn "Was unable to convert the following files:\n";
359 warn "\t" . join("\n\t",sort(keys %bad_file)) . "\n";
362 exit $Exit;
364 sub expr {
365 $new = '"(assembly code)"' and return if /\b__asm__\b/; # freak out.
366 my $joined_args;
367 if(keys(%curargs)) {
368 $joined_args = join('|', keys(%curargs));
370 while ($_ ne '') {
371 s/^\&\&// && do { $new .= " &&"; next;}; # handle && operator
372 s/^\&([\(a-z\)]+)/$1/i; # hack for things that take the address of
373 s/^(\s+)// && do {$new .= ' '; next;};
374 s/^0X([0-9A-F]+)[UL]*//i
375 && do {my $hex = $1;
376 $hex =~ s/^0+//;
377 if (length $hex > 8 && !$Config{use64bitint}) {
378 # Croak if nv_preserves_uv_bits < 64 ?
379 $new .= hex(substr($hex, -8)) +
380 2**32 * hex(substr($hex, 0, -8));
381 # The above will produce "errorneus" code
382 # if the hex constant was e.g. inside UINT64_C
383 # macro, but then again, h2ph is an approximation.
384 } else {
385 $new .= lc("0x$hex");
387 next;};
388 s/^(-?\d+\.\d+E[-+]?\d+)[FL]?//i && do {$new .= $1; next;};
389 s/^(\d+)\s*[LU]*//i && do {$new .= $1; next;};
390 s/^("(\\"|[^"])*")// && do {$new .= $1; next;};
391 s/^'((\\"|[^"])*)'// && do {
392 if ($curargs{$1}) {
393 $new .= "ord('\$$1')";
394 } else {
395 $new .= "ord('$1')";
397 next;
399 # replace "sizeof(foo)" with "{foo}"
400 # also, remove * (C dereference operator) to avoid perl syntax
401 # problems. Where the %sizeof array comes from is anyone's
402 # guess (c2ph?), but this at least avoids fatal syntax errors.
403 # Behavior is undefined if sizeof() delimiters are unbalanced.
404 # This code was modified to able to handle constructs like this:
405 # sizeof(*(p)), which appear in the HP-UX 10.01 header files.
406 s/^sizeof\s*\(// && do {
407 $new .= '$sizeof';
408 my $lvl = 1; # already saw one open paren
409 # tack { on the front, and skip it in the loop
410 $_ = "{" . "$_";
411 my $index = 1;
412 # find balanced closing paren
413 while ($index <= length($_) && $lvl > 0) {
414 $lvl++ if substr($_, $index, 1) eq "(";
415 $lvl-- if substr($_, $index, 1) eq ")";
416 $index++;
418 # tack } on the end, replacing )
419 substr($_, $index - 1, 1) = "}";
420 # remove pesky * operators within the sizeof argument
421 substr($_, 0, $index - 1) =~ s/\*//g;
422 next;
424 # Eliminate typedefs
425 /\(([\w\s]+)[\*\s]*\)\s*[\w\(]/ && do {
426 my $doit = 1;
427 foreach (split /\s+/, $1) { # Make sure all the words are types,
428 unless($isatype{$_} or $_ eq 'struct' or $_ eq 'union'){
429 $doit = 0;
430 last;
433 if( $doit ){
434 s/\([\w\s]+[\*\s]*\)// && next; # then eliminate them.
437 # struct/union member, including arrays:
438 s/^([_A-Z]\w*(\[[^\]]+\])?((\.|->)[_A-Z]\w*(\[[^\]]+\])?)+)//i && do {
439 my $id = $1;
440 $id =~ s/(\.|(->))([^\.\-]*)/->\{$3\}/g;
441 $id =~ s/\b([^\$])($joined_args)/$1\$$2/g if length($joined_args);
442 while($id =~ /\[\s*([^\$\&\d\]]+)\]/) {
443 my($index) = $1;
444 $index =~ s/\s//g;
445 if(exists($curargs{$index})) {
446 $index = "\$$index";
447 } else {
448 $index = "&$index";
450 $id =~ s/\[\s*([^\$\&\d\]]+)\]/[$index]/;
452 $new .= " (\$$id)";
454 s/^([_a-zA-Z]\w*)// && do {
455 my $id = $1;
456 if ($id eq 'struct' || $id eq 'union') {
457 s/^\s+(\w+)//;
458 $id .= ' ' . $1;
459 $isatype{$id} = 1;
460 } elsif ($id =~ /^((un)?signed)|(long)|(short)$/) {
461 while (s/^\s+(\w+)//) { $id .= ' ' . $1; }
462 $isatype{$id} = 1;
464 if ($curargs{$id}) {
465 $new .= "\$$id";
466 $new .= '->' if /^[\[\{]/;
467 } elsif ($id eq 'defined') {
468 $new .= 'defined';
469 } elsif (/^\s*\(/) {
470 s/^\s*\((\w),/("$1",/ if $id =~ /^_IO[WR]*$/i; # cheat
471 $new .= " &$id";
472 } elsif ($isatype{$id}) {
473 if ($new =~ /{\s*$/) {
474 $new .= "'$id'";
475 } elsif ($new =~ /\(\s*$/ && /^[\s*]*\)/) {
476 $new =~ s/\(\s*$//;
477 s/^[\s*]*\)//;
478 } else {
479 $new .= q(').$id.q(');
481 } else {
482 if ($inif && $new !~ /defined\s*\($/) {
483 $new .= '(defined(&' . $id . ') ? &' . $id . ' : 0)';
484 } elsif (/^\[/) {
485 $new .= " \$$id";
486 } else {
487 $new .= ' &' . $id;
490 next;
492 s/^(.)// && do { if ($1 ne '#') { $new .= $1; } next;};
497 sub next_line
499 my $file = shift;
500 my ($in, $out);
501 my $pre_sub_tri_graphs = 1;
503 READ: while (not eof IN) {
504 $in .= <IN>;
505 chomp $in;
506 next unless length $in;
508 while (length $in) {
509 if ($pre_sub_tri_graphs) {
510 # Preprocess all tri-graphs
511 # including things stuck in quoted string constants.
512 $in =~ s/\?\?=/#/g; # | ??=| #|
513 $in =~ s/\?\?\!/|/g; # | ??!| ||
514 $in =~ s/\?\?'/^/g; # | ??'| ^|
515 $in =~ s/\?\?\(/[/g; # | ??(| [|
516 $in =~ s/\?\?\)/]/g; # | ??)| ]|
517 $in =~ s/\?\?\-/~/g; # | ??-| ~|
518 $in =~ s/\?\?\//\\/g; # | ??/| \|
519 $in =~ s/\?\?</{/g; # | ??<| {|
520 $in =~ s/\?\?>/}/g; # | ??>| }|
522 if ($in =~ /^\#ifdef __LANGUAGE_PASCAL__/) {
523 # Tru64 disassembler.h evilness: mixed C and Pascal.
524 while (<IN>) {
525 last if /^\#endif/;
527 $in = "";
528 next READ;
530 if ($in =~ /^extern inline / && # Inlined assembler.
531 $^O eq 'linux' && $file =~ m!(?:^|/)asm/[^/]+\.h$!) {
532 while (<IN>) {
533 last if /^}/;
535 $in = "";
536 next READ;
538 if ($in =~ s/\\$//) { # \-newline
539 $out .= ' ';
540 next READ;
541 } elsif ($in =~ s/^([^"'\\\/]+)//) { # Passthrough
542 $out .= $1;
543 } elsif ($in =~ s/^(\\.)//) { # \...
544 $out .= $1;
545 } elsif ($in =~ /^'/) { # '...
546 if ($in =~ s/^('(\\.|[^'\\])*')//) {
547 $out .= $1;
548 } else {
549 next READ;
551 } elsif ($in =~ /^"/) { # "...
552 if ($in =~ s/^("(\\.|[^"\\])*")//) {
553 $out .= $1;
554 } else {
555 next READ;
557 } elsif ($in =~ s/^\/\/.*//) { # //...
558 # fall through
559 } elsif ($in =~ m/^\/\*/) { # /*...
560 # C comment removal adapted from perlfaq6:
561 if ($in =~ s/^\/\*[^*]*\*+([^\/*][^*]*\*+)*\///) {
562 $out .= ' ';
563 } else { # Incomplete /* */
564 next READ;
566 } elsif ($in =~ s/^(\/)//) { # /...
567 $out .= $1;
568 } elsif ($in =~ s/^([^\'\"\\\/]+)//) {
569 $out .= $1;
570 } elsif ($^O eq 'linux' &&
571 $file =~ m!(?:^|/)linux/byteorder/pdp_endian\.h$! &&
572 $in =~ s!\'T KNOW!!) {
573 $out =~ s!I DON$!I_DO_NOT_KNOW!;
574 } else {
575 if ($opt_e) {
576 warn "Cannot parse $file:\n$in\n";
577 $bad_file{$file} = 1;
578 $in = '';
579 $out = undef;
580 last READ;
581 } else {
582 die "Cannot parse:\n$in\n";
587 last READ if $out =~ /\S/;
590 return $out;
594 # Handle recursive subdirectories without getting a grotesquely big stack.
595 # Could this be implemented using File::Find?
596 sub next_file
598 my $file;
600 while (@ARGV) {
601 $file = shift @ARGV;
603 if ($file eq '-' or -f $file or -l $file) {
604 return $file;
605 } elsif (-d $file) {
606 if ($opt_r) {
607 expand_glob($file);
608 } else {
609 print STDERR "Skipping directory `$file'\n";
611 } elsif ($opt_a) {
612 return $file;
613 } else {
614 print STDERR "Skipping `$file': not a file or directory\n";
618 return undef;
622 # Put all the files in $directory into @ARGV for processing.
623 sub expand_glob
625 my ($directory) = @_;
627 $directory =~ s:/$::;
629 opendir DIR, $directory;
630 foreach (readdir DIR) {
631 next if ($_ eq '.' or $_ eq '..');
633 # expand_glob() is going to be called until $ARGV[0] isn't a
634 # directory; so push directories, and unshift everything else.
635 if (-d "$directory/$_") { push @ARGV, "$directory/$_" }
636 else { unshift @ARGV, "$directory/$_" }
638 closedir DIR;
642 # Given $file, a symbolic link to a directory in the C include directory,
643 # make an equivalent symbolic link in $Dest_dir, if we can figure out how.
644 # Otherwise, just duplicate the file or directory.
645 sub link_if_possible
647 my ($dirlink) = @_;
648 my $target = eval 'readlink($dirlink)';
650 if ($target =~ m:^\.\./: or $target =~ m:^/:) {
651 # The target of a parent or absolute link could leave the $Dest_dir
652 # hierarchy, so let's put all of the contents of $dirlink (actually,
653 # the contents of $target) into @ARGV; as a side effect down the
654 # line, $dirlink will get created as an _actual_ directory.
655 expand_glob($dirlink);
656 } else {
657 if (-l "$Dest_dir/$dirlink") {
658 unlink "$Dest_dir/$dirlink" or
659 print STDERR "Could not remove link $Dest_dir/$dirlink: $!\n";
662 if (eval 'symlink($target, "$Dest_dir/$dirlink")') {
663 print "Linking $target -> $Dest_dir/$dirlink\n";
665 # Make sure that the link _links_ to something:
666 if (! -e "$Dest_dir/$target") {
667 mkpath("$Dest_dir/$target", 0755) or
668 print STDERR "Could not create $Dest_dir/$target/\n";
670 } else {
671 print STDERR "Could not symlink $target -> $Dest_dir/$dirlink: $!\n";
677 # Push all #included files in $file onto our stack, except for STDIN
678 # and files we've already processed.
679 sub queue_includes_from
681 my ($file) = @_;
682 my $line;
684 return if ($file eq "-");
686 open HEADER, $file or return;
687 while (defined($line = <HEADER>)) {
688 while (/\\$/) { # Handle continuation lines
689 chop $line;
690 $line .= <HEADER>;
693 if ($line =~ /^#\s*include\s+<(.*?)>/) {
694 push(@ARGV, $1) unless $Is_converted{$1};
697 close HEADER;
701 # Determine include directories; $Config{usrinc} should be enough for (all
702 # non-GCC?) C compilers, but gcc uses an additional include directory.
703 sub inc_dirs
705 my $from_gcc = `LC_ALL=C $Config{cc} -v 2>&1`;
706 if( !( $from_gcc =~ s:^Reading specs from (.*?)/specs\b.*:$1/include:s ) )
707 { # gcc-4+ :
708 $from_gcc = `LC_ALL=C $Config{cc} -print-search-dirs 2>&1`;
709 if ( !($from_gcc =~ s/^install:\s*([^\s]+[^\s\/])([\s\/]*).*$/$1\/include/s) )
711 $from_gcc = '';
714 length($from_gcc) ? ($from_gcc, $Config{usrinc}) : ($Config{usrinc});
718 # Create "_h2ph_pre.ph", if it doesn't exist or was built by a different
719 # version of h2ph.
720 sub build_preamble_if_necessary
722 # Increment $VERSION every time this function is modified:
723 my $VERSION = 2;
724 my $preamble = "$Dest_dir/_h2ph_pre.ph";
726 # Can we skip building the preamble file?
727 if (-r $preamble) {
728 # Extract version number from first line of preamble:
729 open PREAMBLE, $preamble or die "Cannot open $preamble: $!";
730 my $line = <PREAMBLE>;
731 $line =~ /(\b\d+\b)/;
732 close PREAMBLE or die "Cannot close $preamble: $!";
734 # Don't build preamble if a compatible preamble exists:
735 return if $1 == $VERSION;
738 my (%define) = _extract_cc_defines();
740 open PREAMBLE, ">$preamble" or die "Cannot open $preamble: $!";
741 print PREAMBLE "# This file was created by h2ph version $VERSION\n";
743 foreach (sort keys %define) {
744 if ($opt_D) {
745 print PREAMBLE "# $_=$define{$_}\n";
748 if ($define{$_} =~ /^(\d+)U?L{0,2}$/i) {
749 print PREAMBLE
750 "unless (defined &$_) { sub $_() { $1 } }\n\n";
751 } elsif ($define{$_} =~ /^\w+$/) {
752 print PREAMBLE
753 "unless (defined &$_) { sub $_() { &$define{$_} } }\n\n";
754 } else {
755 print PREAMBLE
756 "unless (defined &$_) { sub $_() { \"",
757 quotemeta($define{$_}), "\" } }\n\n";
760 close PREAMBLE or die "Cannot close $preamble: $!";
764 # %Config contains information on macros that are pre-defined by the
765 # system's compiler. We need this information to make the .ph files
766 # function with perl as the .h files do with cc.
767 sub _extract_cc_defines
769 my %define;
770 my $allsymbols = join " ",
771 @Config{'ccsymbols', 'cppsymbols', 'cppccsymbols'};
773 # Split compiler pre-definitions into `key=value' pairs:
774 foreach (split /\s+/, $allsymbols) {
775 /(.+?)=(.+)/ and $define{$1} = $2;
777 if ($opt_D) {
778 print STDERR "$_: $1 -> $2\n";
782 return %define;
788 ##############################################################################
789 __END__
791 =head1 NAME
793 h2ph - convert .h C header files to .ph Perl header files
795 =head1 SYNOPSIS
797 B<h2ph [-d destination directory] [-r | -a] [-l] [headerfiles]>
799 =head1 DESCRIPTION
801 I<h2ph>
802 converts any C header files specified to the corresponding Perl header file
803 format.
804 It is most easily run while in /usr/include:
806 cd /usr/include; h2ph * sys/*
810 cd /usr/include; h2ph * sys/* arpa/* netinet/*
814 cd /usr/include; h2ph -r -l .
816 The output files are placed in the hierarchy rooted at Perl's
817 architecture dependent library directory. You can specify a different
818 hierarchy with a B<-d> switch.
820 If run with no arguments, filters standard input to standard output.
822 =head1 OPTIONS
824 =over 4
826 =item -d destination_dir
828 Put the resulting B<.ph> files beneath B<destination_dir>, instead of
829 beneath the default Perl library location (C<$Config{'installsitsearch'}>).
831 =item -r
833 Run recursively; if any of B<headerfiles> are directories, then run I<h2ph>
834 on all files in those directories (and their subdirectories, etc.). B<-r>
835 and B<-a> are mutually exclusive.
837 =item -a
839 Run automagically; convert B<headerfiles>, as well as any B<.h> files
840 which they include. This option will search for B<.h> files in all
841 directories which your C compiler ordinarily uses. B<-a> and B<-r> are
842 mutually exclusive.
844 =item -l
846 Symbolic links will be replicated in the destination directory. If B<-l>
847 is not specified, then links are skipped over.
849 =item -h
851 Put ``hints'' in the .ph files which will help in locating problems with
852 I<h2ph>. In those cases when you B<require> a B<.ph> file containing syntax
853 errors, instead of the cryptic
855 [ some error condition ] at (eval mmm) line nnn
857 you will see the slightly more helpful
859 [ some error condition ] at filename.ph line nnn
861 However, the B<.ph> files almost double in size when built using B<-h>.
863 =item -D
865 Include the code from the B<.h> file as a comment in the B<.ph> file.
866 This is primarily used for debugging I<h2ph>.
868 =item -Q
870 ``Quiet'' mode; don't print out the names of the files being converted.
872 =back
874 =head1 ENVIRONMENT
876 No environment variables are used.
878 =head1 FILES
880 /usr/include/*.h
881 /usr/include/sys/*.h
883 etc.
885 =head1 AUTHOR
887 Larry Wall
889 =head1 SEE ALSO
891 perl(1)
893 =head1 DIAGNOSTICS
895 The usual warnings if it can't read or write the files involved.
897 =head1 BUGS
899 Doesn't construct the %sizeof array for you.
901 It doesn't handle all C constructs, but it does attempt to isolate
902 definitions inside evals so that you can get at the definitions
903 that it can translate.
905 It's only intended as a rough tool.
906 You may need to dicker with the files produced.
908 You have to run this program by hand; it's not run as part of the Perl
909 installation.
911 Doesn't handle complicated expressions built piecemeal, a la:
913 enum {
914 FIRST_VALUE,
915 SECOND_VALUE,
916 #ifdef ABC
917 THIRD_VALUE
918 #endif
921 Doesn't necessarily locate all of your C compiler's internally-defined
922 symbols.
924 =cut