1#!/usr/local/bin/perl 2 3use Config; 4use File::Basename qw(basename dirname); 5use Cwd; 6 7# List explicitly here the variables you want Configure to 8# generate. Metaconfig only looks for shell variables, so you 9# have to mention them as if they were shell variables, not 10# %Config entries. Thus you write 11# $startperl 12# to ensure Configure will look for $Config{startperl}. 13# Wanted: $archlibexp 14 15# This forces PL files to create target in same directory as PL file. 16# This is so that make depend always knows where to find PL derivatives. 17$origdir = cwd; 18chdir dirname($0); 19$file = basename($0, '.PL'); 20$file .= '.com' if $^O eq 'VMS'; 21 22open OUT,">$file" or die "Can't create $file: $!"; 23 24print "Extracting $file (with variable substitutions)\n"; 25 26# In this section, perl variables will be expanded during extraction. 27# You can use $Config{...} to use Configure variables. 28 29print OUT <<"!GROK!THIS!"; 30$Config{startperl} 31 eval 'exec $Config{perlpath} -S \$0 \${1+"\$@"}' 32 if \$running_under_some_shell; 33!GROK!THIS! 34 35# In the following, perl variables are not expanded during extraction. 36 37print OUT <<'!NO!SUBS!'; 38 39use strict; 40 41use Config; 42use File::Path qw(mkpath); 43use Getopt::Std; 44 45# Make sure read permissions for all are set: 46if (defined umask && (umask() & 0444)) { 47 umask (umask() & ~0444); 48} 49 50getopts('Dd:rlhaQe'); 51use vars qw($opt_D $opt_d $opt_r $opt_l $opt_h $opt_a $opt_Q $opt_e); 52die "-r and -a options are mutually exclusive\n" if ($opt_r and $opt_a); 53my @inc_dirs = inc_dirs() if $opt_a; 54 55my $Exit = 0; 56 57my $Dest_dir = $opt_d || $Config{installsitearch}; 58die "Destination directory $Dest_dir doesn't exist or isn't a directory\n" 59 unless -d $Dest_dir; 60 61my @isatype = qw( 62 char uchar u_char 63 short ushort u_short 64 int uint u_int 65 long ulong u_long 66 FILE key_t caddr_t 67 float double size_t 68); 69 70my %isatype; 71@isatype{@isatype} = (1) x @isatype; 72my $inif = 0; 73my %Is_converted; 74my %bad_file = (); 75 76@ARGV = ('-') unless @ARGV; 77 78build_preamble_if_necessary(); 79 80sub reindent($) { 81 my($text) = shift; 82 $text =~ s/\n/\n /g; 83 $text =~ s/ /\t/g; 84 $text; 85} 86 87my ($t, $tab, %curargs, $new, $eval_index, $dir, $name, $args, $outfile); 88my ($incl, $incl_type, $incl_quote, $next); 89while (defined (my $file = next_file())) { 90 if (-l $file and -d $file) { 91 link_if_possible($file) if ($opt_l); 92 next; 93 } 94 95 # Recover from header files with unbalanced cpp directives 96 $t = ''; 97 $tab = 0; 98 99 # $eval_index goes into ``#line'' directives, to help locate syntax errors: 100 $eval_index = 1; 101 102 if ($file eq '-') { 103 open(IN, "-"); 104 open(OUT, ">-"); 105 } else { 106 ($outfile = $file) =~ s/\.h$/.ph/ || next; 107 print "$file -> $outfile\n" unless $opt_Q; 108 if ($file =~ m|^(.*)/|) { 109 $dir = $1; 110 mkpath "$Dest_dir/$dir"; 111 } 112 113 if ($opt_a) { # automagic mode: locate header file in @inc_dirs 114 foreach (@inc_dirs) { 115 chdir $_; 116 last if -f $file; 117 } 118 } 119 120 open(IN,"$file") || (($Exit = 1),(warn "Can't open $file: $!\n"),next); 121 open(OUT,">$Dest_dir/$outfile") || die "Can't create $outfile: $!\n"; 122 } 123 124 print OUT 125 "require '_h2ph_pre.ph';\n\n", 126 "no warnings qw(redefine misc);\n\n"; 127 128 while (defined (local $_ = next_line($file))) { 129 if (s/^\s*\#\s*//) { 130 if (s/^define\s+(\w+)//) { 131 $name = $1; 132 $new = ''; 133 s/\s+$//; 134 s/\(\w+\s*\(\*\)\s*\(\w*\)\)\s*(-?\d+)/$1/; # (int (*)(foo_t))0 135 if (s/^\(([\w,\s]*)\)//) { 136 $args = $1; 137 my $proto = '() '; 138 if ($args ne '') { 139 $proto = ''; 140 foreach my $arg (split(/,\s*/,$args)) { 141 $arg =~ s/^\s*([^\s].*[^\s])\s*$/$1/; 142 $curargs{$arg} = 1; 143 } 144 $args =~ s/\b(\w)/\$$1/g; 145 $args = "my($args) = \@_;\n$t "; 146 } 147 s/^\s+//; 148 expr(); 149 $new =~ s/(["\\])/\\$1/g; #"]); 150 EMIT($proto); 151 } else { 152 s/^\s+//; 153 expr(); 154 $new = 1 if $new eq ''; 155 $new = reindent($new); 156 $args = reindent($args); 157 if ($t ne '') { 158 $new =~ s/(['\\])/\\$1/g; #']); 159 160 if ($opt_h) { 161 print OUT $t,"eval \"\\n#line $eval_index $outfile\\n\" . 'sub $name () {",$new,";}' unless defined(\&$name);\n"; 162 $eval_index++; 163 } else { 164 print OUT $t,"eval 'sub $name () {",$new,";}' unless defined(\&$name);\n"; 165 } 166 } else { 167 # Shunt around such directives as `#define FOO FOO': 168 next if " \&$name" eq $new; 169 170 print OUT $t,"unless(defined(\&$name)) {\n sub $name () {\t",$new,";}\n}\n"; 171 } 172 } 173 } elsif (/^(include|import|include_next)\s*([<\"])(.*)[>\"]/) { 174 $incl_type = $1; 175 $incl_quote = $2; 176 $incl = $3; 177 if (($incl_type eq 'include_next') || 178 ($opt_e && exists($bad_file{$incl}))) { 179 $incl =~ s/\.h$/.ph/; 180 print OUT ($t, 181 "eval {\n"); 182 $tab += 4; 183 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); 184 print OUT ($t, "my(\@REM);\n"); 185 if ($incl_type eq 'include_next') { 186 print OUT ($t, 187 "my(\%INCD) = map { \$INC{\$_} => 1 } ", 188 "(grep { \$_ eq \"$incl\" } ", 189 "keys(\%INC));\n"); 190 print OUT ($t, 191 "\@REM = map { \"\$_/$incl\" } ", 192 "(grep { not exists(\$INCD{\"\$_/$incl\"})", 193 " and -f \"\$_/$incl\" } \@INC);\n"); 194 } else { 195 print OUT ($t, 196 "\@REM = map { \"\$_/$incl\" } ", 197 "(grep {-r \"\$_/$incl\" } \@INC);\n"); 198 } 199 print OUT ($t, 200 "require \"\$REM[0]\" if \@REM;\n"); 201 $tab -= 4; 202 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); 203 print OUT ($t, 204 "};\n"); 205 print OUT ($t, 206 "warn(\$\@) if \$\@;\n"); 207 } else { 208 $incl =~ s/\.h$/.ph/; 209 # copy the prefix in the quote syntax (#include "x.h") case 210 if ($incl !~ m|/| && $incl_quote eq q{"} && $file =~ m|^(.*)/|) { 211 $incl = "$1/$incl"; 212 } 213 print OUT $t,"require '$incl';\n"; 214 } 215 } elsif (/^ifdef\s+(\w+)/) { 216 print OUT $t,"if(defined(&$1)) {\n"; 217 $tab += 4; 218 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); 219 } elsif (/^ifndef\s+(\w+)/) { 220 print OUT $t,"unless(defined(&$1)) {\n"; 221 $tab += 4; 222 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); 223 } elsif (s/^if\s+//) { 224 $new = ''; 225 $inif = 1; 226 expr(); 227 $inif = 0; 228 print OUT $t,"if($new) {\n"; 229 $tab += 4; 230 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); 231 } elsif (s/^elif\s+//) { 232 $new = ''; 233 $inif = 1; 234 expr(); 235 $inif = 0; 236 $tab -= 4; 237 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); 238 print OUT $t,"}\n elsif($new) {\n"; 239 $tab += 4; 240 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); 241 } elsif (/^else/) { 242 $tab -= 4; 243 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); 244 print OUT $t,"} else {\n"; 245 $tab += 4; 246 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); 247 } elsif (/^endif/) { 248 $tab -= 4; 249 $t = "\t" x ($tab / 8) . ' ' x ($tab % 8); 250 print OUT $t,"}\n"; 251 } elsif(/^undef\s+(\w+)/) { 252 print OUT $t, "undef(&$1) if defined(&$1);\n"; 253 } elsif(/^error\s+(".*")/) { 254 print OUT $t, "die($1);\n"; 255 } elsif(/^error\s+(.*)/) { 256 print OUT $t, "die(\"", quotemeta($1), "\");\n"; 257 } elsif(/^warning\s+(.*)/) { 258 print OUT $t, "warn(\"", quotemeta($1), "\");\n"; 259 } elsif(/^ident\s+(.*)/) { 260 print OUT $t, "# $1\n"; 261 } 262 } elsif (/^\s*(typedef\s*)?enum\s*(\s+[a-zA-Z_]\w*\s*)?/) { # { for vi 263 until(/\{[^}]*\}.*;/ || /;/) { 264 last unless defined ($next = next_line($file)); 265 chomp $next; 266 # drop "#define FOO FOO" in enums 267 $next =~ s/^\s*#\s*define\s+(\w+)\s+\1\s*$//; 268 # #defines in enums (aliases) 269 $next =~ s/^\s*#\s*define\s+(\w+)\s+(\w+)\s*$/$1 = $2,/; 270 $_ .= $next; 271 print OUT "# $next\n" if $opt_D; 272 } 273 s/#\s*if.*?#\s*endif//g; # drop #ifdefs 274 s@/\*.*?\*/@@g; 275 s/\s+/ /g; 276 next unless /^\s?(typedef\s?)?enum\s?([a-zA-Z_]\w*)?\s?\{(.*)\}\s?([a-zA-Z_]\w*)?\s?;/; 277 (my $enum_subs = $3) =~ s/\s//g; 278 my @enum_subs = split(/,/, $enum_subs); 279 my $enum_val = -1; 280 foreach my $enum (@enum_subs) { 281 my ($enum_name, $enum_value) = $enum =~ /^([a-zA-Z_]\w*)(=.+)?$/; 282 $enum_name or next; 283 $enum_value =~ s/^=//; 284 $enum_val = (length($enum_value) ? $enum_value : $enum_val + 1); 285 if ($opt_h) { 286 print OUT ($t, 287 "eval(\"\\n#line $eval_index $outfile\\n", 288 "sub $enum_name () \{ $enum_val; \}\") ", 289 "unless defined(\&$enum_name);\n"); 290 ++ $eval_index; 291 } else { 292 print OUT ($t, 293 "eval(\"sub $enum_name () \{ $enum_val; \}\") ", 294 "unless defined(\&$enum_name);\n"); 295 } 296 } 297 } elsif (/^(?:__extension__\s+)?(?:extern|static)\s+(?:__)?inline(?:__)?\s+/ 298 and !/;\s*$/ and !/{\s*}\s*$/) 299 { # { for vi 300 # This is a hack to parse the inline functions in the glibc headers. 301 # Warning: massive kludge ahead. We suppose inline functions 302 # are mainly constructed like macros. 303 while (1) { 304 last unless defined ($next = next_line($file)); 305 chomp $next; 306 undef $_, last if $next =~ /__THROW\s*;/ 307 or $next =~ /^(__extension__|extern|static)\b/; 308 $_ .= " $next"; 309 print OUT "# $next\n" if $opt_D; 310 last if $next =~ /^}|^{.*}\s*$/; 311 } 312 next if not defined; # because it's only a prototype 313 s/\b(__extension__|extern|static|(?:__)?inline(?:__)?)\b//g; 314 # violently drop #ifdefs 315 s/#\s*if.*?#\s*endif//g 316 and print OUT "# some #ifdef were dropped here -- fill in the blanks\n"; 317 if (s/^(?:\w|\s|\*)*\s(\w+)\s*//) { 318 $name = $1; 319 } else { 320 warn "name not found"; next; # shouldn't occur... 321 } 322 my @args; 323 if (s/^\(([^()]*)\)\s*(\w+\s*)*//) { 324 for my $arg (split /,/, $1) { 325 if ($arg =~ /(\w+)\s*$/) { 326 $curargs{$1} = 1; 327 push @args, $1; 328 } 329 } 330 } 331 $args = ( 332 @args 333 ? "my(" . (join ',', map "\$$_", @args) . ") = \@_;\n$t " 334 : "" 335 ); 336 my $proto = @args ? '' : '() '; 337 $new = ''; 338 s/\breturn\b//g; # "return" doesn't occur in macros usually... 339 expr(); 340 # try to find and perlify local C variables 341 our @local_variables = (); # needs to be a our(): (?{...}) bug workaround 342 { 343 use re "eval"; 344 my $typelist = join '|', keys %isatype; 345 $new =~ s[' 346 (?:(?:__)?const(?:__)?\s+)? 347 (?:(?:un)?signed\s+)? 348 (?:long\s+)? 349 (?:$typelist)\s+ 350 (\w+) 351 (?{ push @local_variables, $1 }) 352 '] 353 [my \$$1]gx; 354 $new =~ s[' 355 (?:(?:__)?const(?:__)?\s+)? 356 (?:(?:un)?signed\s+)? 357 (?:long\s+)? 358 (?:$typelist)\s+ 359 ' \s+ &(\w+) \s* ; 360 (?{ push @local_variables, $1 }) 361 ] 362 [my \$$1;]gx; 363 } 364 $new =~ s/&$_\b/\$$_/g for @local_variables; 365 $new =~ s/(["\\])/\\$1/g; #"]); 366 # now that's almost like a macro (we hope) 367 EMIT($proto); 368 } 369 } 370 $Is_converted{$file} = 1; 371 if ($opt_e && exists($bad_file{$file})) { 372 unlink($Dest_dir . '/' . $outfile); 373 $next = ''; 374 } else { 375 print OUT "1;\n"; 376 queue_includes_from($file) if $opt_a; 377 } 378} 379 380if ($opt_e && (scalar(keys %bad_file) > 0)) { 381 warn "Was unable to convert the following files:\n"; 382 warn "\t" . join("\n\t",sort(keys %bad_file)) . "\n"; 383} 384 385exit $Exit; 386 387sub EMIT { 388 my $proto = shift; 389 390 $new = reindent($new); 391 $args = reindent($args); 392 if ($t ne '') { 393 $new =~ s/(['\\])/\\$1/g; #']); 394 if ($opt_h) { 395 print OUT $t, 396 "eval \"\\n#line $eval_index $outfile\\n\" . 'sub $name $proto\{\n$t ${args}eval q($new);\n$t}' unless defined(\&$name);\n"; 397 $eval_index++; 398 } else { 399 print OUT $t, 400 "eval 'sub $name $proto\{\n$t ${args}eval q($new);\n$t}' unless defined(\&$name);\n"; 401 } 402 } else { 403 print OUT "unless(defined(\&$name)) {\n sub $name $proto\{\n\t${args}eval q($new);\n }\n}\n"; 404 } 405 %curargs = (); 406 return; 407} 408 409sub expr { 410 $new = '"(assembly code)"' and return if /\b__asm__\b/; # freak out. 411 my $joined_args; 412 if(keys(%curargs)) { 413 $joined_args = join('|', keys(%curargs)); 414 } 415 while ($_ ne '') { 416 s/^\&\&// && do { $new .= " &&"; next;}; # handle && operator 417 s/^\&([\(a-z\)]+)/$1/i; # hack for things that take the address of 418 s/^(\s+)// && do {$new .= ' '; next;}; 419 s/^0X([0-9A-F]+)[UL]*//i 420 && do {my $hex = $1; 421 $hex =~ s/^0+//; 422 if (length $hex > 8 && !$Config{use64bitint}) { 423 # Croak if nv_preserves_uv_bits < 64 ? 424 $new .= hex(substr($hex, -8)) + 425 2**32 * hex(substr($hex, 0, -8)); 426 # The above will produce "errorneus" code 427 # if the hex constant was e.g. inside UINT64_C 428 # macro, but then again, h2ph is an approximation. 429 } else { 430 $new .= lc("0x$hex"); 431 } 432 next;}; 433 s/^(-?\d+\.\d+E[-+]?\d+)[FL]?//i && do {$new .= $1; next;}; 434 s/^(\d+)\s*[LU]*//i && do {$new .= $1; next;}; 435 s/^("(\\"|[^"])*")// && do {$new .= $1; next;}; 436 s/^'((\\"|[^"])*)'// && do { 437 if ($curargs{$1}) { 438 $new .= "ord('\$$1')"; 439 } else { 440 $new .= "ord('$1')"; 441 } 442 next; 443 }; 444 # replace "sizeof(foo)" with "{foo}" 445 # also, remove * (C dereference operator) to avoid perl syntax 446 # problems. Where the %sizeof array comes from is anyone's 447 # guess (c2ph?), but this at least avoids fatal syntax errors. 448 # Behavior is undefined if sizeof() delimiters are unbalanced. 449 # This code was modified to able to handle constructs like this: 450 # sizeof(*(p)), which appear in the HP-UX 10.01 header files. 451 s/^sizeof\s*\(// && do { 452 $new .= '$sizeof'; 453 my $lvl = 1; # already saw one open paren 454 # tack { on the front, and skip it in the loop 455 $_ = "{" . "$_"; 456 my $index = 1; 457 # find balanced closing paren 458 while ($index <= length($_) && $lvl > 0) { 459 $lvl++ if substr($_, $index, 1) eq "("; 460 $lvl-- if substr($_, $index, 1) eq ")"; 461 $index++; 462 } 463 # tack } on the end, replacing ) 464 substr($_, $index - 1, 1) = "}"; 465 # remove pesky * operators within the sizeof argument 466 substr($_, 0, $index - 1) =~ s/\*//g; 467 next; 468 }; 469 # Eliminate typedefs 470 /\(([\w\s]+)[\*\s]*\)\s*[\w\(]/ && do { 471 my $doit = 1; 472 foreach (split /\s+/, $1) { # Make sure all the words are types, 473 unless($isatype{$_} or $_ eq 'struct' or $_ eq 'union'){ 474 $doit = 0; 475 last; 476 } 477 } 478 if( $doit ){ 479 s/\([\w\s]+[\*\s]*\)// && next; # then eliminate them. 480 } 481 }; 482 # struct/union member, including arrays: 483 s/^([_A-Z]\w*(\[[^\]]+\])?((\.|->)[_A-Z]\w*(\[[^\]]+\])?)+)//i && do { 484 my $id = $1; 485 $id =~ s/(\.|(->))([^\.\-]*)/->\{$3\}/g; 486 $id =~ s/\b([^\$])($joined_args)/$1\$$2/g if length($joined_args); 487 while($id =~ /\[\s*([^\$\&\d\]]+)\]/) { 488 my($index) = $1; 489 $index =~ s/\s//g; 490 if(exists($curargs{$index})) { 491 $index = "\$$index"; 492 } else { 493 $index = "&$index"; 494 } 495 $id =~ s/\[\s*([^\$\&\d\]]+)\]/[$index]/; 496 } 497 $new .= " (\$$id)"; 498 }; 499 s/^([_a-zA-Z]\w*)// && do { 500 my $id = $1; 501 if ($id eq 'struct' || $id eq 'union') { 502 s/^\s+(\w+)//; 503 $id .= ' ' . $1; 504 $isatype{$id} = 1; 505 } elsif ($id =~ /^((un)?signed)|(long)|(short)$/) { 506 while (s/^\s+(\w+)//) { $id .= ' ' . $1; } 507 $isatype{$id} = 1; 508 } 509 if ($curargs{$id}) { 510 $new .= "\$$id"; 511 $new .= '->' if /^[\[\{]/; 512 } elsif ($id eq 'defined') { 513 $new .= 'defined'; 514 } elsif (/^\s*\(/) { 515 s/^\s*\((\w),/("$1",/ if $id =~ /^_IO[WR]*$/i; # cheat 516 $new .= " &$id"; 517 } elsif ($isatype{$id}) { 518 if ($new =~ /\{\s*$/) { 519 $new .= "'$id'"; 520 } elsif ($new =~ /\(\s*$/ && /^[\s*]*\)/) { 521 $new =~ s/\(\s*$//; 522 s/^[\s*]*\)//; 523 } else { 524 $new .= q(').$id.q('); 525 } 526 } else { 527 if ($inif) { 528 if ($new =~ /defined\s*$/) { 529 $new .= '(&' . $id . ')'; 530 } elsif ($new =~ /defined\s*\($/) { 531 $new .= '&' . $id; 532 } else { 533 $new .= '(defined(&' . $id . ') ? &' . $id . ' : undef)'; 534 } 535 } elsif (/^\[/) { 536 $new .= " \$$id"; 537 } else { 538 $new .= ' &' . $id; 539 } 540 } 541 next; 542 }; 543 s/^(.)// && do { if ($1 ne '#') { $new .= $1; } next;}; 544 } 545} 546 547 548sub next_line 549{ 550 my $file = shift; 551 my ($in, $out); 552 my $pre_sub_tri_graphs = 1; 553 554 READ: while (not eof IN) { 555 $in .= <IN>; 556 chomp $in; 557 next unless length $in; 558 559 while (length $in) { 560 if ($pre_sub_tri_graphs) { 561 # Preprocess all tri-graphs 562 # including things stuck in quoted string constants. 563 $in =~ s/\?\?=/#/g; # | ??=| #| 564 $in =~ s/\?\?\!/|/g; # | ??!| || 565 $in =~ s/\?\?'/^/g; # | ??'| ^| 566 $in =~ s/\?\?\(/[/g; # | ??(| [| 567 $in =~ s/\?\?\)/]/g; # | ??)| ]| 568 $in =~ s/\?\?\-/~/g; # | ??-| ~| 569 $in =~ s/\?\?\//\\/g; # | ??/| \| 570 $in =~ s/\?\?</{/g; # | ??<| {| 571 $in =~ s/\?\?>/}/g; # | ??>| }| 572 } 573 if ($in =~ s/^\#ifdef __LANGUAGE_PASCAL__//) { 574 # Tru64 disassembler.h evilness: mixed C and Pascal. 575 while (<IN>) { 576 last if /^\#endif/; 577 } 578 $in = ""; 579 next READ; 580 } 581 # Skip inlined functions in headers 582 if ($in =~ s/^(extern|static) (__inline__|inline) .*[^;]\s*$//) { 583 while (<IN>) { 584 last if /^}/; 585 } 586 $in = ""; 587 next READ; 588 } 589 if ($in =~ s/\\$//) { # \-newline 590 $out .= ' '; 591 next READ; 592 } elsif ($in =~ s/^([^"'\\\/]+)//) { # Passthrough 593 $out .= $1; 594 } elsif ($in =~ s/^(\\.)//) { # \... 595 $out .= $1; 596 } elsif ($in =~ /^'/) { # '... 597 if ($in =~ s/^('(\\.|[^'\\])*')//) { 598 $out .= $1; 599 } else { 600 next READ; 601 } 602 } elsif ($in =~ /^"/) { # "... 603 if ($in =~ s/^("(\\.|[^"\\])*")//) { 604 $out .= $1; 605 } else { 606 next READ; 607 } 608 } elsif ($in =~ s/^\/\/.*//) { # //... 609 # fall through 610 } elsif ($in =~ m/^\/\*/) { # /*... 611 # C comment removal adapted from perlfaq6: 612 if ($in =~ s/^\/\*[^*]*\*+([^\/*][^*]*\*+)*\///) { 613 $out .= ' '; 614 } else { # Incomplete /* */ 615 next READ; 616 } 617 } elsif ($in =~ s/^(\/)//) { # /... 618 $out .= $1; 619 } elsif ($in =~ s/^([^\'\"\\\/]+)//) { 620 $out .= $1; 621 } elsif ($^O eq 'linux' && 622 $file =~ m!(?:^|/)linux/byteorder/pdp_endian\.h$! && 623 $in =~ s!\'T KNOW!!) { 624 $out =~ s!I DON$!I_DO_NOT_KNOW!; 625 } else { 626 if ($opt_e) { 627 warn "Cannot parse $file:\n$in\n"; 628 $bad_file{$file} = 1; 629 $in = ''; 630 $out = undef; 631 last READ; 632 } else { 633 die "Cannot parse:\n$in\n"; 634 } 635 } 636 } 637 638 last READ if $out =~ /\S/; 639 } 640 641 return $out; 642} 643 644 645# Handle recursive subdirectories without getting a grotesquely big stack. 646# Could this be implemented using File::Find? 647sub next_file 648{ 649 my $file; 650 651 while (@ARGV) { 652 $file = shift @ARGV; 653 654 if ($file eq '-' or -f $file or -l $file) { 655 return $file; 656 } elsif (-d $file) { 657 if ($opt_r) { 658 expand_glob($file); 659 } else { 660 print STDERR "Skipping directory `$file'\n"; 661 } 662 } elsif ($opt_a) { 663 return $file; 664 } else { 665 print STDERR "Skipping `$file': not a file or directory\n"; 666 } 667 } 668 669 return undef; 670} 671 672 673# Put all the files in $directory into @ARGV for processing. 674sub expand_glob 675{ 676 my ($directory) = @_; 677 678 $directory =~ s:/$::; 679 680 opendir DIR, $directory; 681 foreach (readdir DIR) { 682 next if ($_ eq '.' or $_ eq '..'); 683 684 # expand_glob() is going to be called until $ARGV[0] isn't a 685 # directory; so push directories, and unshift everything else. 686 if (-d "$directory/$_") { push @ARGV, "$directory/$_" } 687 else { unshift @ARGV, "$directory/$_" } 688 } 689 closedir DIR; 690} 691 692 693# Given $file, a symbolic link to a directory in the C include directory, 694# make an equivalent symbolic link in $Dest_dir, if we can figure out how. 695# Otherwise, just duplicate the file or directory. 696sub link_if_possible 697{ 698 my ($dirlink) = @_; 699 my $target = eval 'readlink($dirlink)'; 700 701 if ($target =~ m:^\.\./: or $target =~ m:^/:) { 702 # The target of a parent or absolute link could leave the $Dest_dir 703 # hierarchy, so let's put all of the contents of $dirlink (actually, 704 # the contents of $target) into @ARGV; as a side effect down the 705 # line, $dirlink will get created as an _actual_ directory. 706 expand_glob($dirlink); 707 } else { 708 if (-l "$Dest_dir/$dirlink") { 709 unlink "$Dest_dir/$dirlink" or 710 print STDERR "Could not remove link $Dest_dir/$dirlink: $!\n"; 711 } 712 713 if (eval 'symlink($target, "$Dest_dir/$dirlink")') { 714 print "Linking $target -> $Dest_dir/$dirlink\n"; 715 716 # Make sure that the link _links_ to something: 717 if (! -e "$Dest_dir/$target") { 718 mkpath("$Dest_dir/$target", 0755) or 719 print STDERR "Could not create $Dest_dir/$target/\n"; 720 } 721 } else { 722 print STDERR "Could not symlink $target -> $Dest_dir/$dirlink: $!\n"; 723 } 724 } 725} 726 727 728# Push all #included files in $file onto our stack, except for STDIN 729# and files we've already processed. 730sub queue_includes_from 731{ 732 my ($file) = @_; 733 my $line; 734 735 return if ($file eq "-"); 736 737 open HEADER, $file or return; 738 while (defined($line = <HEADER>)) { 739 while (/\\$/) { # Handle continuation lines 740 chop $line; 741 $line .= <HEADER>; 742 } 743 744 if ($line =~ /^#\s*include\s+([<"])(.*?)[>"]/) { 745 my ($delimiter, $new_file) = ($1, $2); 746 # copy the prefix in the quote syntax (#include "x.h") case 747 if ($delimiter eq q{"} && $file =~ m|^(.*)/|) { 748 $new_file = "$1/$new_file"; 749 } 750 push(@ARGV, $new_file) unless $Is_converted{$new_file}; 751 } 752 } 753 close HEADER; 754} 755 756 757# Determine include directories; $Config{usrinc} should be enough for (all 758# non-GCC?) C compilers, but gcc uses additional include directories. 759sub inc_dirs 760{ 761 my $from_gcc = `LC_ALL=C $Config{cc} -v 2>&1`; 762 if( !( $from_gcc =~ s:^Reading specs from (.*?)/specs\b.*:$1/include:s ) ) 763 { # gcc-4+ : 764 $from_gcc = `LC_ALL=C $Config{cc} -print-search-dirs 2>&1`; 765 if ( !($from_gcc =~ s/^install:\s*([^\s]+[^\s\/])([\s\/]*).*$/$1\/include/s) ) 766 { 767 $from_gcc = ''; 768 }; 769 }; 770 length($from_gcc) ? ($from_gcc, $from_gcc . "-fixed", $Config{usrinc}) : ($Config{usrinc}); 771} 772 773 774# Create "_h2ph_pre.ph", if it doesn't exist or was built by a different 775# version of h2ph. 776sub build_preamble_if_necessary 777{ 778 # Increment $VERSION every time this function is modified: 779 my $VERSION = 2; 780 my $preamble = "$Dest_dir/_h2ph_pre.ph"; 781 782 # Can we skip building the preamble file? 783 if (-r $preamble) { 784 # Extract version number from first line of preamble: 785 open PREAMBLE, $preamble or die "Cannot open $preamble: $!"; 786 my $line = <PREAMBLE>; 787 $line =~ /(\b\d+\b)/; 788 close PREAMBLE or die "Cannot close $preamble: $!"; 789 790 # Don't build preamble if a compatible preamble exists: 791 return if $1 == $VERSION; 792 } 793 794 my (%define) = _extract_cc_defines(); 795 796 open PREAMBLE, ">$preamble" or die "Cannot open $preamble: $!"; 797 print PREAMBLE "# This file was created by h2ph version $VERSION\n"; 798 799 foreach (sort keys %define) { 800 if ($opt_D) { 801 print PREAMBLE "# $_=$define{$_}\n"; 802 } 803 if ($define{$_} =~ /^\((.*)\)$/) { 804 # parenthesized value: d=(v) 805 $define{$_} = $1; 806 } 807 if ($define{$_} =~ /^([+-]?(\d+)?\.\d+([eE][+-]?\d+)?)[FL]?$/) { 808 # float: 809 print PREAMBLE 810 "unless (defined &$_) { sub $_() { $1 } }\n\n"; 811 } elsif ($define{$_} =~ /^([+-]?\d+)U?L{0,2}$/i) { 812 # integer: 813 print PREAMBLE 814 "unless (defined &$_) { sub $_() { $1 } }\n\n"; 815 } elsif ($define{$_} =~ /^\w+$/) { 816 print PREAMBLE 817 "unless (defined &$_) { sub $_() { &$define{$_} } }\n\n"; 818 } else { 819 print PREAMBLE 820 "unless (defined &$_) { sub $_() { \"", 821 quotemeta($define{$_}), "\" } }\n\n"; 822 } 823 } 824 print PREAMBLE "\n1;\n"; # avoid 'did not return a true value' when empty 825 close PREAMBLE or die "Cannot close $preamble: $!"; 826} 827 828 829# %Config contains information on macros that are pre-defined by the 830# system's compiler. We need this information to make the .ph files 831# function with perl as the .h files do with cc. 832sub _extract_cc_defines 833{ 834 my %define; 835 my $allsymbols = join " ", 836 @Config{'ccsymbols', 'cppsymbols', 'cppccsymbols'}; 837 838 # Split compiler pre-definitions into `key=value' pairs: 839 while ($allsymbols =~ /([^\s]+)=((\\\s|[^\s])+)/g) { 840 $define{$1} = $2; 841 if ($opt_D) { 842 print STDERR "$_: $1 -> $2\n"; 843 } 844 } 845 846 return %define; 847} 848 849 8501; 851 852############################################################################## 853__END__ 854 855=head1 NAME 856 857h2ph - convert .h C header files to .ph Perl header files 858 859=head1 SYNOPSIS 860 861B<h2ph [-d destination directory] [-r | -a] [-l] [headerfiles]> 862 863=head1 DESCRIPTION 864 865I<h2ph> 866converts any C header files specified to the corresponding Perl header file 867format. 868It is most easily run while in /usr/include: 869 870 cd /usr/include; h2ph * sys/* 871 872or 873 874 cd /usr/include; h2ph * sys/* arpa/* netinet/* 875 876or 877 878 cd /usr/include; h2ph -r -l . 879 880The output files are placed in the hierarchy rooted at Perl's 881architecture dependent library directory. You can specify a different 882hierarchy with a B<-d> switch. 883 884If run with no arguments, filters standard input to standard output. 885 886=head1 OPTIONS 887 888=over 4 889 890=item -d destination_dir 891 892Put the resulting B<.ph> files beneath B<destination_dir>, instead of 893beneath the default Perl library location (C<$Config{'installsitearch'}>). 894 895=item -r 896 897Run recursively; if any of B<headerfiles> are directories, then run I<h2ph> 898on all files in those directories (and their subdirectories, etc.). B<-r> 899and B<-a> are mutually exclusive. 900 901=item -a 902 903Run automagically; convert B<headerfiles>, as well as any B<.h> files 904which they include. This option will search for B<.h> files in all 905directories which your C compiler ordinarily uses. B<-a> and B<-r> are 906mutually exclusive. 907 908=item -l 909 910Symbolic links will be replicated in the destination directory. If B<-l> 911is not specified, then links are skipped over. 912 913=item -h 914 915Put ``hints'' in the .ph files which will help in locating problems with 916I<h2ph>. In those cases when you B<require> a B<.ph> file containing syntax 917errors, instead of the cryptic 918 919 [ some error condition ] at (eval mmm) line nnn 920 921you will see the slightly more helpful 922 923 [ some error condition ] at filename.ph line nnn 924 925However, the B<.ph> files almost double in size when built using B<-h>. 926 927=item -D 928 929Include the code from the B<.h> file as a comment in the B<.ph> file. 930This is primarily used for debugging I<h2ph>. 931 932=item -Q 933 934``Quiet'' mode; don't print out the names of the files being converted. 935 936=back 937 938=head1 ENVIRONMENT 939 940No environment variables are used. 941 942=head1 FILES 943 944 /usr/include/*.h 945 /usr/include/sys/*.h 946 947etc. 948 949=head1 AUTHOR 950 951Larry Wall 952 953=head1 SEE ALSO 954 955perl(1) 956 957=head1 DIAGNOSTICS 958 959The usual warnings if it can't read or write the files involved. 960 961=head1 BUGS 962 963Doesn't construct the %sizeof array for you. 964 965It doesn't handle all C constructs, but it does attempt to isolate 966definitions inside evals so that you can get at the definitions 967that it can translate. 968 969It's only intended as a rough tool. 970You may need to dicker with the files produced. 971 972You have to run this program by hand; it's not run as part of the Perl 973installation. 974 975Doesn't handle complicated expressions built piecemeal, a la: 976 977 enum { 978 FIRST_VALUE, 979 SECOND_VALUE, 980 #ifdef ABC 981 THIRD_VALUE 982 #endif 983 }; 984 985Doesn't necessarily locate all of your C compiler's internally-defined 986symbols. 987 988=cut 989 990!NO!SUBS! 991 992close OUT or die "Can't close $file: $!"; 993chmod 0755, $file or die "Can't reset permissions for $file: $!\n"; 994exec("$Config{'eunicefix'} $file") if $Config{'eunicefix'} ne ':'; 995chdir $origdir; 996